@hanna84/mcp-writing 2.9.1 → 2.9.5

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/index.js CHANGED
@@ -12,10 +12,10 @@ import matter from "gray-matter";
12
12
  import yaml from "js-yaml";
13
13
  import { z } from "zod";
14
14
  import { openDb } from "./db.js";
15
- import { syncAll, isSyncDirWritable, getSyncOwnershipDiagnostics, getFileWriteDiagnostics, writeMeta, readMeta, indexSceneFile, normalizeSceneMetaForPath, sidecarPath, isStructuralProjectId } from "./sync.js";
15
+ import { syncAll, isSyncDirWritable, getSyncOwnershipDiagnostics, getFileWriteDiagnostics, readMeta, indexSceneFile, sidecarPath, isStructuralProjectId } from "./sync.js";
16
16
  import { isGitAvailable, isGitRepository, initGitRepository, createSnapshot, listSnapshots, getSceneProseAtCommit, getHeadCommitHash } from "./git.js";
17
17
  import { renderCharacterArcTemplate, renderCharacterSheetTemplate, renderPlaceSheetTemplate, slugifyEntityName } from "./world-entity-templates.js";
18
- import { importScrivenerSync, validateProjectId, validateUniverseId } from "./importer.js";
18
+ import { validateProjectId } from "./importer.js";
19
19
  import { ASYNC_PROGRESS_PREFIX } from "./async-progress.js";
20
20
  import {
21
21
  STYLEGUIDE_CONFIG_BASENAME,
@@ -43,6 +43,9 @@ import {
43
43
  buildReviewBundlePlan,
44
44
  createReviewBundleArtifacts,
45
45
  } from "./review-bundles.js";
46
+ import { registerSyncTools } from "./tools/sync.js";
47
+ import { registerSearchTools } from "./tools/search.js";
48
+ import { registerMetadataTools } from "./tools/metadata.js";
46
49
 
47
50
  const SYNC_DIR = process.env.WRITING_SYNC_DIR ?? "./sync";
48
51
  const DB_PATH = process.env.DB_PATH ?? "./writing.db";
@@ -700,9 +703,8 @@ if (GIT_AVAILABLE && SYNC_DIR_WRITABLE) {
700
703
 
701
704
  // In-memory storage for pending edit proposals (Phase 3)
702
705
  const pendingProposals = new Map();
703
- let nextProposalId = 1;
704
706
  function generateProposalId() {
705
- return `proposal-${nextProposalId++}`;
707
+ return `proposal-${randomUUID()}`;
706
708
  }
707
709
 
708
710
  function getRuntimeDiagnostics() {
@@ -1012,524 +1014,39 @@ function createMcpServer() {
1012
1014
  }
1013
1015
  );
1014
1016
 
1015
- // ---- sync ----------------------------------------------------------------
1016
- s.tool("sync", "Re-scan the sync folder and update the scene/character/place index from disk. Call this after making edits in Scrivener or updating sidecar files outside the MCP.", {}, async () => {
1017
- const result = syncAll(db, SYNC_DIR, { writable: SYNC_DIR_WRITABLE });
1018
- const parts = [`Sync complete. ${result.indexed} scenes indexed. ${result.staleMarked} scenes marked stale.`];
1019
- if (result.sidecarsMigrated) parts.push(`${result.sidecarsMigrated} sidecar(s) auto-generated from frontmatter.`);
1020
- if (result.skipped) parts.push(`${result.skipped} file(s) skipped (no scene_id).`);
1021
- if (result.skipped) parts.push(`Tip: for raw Scrivener Draft exports, run scripts/import.js first, then run sync again.`);
1022
- const summary = result.warningSummary;
1023
- const summaryEntries = Object.entries(summary);
1024
- if (summaryEntries.length) {
1025
- const lines = summaryEntries.map(([type, entry]) => `- ${type}: ${entry.count} (e.g. ${entry.examples[0]})`);
1026
- parts.push(`\n⚠️ Warning summary:\n` + lines.join("\n"));
1027
- }
1028
- return { content: [{ type: "text", text: parts.join(" ") }] };
1029
- });
1030
-
1031
- // ---- import_scrivener_sync ----------------------------------------------
1032
- s.tool(
1033
- "import_scrivener_sync",
1034
- "[STABLE] Import Scrivener External Folder Sync Draft files into this server's WRITING_SYNC_DIR by generating scene sidecars and reconciling by Scrivener binder ID. This is the recommended default path for first-time setup before sync().",
1035
- {
1036
- source_dir: z.string().describe("Path to Scrivener external sync folder (the folder that contains Draft/, or Draft/ itself)."),
1037
- project_id: z.string().optional().describe("Project ID override (e.g. 'the-lamb'). Defaults to a slug derived from WRITING_SYNC_DIR."),
1038
- dry_run: z.boolean().optional().describe("If true, reports planned writes without changing files."),
1039
- auto_sync: z.boolean().optional().describe("If true (default), runs sync() after import when not dry-run."),
1040
- preflight: z.boolean().optional().describe("If true, returns a list of files that would be processed without doing any work. Use to verify scope before a large import."),
1041
- ignore_patterns: z.array(z.string()).optional().describe("Array of regex patterns matched against filenames. Files matching any pattern are excluded from import. Useful to skip fragments, beat-sheet notes, or feedback files."),
1042
- },
1043
- async ({ source_dir, project_id, dry_run = false, auto_sync = true, preflight = false, ignore_patterns = [] }) => {
1044
- if (project_id !== undefined) {
1045
- const projectIdCheck = validateProjectId(project_id);
1046
- if (!projectIdCheck.ok) {
1047
- return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1048
- }
1049
- }
1050
-
1051
- const ignorePatternCheck = validateRegexPatterns(ignore_patterns);
1052
- if (!ignorePatternCheck.ok) {
1053
- return errorResponse(
1054
- "INVALID_IGNORE_PATTERN",
1055
- `Invalid ignore pattern '${ignorePatternCheck.pattern}': ${ignorePatternCheck.reason}`,
1056
- {
1057
- source_dir,
1058
- sync_dir: SYNC_DIR_ABS,
1059
- project_id: project_id ?? null,
1060
- pattern: ignorePatternCheck.pattern,
1061
- }
1062
- );
1063
- }
1064
-
1065
- if (!dry_run && !SYNC_DIR_WRITABLE) {
1066
- return errorResponse(
1067
- "SYNC_DIR_NOT_WRITABLE",
1068
- "Cannot import because WRITING_SYNC_DIR is not writable in this runtime.",
1069
- { sync_dir: SYNC_DIR_ABS }
1070
- );
1071
- }
1072
-
1073
- let importResult;
1074
- try {
1075
- importResult = importScrivenerSync({
1076
- scrivenerDir: source_dir,
1077
- mcpSyncDir: SYNC_DIR,
1078
- projectId: project_id,
1079
- dryRun: Boolean(dry_run) || preflight,
1080
- preflight: Boolean(preflight),
1081
- ignorePatterns: ignore_patterns,
1082
- });
1083
- } catch (error) {
1084
- if (error && typeof error === "object" && error.code === "INVALID_IGNORE_PATTERN") {
1085
- return errorResponse(
1086
- "INVALID_IGNORE_PATTERN",
1087
- error instanceof Error ? error.message : "Invalid ignore pattern.",
1088
- {
1089
- source_dir,
1090
- sync_dir: SYNC_DIR_ABS,
1091
- project_id: project_id ?? null,
1092
- pattern: error.pattern ?? null,
1093
- }
1094
- );
1095
- }
1096
- return errorResponse(
1097
- "IMPORT_FAILED",
1098
- error instanceof Error ? error.message : "Import failed.",
1099
- {
1100
- source_dir,
1101
- sync_dir: SYNC_DIR_ABS,
1102
- project_id: project_id ?? null,
1103
- }
1104
- );
1105
- }
1106
-
1107
- let syncResult = null;
1108
- if (!dry_run && !preflight && auto_sync) {
1109
- syncResult = syncAll(db, SYNC_DIR, { writable: SYNC_DIR_WRITABLE });
1110
- }
1111
-
1112
- return jsonResponse({
1113
- ok: true,
1114
- import: {
1115
- source_dir: importResult.scrivenerDir,
1116
- sync_dir: importResult.mcpSyncDir,
1117
- scenes_dir: importResult.scenesDir,
1118
- project_id: importResult.projectId,
1119
- preflight: importResult.preflight,
1120
- source_files: importResult.sourceFiles,
1121
- ignored_files: importResult.ignoredFiles,
1122
- ...(importResult.preflight ? {
1123
- files_to_process: importResult.filesToProcess,
1124
- file_previews: importResult.filePreviews,
1125
- existing_sidecars: importResult.existingSidecars,
1126
- } : {}),
1127
- created: importResult.created,
1128
- existing: importResult.existing,
1129
- skipped: importResult.skipped,
1130
- beat_markers_seen: importResult.beatMarkersSeen,
1131
- dry_run: importResult.dryRun,
1132
- },
1133
- sync: syncResult
1134
- ? {
1135
- indexed: syncResult.indexed,
1136
- stale_marked: syncResult.staleMarked,
1137
- sidecars_migrated: syncResult.sidecarsMigrated,
1138
- skipped: syncResult.skipped,
1139
- warning_summary: syncResult.warningSummary,
1140
- }
1141
- : null,
1142
- next_step: preflight
1143
- ? "Preflight complete. Review file_previews and ignored_files, then re-run without preflight=true."
1144
- : dry_run
1145
- ? "Dry run complete. Re-run with dry_run=false to write files."
1146
- : auto_sync
1147
- ? "Import and sync complete."
1148
- : "Import complete. Run sync() to index imported scenes.",
1149
- });
1150
- }
1151
- );
1152
-
1153
- // ---- async import/merge jobs --------------------------------------------
1154
- s.tool(
1155
- "import_scrivener_sync_async",
1156
- "[STABLE] Start an asynchronous Scrivener External Folder Sync import job. This is the recommended default import path when the sync tree is large. Returns immediately with a job_id to poll via get_async_job_status.",
1157
- {
1158
- source_dir: z.string().describe("Path to Scrivener external sync folder (the folder that contains Draft/, or Draft/ itself)."),
1159
- project_id: z.string().optional().describe("Project ID override (e.g. 'the-lamb' or 'universe-1/book-1-the-lamb')."),
1160
- dry_run: z.boolean().optional().describe("If true, reports planned writes without changing files."),
1161
- auto_sync: z.boolean().optional().describe("If true, runs sync() after a non-dry-run async import finishes."),
1162
- preflight: z.boolean().optional().describe("If true, returns a list of files that would be processed without doing any work."),
1163
- ignore_patterns: z.array(z.string()).optional().describe("Array of regex patterns matched against filenames. Files matching any pattern are excluded from import."),
1164
- },
1165
- async ({ source_dir, project_id, dry_run = false, auto_sync = false, preflight = false, ignore_patterns = [] }) => {
1166
- if (project_id !== undefined) {
1167
- const projectIdCheck = validateProjectId(project_id);
1168
- if (!projectIdCheck.ok) {
1169
- return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1170
- }
1171
- }
1172
-
1173
- const ignorePatternCheck = validateRegexPatterns(ignore_patterns);
1174
- if (!ignorePatternCheck.ok) {
1175
- return errorResponse(
1176
- "INVALID_IGNORE_PATTERN",
1177
- `Invalid ignore pattern '${ignorePatternCheck.pattern}': ${ignorePatternCheck.reason}`,
1178
- {
1179
- source_dir,
1180
- sync_dir: SYNC_DIR_ABS,
1181
- project_id: project_id ?? null,
1182
- pattern: ignorePatternCheck.pattern,
1183
- }
1184
- );
1185
- }
1186
-
1187
- if (!dry_run && !preflight && !SYNC_DIR_WRITABLE) {
1188
- return errorResponse(
1189
- "SYNC_DIR_NOT_WRITABLE",
1190
- "Cannot import because WRITING_SYNC_DIR is not writable in this runtime.",
1191
- { sync_dir: SYNC_DIR_ABS }
1192
- );
1193
- }
1194
-
1195
- const job = startAsyncJob({
1196
- kind: "import_scrivener_sync",
1197
- requestPayload: {
1198
- kind: "import_scrivener_sync",
1199
- args: {
1200
- source_dir,
1201
- project_id,
1202
- dry_run: Boolean(dry_run),
1203
- preflight: Boolean(preflight),
1204
- ignore_patterns,
1205
- },
1206
- context: {
1207
- sync_dir: SYNC_DIR,
1208
- },
1209
- },
1210
- onComplete: (completedJob) => {
1211
- if (!auto_sync || dry_run || preflight || completedJob.status !== "completed") return;
1212
- const syncResult = syncAll(db, SYNC_DIR, { writable: SYNC_DIR_WRITABLE });
1213
- if (completedJob.result && completedJob.result.ok) {
1214
- completedJob.result.sync = {
1215
- indexed: syncResult.indexed,
1216
- stale_marked: syncResult.staleMarked,
1217
- sidecars_migrated: syncResult.sidecarsMigrated,
1218
- skipped: syncResult.skipped,
1219
- warning_summary: syncResult.warningSummary,
1220
- };
1221
- }
1222
- },
1223
- });
1224
-
1225
- return jsonResponse({
1226
- ok: true,
1227
- async: true,
1228
- job: toPublicJob(job, false),
1229
- next_step: "Call get_async_job_status with job_id until status is 'completed' or 'failed'.",
1230
- });
1231
- }
1232
- );
1233
-
1234
- s.tool(
1235
- "merge_scrivener_project_beta",
1236
- "Merge metadata directly from a Scrivener .scriv project into existing scene sidecars by starting a background job. This path is opt-in and requires sidecars to already exist (for example, from import_scrivener_sync). Returns immediately with a job_id to poll via get_async_job_status.",
1237
- {
1238
- source_project_dir: z.string().describe("Path to a Scrivener .scriv bundle directory."),
1239
- project_id: z.string().optional().describe("Project ID containing existing sidecars (e.g. 'the-lamb' or 'universe-1/book-1-the-lamb')."),
1240
- scenes_dir: z.string().optional().describe("Absolute path to the scenes directory containing .meta.yaml sidecars. Overrides the path derived from project_id."),
1241
- dry_run: z.boolean().optional().describe("If true (default), reports planned merges without writing files."),
1242
- auto_sync: z.boolean().optional().describe("If true, runs sync() after a non-dry-run async merge finishes."),
1243
- organize_by_chapters: z.boolean().optional().describe("If true (default false), relocate scene files into chapter-based folder hierarchies. Chapter metadata is always extracted to sidecars."),
1244
- },
1245
- async ({ source_project_dir, project_id, scenes_dir, dry_run = true, auto_sync = false, organize_by_chapters = false }) => {
1246
- if (project_id !== undefined) {
1247
- const projectIdCheck = validateProjectId(project_id);
1248
- if (!projectIdCheck.ok) {
1249
- return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1250
- }
1251
- }
1252
-
1253
- if (!dry_run && !SYNC_DIR_WRITABLE) {
1254
- return errorResponse(
1255
- "SYNC_DIR_NOT_WRITABLE",
1256
- "Cannot merge Scrivener metadata because WRITING_SYNC_DIR is not writable in this runtime.",
1257
- { sync_dir: SYNC_DIR_ABS }
1258
- );
1259
- }
1260
-
1261
- const resolvedScenesDir = scenes_dir
1262
- ?? (project_id ? path.join(resolveProjectRoot(project_id), "scenes") : undefined);
1263
- const normalizedScenesDir = resolvedScenesDir ? path.resolve(resolvedScenesDir) : undefined;
1264
-
1265
- if (normalizedScenesDir) {
1266
- if (!isPathInsideSyncDir(normalizedScenesDir)) {
1267
- return errorResponse(
1268
- "INVALID_SCENES_DIR",
1269
- "scenes_dir must be inside WRITING_SYNC_DIR.",
1270
- { scenes_dir: normalizedScenesDir, sync_dir: SYNC_DIR_ABS, sync_dir_real: SYNC_DIR_REAL }
1271
- );
1272
- }
1273
- }
1274
-
1275
- const job = startAsyncJob({
1276
- kind: "merge_scrivener_project_beta",
1277
- requestPayload: {
1278
- kind: "merge_scrivener_project_beta",
1279
- args: {
1280
- source_project_dir,
1281
- project_id,
1282
- scenes_dir: normalizedScenesDir,
1283
- dry_run: Boolean(dry_run),
1284
- organize_by_chapters: Boolean(organize_by_chapters),
1285
- },
1286
- context: {
1287
- sync_dir: SYNC_DIR,
1288
- },
1289
- },
1290
- onComplete: (completedJob) => {
1291
- if (!auto_sync || dry_run || completedJob.status !== "completed") return;
1292
- const syncResult = syncAll(db, SYNC_DIR, { writable: SYNC_DIR_WRITABLE });
1293
- if (completedJob.result && completedJob.result.ok) {
1294
- completedJob.result.sync = {
1295
- indexed: syncResult.indexed,
1296
- stale_marked: syncResult.staleMarked,
1297
- sidecars_migrated: syncResult.sidecarsMigrated,
1298
- skipped: syncResult.skipped,
1299
- warning_summary: syncResult.warningSummary,
1300
- };
1301
- }
1302
- },
1303
- });
1304
-
1305
- return jsonResponse({
1306
- ok: true,
1307
- async: true,
1308
- job: toPublicJob(job, false),
1309
- next_step: "Call get_async_job_status with job_id until status is 'completed' or 'failed'.",
1310
- });
1311
- }
1312
- );
1313
-
1314
- s.tool(
1315
- "enrich_scene_characters_batch",
1316
- "Start an asynchronous batch job that infers scene character mentions and updates scene metadata links. Version 1 uses canonical character names only (no aliases). Defaults to dry_run=true.",
1317
- {
1318
- project_id: z.string().describe("Project ID (e.g. 'the-lamb' or 'universe-1/book-1-the-lamb')."),
1319
- scene_ids: z.array(z.string()).optional().describe("Optional allowlist of scene IDs to process before other filters are applied."),
1320
- part: z.number().int().optional().describe("Optional part number filter."),
1321
- chapter: z.number().int().optional().describe("Optional chapter number filter."),
1322
- only_stale: z.boolean().optional().describe("If true, only process scenes currently marked metadata_stale."),
1323
- dry_run: z.boolean().optional().describe("If true (default), returns preview results without writing sidecars."),
1324
- replace_mode: z.enum(["merge", "replace"]).optional().describe("merge (default): add inferred IDs; replace: overwrite characters with inferred IDs."),
1325
- max_scenes: z.number().int().positive().optional().describe("Hard guardrail for resolved scene count (default: 200)."),
1326
- include_match_details: z.boolean().optional().describe("If true, include extra match diagnostics per scene."),
1327
- confirm_replace: z.boolean().optional().describe("Must be true when replace_mode=replace."),
1328
- },
1329
- async ({
1330
- project_id,
1331
- scene_ids,
1332
- part,
1333
- chapter,
1334
- only_stale = false,
1335
- dry_run = true,
1336
- replace_mode = "merge",
1337
- max_scenes = 200,
1338
- include_match_details = false,
1339
- confirm_replace = false,
1340
- }) => {
1341
- const projectIdCheck = validateProjectId(project_id);
1342
- if (!projectIdCheck.ok) {
1343
- return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1344
- }
1345
-
1346
- if (replace_mode === "replace" && !confirm_replace) {
1347
- return errorResponse(
1348
- "VALIDATION_ERROR",
1349
- "replace_mode=replace requires confirm_replace=true.",
1350
- { replace_mode, confirm_replace }
1351
- );
1352
- }
1353
-
1354
- if (!dry_run && !SYNC_DIR_WRITABLE) {
1355
- return errorResponse(
1356
- "READ_ONLY",
1357
- "Cannot run batch character enrichment in write mode: sync dir is read-only.",
1358
- { sync_dir: SYNC_DIR_ABS }
1359
- );
1360
- }
1361
-
1362
- const characterRows = db.prepare(`
1363
- SELECT character_id, name
1364
- FROM characters
1365
- WHERE project_id = ? OR universe_id = (SELECT universe_id FROM projects WHERE project_id = ?)
1366
- ORDER BY length(name) DESC
1367
- `).all(project_id, project_id);
1368
-
1369
- const targetResolution = resolveBatchTargetScenes(db, {
1370
- projectId: project_id,
1371
- sceneIds: scene_ids,
1372
- part,
1373
- chapter,
1374
- onlyStale: Boolean(only_stale),
1375
- });
1376
- if (!targetResolution.ok) {
1377
- return errorResponse(targetResolution.code, targetResolution.message, targetResolution.details);
1378
- }
1379
-
1380
- const targetScenes = targetResolution.rows;
1381
- const projectExists = targetResolution.project_exists !== false;
1382
- if (targetScenes.length > max_scenes) {
1383
- return errorResponse(
1384
- "VALIDATION_ERROR",
1385
- `Matched ${targetScenes.length} scenes, which exceeds max_scenes=${max_scenes}.`,
1386
- {
1387
- matched_scenes: targetScenes.length,
1388
- max_scenes,
1389
- project_id,
1390
- next_step: maxScenesNextStep(targetScenes.length),
1391
- }
1392
- );
1393
- }
1394
-
1395
- const job = startAsyncJob({
1396
- kind: "enrich_scene_characters_batch",
1397
- requestPayload: {
1398
- kind: "enrich_scene_characters_batch",
1399
- args: {
1400
- project_id,
1401
- dry_run: Boolean(dry_run),
1402
- replace_mode,
1403
- include_match_details: Boolean(include_match_details),
1404
- project_exists: projectExists,
1405
- target_scenes: targetScenes,
1406
- character_rows: characterRows,
1407
- },
1408
- context: { sync_dir: SYNC_DIR },
1409
- },
1410
- onComplete: (completedJob) => {
1411
- if (dry_run || completedJob.status !== "completed" || !completedJob.result?.ok) return;
1412
-
1413
- syncAll(db, SYNC_DIR, { writable: SYNC_DIR_WRITABLE });
1414
-
1415
- const changedScenes = (completedJob.result.results ?? [])
1416
- .filter(row => row.status === "changed")
1417
- .map(row => row.scene_id);
1418
-
1419
- for (const sceneId of changedScenes) {
1420
- db.prepare(`UPDATE scenes SET metadata_stale = 0 WHERE scene_id = ? AND project_id = ?`)
1421
- .run(sceneId, project_id);
1422
- }
1423
- },
1424
- });
1425
-
1426
- return jsonResponse({
1427
- ok: true,
1428
- async: true,
1429
- job: toPublicJob(job, false),
1430
- next_step: "Call get_async_job_status with job_id until status is 'completed', 'failed', or 'cancelled'.",
1431
- });
1432
- }
1433
- );
1434
-
1435
- s.tool(
1436
- "get_async_job_status",
1437
- "Get status and result for an asynchronous job started by async tools such as import_scrivener_sync_async, merge_scrivener_project_beta, or enrich_scene_characters_batch. Use this to poll job progress after receiving a job_id. Common next step: if status is still running, call this tool again; if status is completed inspect result, and if status is failed or cancelled inspect job/result diagnostics.",
1438
- {
1439
- job_id: z.string().describe("Job ID returned by an async start tool."),
1440
- include_result: z.boolean().optional().describe("If true (default), includes completed result payload when available."),
1441
- },
1442
- async ({ job_id, include_result = true }) => {
1443
- pruneAsyncJobs();
1444
- const job = asyncJobs.get(job_id);
1445
- if (!job) {
1446
- return errorResponse("NOT_FOUND", `Async job '${job_id}' was not found. It may have expired. Hint: call list_async_jobs to see currently tracked job IDs.`);
1447
- }
1448
- return jsonResponse({ ok: true, async: true, job: toPublicJob(job, include_result) });
1449
- }
1450
- );
1451
-
1452
- s.tool(
1453
- "list_async_jobs",
1454
- "List asynchronous jobs currently known to this server. Use this when you lost a job_id or need a dashboard view of running/completed jobs. Returns an object envelope containing a jobs array of job objects sorted by newest first.",
1455
- {
1456
- include_results: z.boolean().optional().describe("If true, includes completed result payloads."),
1457
- },
1458
- async ({ include_results = false }) => {
1459
- pruneAsyncJobs();
1460
- const jobs = [...asyncJobs.values()]
1461
- .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
1462
- .map(job => toPublicJob(job, include_results));
1463
- return jsonResponse({ ok: true, async: true, jobs });
1464
- }
1465
- );
1466
-
1467
- s.tool(
1468
- "cancel_async_job",
1469
- "Cancel a running asynchronous job. Use this when an import/merge/batch run was started with overly broad scope or is no longer needed. Returns the updated job state; cancellation is cooperative and may transition through 'cancelling' before 'cancelled'.",
1470
- {
1471
- job_id: z.string().describe("Job ID returned by an async start tool."),
1472
- },
1473
- async ({ job_id }) => {
1474
- pruneAsyncJobs();
1475
- const job = asyncJobs.get(job_id);
1476
- if (!job) {
1477
- return errorResponse("NOT_FOUND", `Async job '${job_id}' was not found. It may have expired. Hint: call list_async_jobs to find active IDs.`);
1478
- }
1479
-
1480
- if (job.status !== "running") {
1481
- return jsonResponse({
1482
- ok: true,
1483
- async: true,
1484
- cancelled: false,
1485
- message: `Job is already ${job.status}.`,
1486
- job: toPublicJob(job, false),
1487
- });
1488
- }
1489
-
1490
- // Guard: if the child has already exited, its exit handler will have
1491
- // set the terminal status. Don't overwrite it.
1492
- const childHasExited = job.child.exitCode !== null || job.child.signalCode !== null;
1493
- if (childHasExited) {
1494
- return jsonResponse({
1495
- ok: true,
1496
- async: true,
1497
- cancelled: false,
1498
- message: "Job is no longer running.",
1499
- job: toPublicJob(job, false),
1500
- });
1501
- }
1502
-
1503
- let signalSent = false;
1504
- try {
1505
- signalSent = job.child.kill("SIGTERM");
1506
- } catch {
1507
- // kill() threw — treat as signal not sent
1508
- }
1509
-
1510
- if (!signalSent) {
1511
- return jsonResponse({
1512
- ok: true,
1513
- async: true,
1514
- cancelled: false,
1515
- message: "Cancellation could not be requested; job may have already finished.",
1516
- job: toPublicJob(job, false),
1517
- });
1518
- }
1519
-
1520
- // Transitional: signal sent but worker has not yet exited.
1521
- // Exit/error handlers will finalise status to "cancelled".
1522
- job.status = "cancelling";
1523
-
1524
- return jsonResponse({
1525
- ok: true,
1526
- async: true,
1527
- cancelled: true,
1528
- message: "Cancellation requested. Poll get_async_job_status until status is 'cancelled'.",
1529
- job: toPublicJob(job, false),
1530
- });
1531
- }
1532
- );
1017
+ // Passed to each tool registration module (tools/*.js) to thread state and
1018
+ // shared helpers without circular imports. Grows as groups are extracted.
1019
+ const toolContext = {
1020
+ db,
1021
+ SYNC_DIR,
1022
+ SYNC_DIR_ABS,
1023
+ SYNC_DIR_REAL,
1024
+ SYNC_DIR_WRITABLE,
1025
+ GIT_ENABLED,
1026
+ asyncJobs,
1027
+ errorResponse,
1028
+ jsonResponse,
1029
+ validateRegexPatterns,
1030
+ startAsyncJob,
1031
+ pruneAsyncJobs,
1032
+ toPublicJob,
1033
+ resolveProjectRoot,
1034
+ resolveBatchTargetScenes,
1035
+ maxScenesNextStep,
1036
+ isPathInsideSyncDir,
1037
+ deriveLoglineFromProse,
1038
+ inferCharacterIdsFromProse,
1039
+ paginateRows,
1040
+ DEFAULT_METADATA_PAGE_SIZE,
1041
+ MAX_CHAPTER_SCENES,
1042
+ getSceneProseAtCommit,
1043
+ readSupportingNotesForEntity,
1044
+ readEntityMetadata,
1045
+ createCanonicalWorldEntity,
1046
+ };
1047
+ registerSyncTools(s, toolContext);
1048
+ registerSearchTools(s, toolContext);
1049
+ registerMetadataTools(s, toolContext);
1533
1050
 
1534
1051
  // ---- get_runtime_config --------------------------------------------------
1535
1052
  s.tool(
@@ -2389,920 +1906,6 @@ function createMcpServer() {
2389
1906
  }
2390
1907
  );
2391
1908
 
2392
- // ---- find_scenes ---------------------------------------------------------
2393
- s.tool(
2394
- "find_scenes",
2395
- "Find scenes by filtering on character, Save the Cat beat, tags, part, chapter, or POV. Returns ordered scene metadata only — no prose. All filters are optional and combinable. Supports pagination via page/page_size and auto-paginates large result sets with total_count. Warns if any matching scenes have stale metadata.",
2396
- {
2397
- project_id: z.string().optional().describe("Project ID (e.g. 'the-lamb'). Use to scope results to one project."),
2398
- character: z.string().optional().describe("A character_id (e.g. 'char-mira-nystrom'). Returns only scenes that character appears in. Use list_characters first to find valid IDs."),
2399
- beat: z.string().optional().describe("Save the Cat beat name (e.g. 'Opening Image'). Exact match."),
2400
- tag: z.string().optional().describe("Scene tag to filter by. Exact match."),
2401
- part: z.number().int().optional().describe("Part number (integer, e.g. 1). Chapters are numbered globally across the whole project."),
2402
- chapter: z.number().int().optional().describe("Chapter number (integer, e.g. 3). Chapters are numbered globally across the whole project — do not reset per part."),
2403
- pov: z.string().optional().describe("POV character_id. Use list_characters first to find valid IDs."),
2404
- page: z.number().int().min(1).optional().describe("Optional page number for paginated responses (1-based)."),
2405
- page_size: z.number().int().min(1).max(200).optional().describe("Optional page size for paginated responses (default: 20, max: 200)."),
2406
- },
2407
- async ({ project_id, character, beat, tag, part, chapter, pov, page, page_size }) => {
2408
- let query = `
2409
- SELECT DISTINCT s.scene_id, s.project_id, s.title, s.part, s.chapter, s.chapter_title, s.pov,
2410
- s.logline, s.scene_change, s.causality, s.stakes, s.scene_functions,
2411
- s.save_the_cat_beat, s.timeline_position, s.story_time,
2412
- s.word_count, s.metadata_stale
2413
- FROM scenes s
2414
- `;
2415
- const joins = [];
2416
- const conditions = [];
2417
- const params = [];
2418
-
2419
- if (character) {
2420
- joins.push(`JOIN scene_characters sc ON sc.scene_id = s.scene_id AND sc.character_id = ?`);
2421
- params.push(character);
2422
- }
2423
- if (tag) {
2424
- joins.push(`JOIN scene_tags st ON st.scene_id = s.scene_id AND st.tag = ?`);
2425
- params.push(tag);
2426
- }
2427
- if (project_id) { conditions.push(`s.project_id = ?`); params.push(project_id); }
2428
- if (beat) { conditions.push(`s.save_the_cat_beat = ?`); params.push(beat); }
2429
- if (part) { conditions.push(`s.part = ?`); params.push(part); }
2430
- if (chapter) { conditions.push(`s.chapter = ?`); params.push(chapter); }
2431
- if (pov) { conditions.push(`s.pov = ?`); params.push(pov); }
2432
-
2433
- if (joins.length) query += " " + joins.join(" ");
2434
- if (conditions.length) query += " WHERE " + conditions.join(" AND ");
2435
- query += " ORDER BY s.part, s.chapter, s.timeline_position";
2436
-
2437
- const rows = db.prepare(query).all(...params);
2438
- if (rows.length === 0) {
2439
- return errorResponse("NO_RESULTS", "No scenes match the given filters. Hint: broaden filters or call search_metadata with a keyword first.");
2440
- }
2441
-
2442
- const staleCount = rows.filter(r => r.metadata_stale).length;
2443
- const warning = staleCount > 0
2444
- ? `${staleCount} scene(s) have stale metadata — prose has changed since last enrichment. Consider running enrich_scene() before relying on this data for analysis.`
2445
- : undefined;
2446
-
2447
- const paged = paginateRows(rows, {
2448
- page,
2449
- pageSize: page_size,
2450
- forcePagination: rows.length > DEFAULT_METADATA_PAGE_SIZE,
2451
- });
2452
-
2453
- const payload = paged.paginated
2454
- ? {
2455
- results: paged.rows,
2456
- ...paged.meta,
2457
- warning,
2458
- }
2459
- : rows;
2460
-
2461
- return {
2462
- content: [{
2463
- type: "text",
2464
- text: JSON.stringify(payload, null, 2),
2465
- }],
2466
- };
2467
- }
2468
- );
2469
-
2470
- // ---- get_scene_prose -----------------------------------------------------
2471
- s.tool(
2472
- "get_scene_prose",
2473
- "Load the full prose text of a single scene. Use this for close reading, continuity checks, or when you need the actual writing. For overview or filtering, use find_scenes instead — it is much cheaper. Optionally retrieve a past version from git history.",
2474
- {
2475
- scene_id: z.string().describe("The scene_id to retrieve (e.g. 'sc-001-prologue'). Get this from find_scenes or get_arc."),
2476
- commit: z.string().optional().describe("Optional git commit hash to retrieve a past version. Use list_snapshots to find valid hashes. If omitted, returns the current prose."),
2477
- },
2478
- async ({ scene_id, commit }) => {
2479
- const scene = db.prepare(`SELECT file_path, metadata_stale FROM scenes WHERE scene_id = ?`).get(scene_id);
2480
- if (!scene) {
2481
- return errorResponse("NOT_FOUND", `Scene '${scene_id}' not found. Run sync() if you just added it.`);
2482
- }
2483
- try {
2484
- let rawContent;
2485
- if (commit && GIT_ENABLED) {
2486
- // Retrieve from git history
2487
- rawContent = getSceneProseAtCommit(SYNC_DIR, scene.file_path, commit);
2488
- } else if (commit && !GIT_ENABLED) {
2489
- return errorResponse("GIT_UNAVAILABLE", "Git is not available — cannot retrieve historical versions.");
2490
- } else {
2491
- // Retrieve current version
2492
- rawContent = fs.readFileSync(scene.file_path, "utf8");
2493
- }
2494
-
2495
- const { content: prose } = matter(rawContent);
2496
- const versionNote = commit ? `\n\n(Retrieved from commit: ${commit})` : "";
2497
- const warning = scene.metadata_stale && !commit
2498
- ? `\n\n⚠️ Metadata for this scene may be stale — prose has changed since last enrichment.`
2499
- : "";
2500
- return { content: [{ type: "text", text: prose.trim() + versionNote + warning }] };
2501
- } catch (err) {
2502
- if (err.code === "ENOENT") {
2503
- return errorResponse(
2504
- "STALE_PATH",
2505
- `Prose file for scene '${scene_id}' not found at indexed path — the file may have moved since the last sync. Run sync() to refresh the index.`,
2506
- { indexed_path: scene.file_path }
2507
- );
2508
- }
2509
- return errorResponse("IO_ERROR", `Failed to read scene file: ${err.message}`);
2510
- }
2511
- }
2512
- );
2513
-
2514
- // ---- get_chapter_prose ---------------------------------------------------
2515
- s.tool(
2516
- "get_chapter_prose",
2517
- `Load the full prose for every scene in a chapter, concatenated in order. Expensive — only use when you need to read an entire chapter. Capped at ${MAX_CHAPTER_SCENES} scenes. Use find_scenes first to confirm the chapter exists.`,
2518
- {
2519
- project_id: z.string().describe("Project ID (e.g. 'the-lamb')."),
2520
- part: z.number().int().describe("Part number (integer)."),
2521
- chapter: z.number().int().describe("Chapter number (integer, globally numbered across the whole project)."),
2522
- },
2523
- async ({ project_id, part, chapter }) => {
2524
- const allScenes = db.prepare(`
2525
- SELECT scene_id, title, file_path FROM scenes
2526
- WHERE project_id = ? AND part = ? AND chapter = ?
2527
- ORDER BY timeline_position
2528
- `).all(project_id, part, chapter);
2529
-
2530
- if (allScenes.length === 0) {
2531
- return errorResponse("NO_RESULTS", `No scenes found for Part ${part}, Chapter ${chapter}.`);
2532
- }
2533
-
2534
- const truncated = allScenes.length > MAX_CHAPTER_SCENES;
2535
- const scenes = truncated ? allScenes.slice(0, MAX_CHAPTER_SCENES) : allScenes;
2536
-
2537
- const parts = [];
2538
- for (const scene of scenes) {
2539
- try {
2540
- const raw = fs.readFileSync(scene.file_path, "utf8");
2541
- const { content: prose } = matter(raw);
2542
- parts.push(`## ${scene.title ?? scene.scene_id}\n\n${prose.trim()}`);
2543
- } catch (err) {
2544
- parts.push(`## ${scene.scene_id}\n\n[Error reading file: ${err.message}]`);
2545
- }
2546
- }
2547
-
2548
- const warning = truncated
2549
- ? `\n\n⚠️ Chapter has ${allScenes.length} scenes — only the first ${MAX_CHAPTER_SCENES} were loaded. Set MAX_CHAPTER_SCENES to increase this limit.`
2550
- : "";
2551
- return { content: [{ type: "text", text: parts.join("\n\n---\n\n") + warning }] };
2552
- }
2553
- );
2554
-
2555
- // ---- get_arc -------------------------------------------------------------
2556
- s.tool(
2557
- "get_arc",
2558
- "Get every scene a character appears in, ordered by part/chapter/position. Returns scene metadata only — no prose. Use this to trace a character's arc through the story. Supports pagination via page/page_size and auto-paginates large result sets with total_count. Call list_characters first to get the character_id.",
2559
- {
2560
- character_id: z.string().describe("The character_id to trace (e.g. 'char-mira-nystrom'). Use list_characters to find valid IDs."),
2561
- project_id: z.string().optional().describe("Limit to a specific project (e.g. 'the-lamb')."),
2562
- page: z.number().int().min(1).optional().describe("Optional page number for paginated responses (1-based)."),
2563
- page_size: z.number().int().min(1).max(200).optional().describe("Optional page size for paginated responses (default: 20, max: 200)."),
2564
- },
2565
- async ({ character_id, project_id, page, page_size }) => {
2566
- let query = `
2567
- SELECT s.scene_id, s.project_id, s.part, s.chapter, s.chapter_title, s.title, s.logline,
2568
- s.scene_change, s.causality, s.stakes, s.scene_functions,
2569
- s.save_the_cat_beat, s.timeline_position, s.story_time, s.pov, s.metadata_stale
2570
- FROM scenes s
2571
- JOIN scene_characters sc ON sc.scene_id = s.scene_id
2572
- WHERE sc.character_id = ?
2573
- `;
2574
- const params = [character_id];
2575
- if (project_id) { query += ` AND s.project_id = ?`; params.push(project_id); }
2576
- query += ` ORDER BY s.part, s.chapter, s.timeline_position`;
2577
-
2578
- const rows = db.prepare(query).all(...params);
2579
- if (rows.length === 0) {
2580
- return errorResponse("NO_RESULTS", `No scenes found for character '${character_id}'.`);
2581
- }
2582
-
2583
- const staleCount = rows.filter(r => r.metadata_stale).length;
2584
- const warning = staleCount > 0
2585
- ? `${staleCount} scene(s) have stale metadata.`
2586
- : undefined;
2587
-
2588
- const paged = paginateRows(rows, {
2589
- page,
2590
- pageSize: page_size,
2591
- forcePagination: rows.length > DEFAULT_METADATA_PAGE_SIZE,
2592
- });
2593
-
2594
- const payload = paged.paginated
2595
- ? {
2596
- results: paged.rows,
2597
- ...paged.meta,
2598
- warning,
2599
- }
2600
- : rows;
2601
-
2602
- return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
2603
- }
2604
- );
2605
-
2606
- // ---- list_characters -----------------------------------------------------
2607
- s.tool(
2608
- "list_characters",
2609
- "List all indexed characters with their character_id, name, role, and arc_summary. Call this first whenever you need to filter scenes by character or look up a character sheet — it gives you the character_id values required by other tools.",
2610
- {
2611
- project_id: z.string().optional().describe("Limit to a specific project (e.g. 'the-lamb')."),
2612
- universe_id: z.string().optional().describe("Limit to a specific universe (if using cross-project world-building)."),
2613
- },
2614
- async ({ project_id, universe_id }) => {
2615
- let query = `SELECT character_id, name, role, arc_summary, project_id, universe_id FROM characters`;
2616
- const conditions = [];
2617
- const params = [];
2618
- if (project_id) { conditions.push(`project_id = ?`); params.push(project_id); }
2619
- if (universe_id) { conditions.push(`universe_id = ?`); params.push(universe_id); }
2620
- if (conditions.length) query += " WHERE " + conditions.join(" AND ");
2621
- query += " ORDER BY name";
2622
-
2623
- const rows = db.prepare(query).all(...params);
2624
- if (rows.length === 0) {
2625
- return errorResponse("NO_RESULTS", "No characters found.");
2626
- }
2627
- return { content: [{ type: "text", text: JSON.stringify(rows, null, 2) }] };
2628
- }
2629
- );
2630
-
2631
- // ---- get_character_sheet -------------------------------------------------
2632
- s.tool(
2633
- "get_character_sheet",
2634
- "Get full character details: role, arc_summary, traits, the canonical sheet content, and any adjacent support notes when the character uses a folder-based layout. Use list_characters first to get the character_id.",
2635
- {
2636
- character_id: z.string().describe("The character_id to look up (e.g. 'char-sebastian'). Use list_characters to find valid IDs."),
2637
- },
2638
- async ({ character_id }) => {
2639
- const character = db.prepare(`SELECT * FROM characters WHERE character_id = ?`).get(character_id);
2640
- if (!character) {
2641
- return errorResponse("NOT_FOUND", `Character '${character_id}' not found.`);
2642
- }
2643
-
2644
- const traits = db.prepare(`SELECT trait FROM character_traits WHERE character_id = ?`)
2645
- .all(character_id).map(r => r.trait);
2646
-
2647
- let notes = "";
2648
- let supportingNotes = [];
2649
- if (character.file_path) {
2650
- try {
2651
- const raw = fs.readFileSync(character.file_path, "utf8");
2652
- const { content } = matter(raw);
2653
- notes = content.trim();
2654
- supportingNotes = readSupportingNotesForEntity(character.file_path);
2655
- } catch { /* empty */ }
2656
- }
2657
-
2658
- const result = {
2659
- ...character,
2660
- traits,
2661
- notes: notes || undefined,
2662
- supporting_notes: supportingNotes.length ? supportingNotes : undefined,
2663
- };
2664
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2665
- }
2666
- );
2667
-
2668
- // ---- create_character_sheet ---------------------------------------------
2669
- s.tool(
2670
- "create_character_sheet",
2671
- "Create or reuse a canonical character sheet folder with sheet.md and sheet.meta.yaml so the character can be indexed immediately. If the folder already exists, missing canonical files are backfilled and the existing sheet is preserved.",
2672
- {
2673
- name: z.string().describe("Display name of the character (e.g. 'Mira Nystrom')."),
2674
- project_id: z.string().optional().describe("Project scope for a book-local character (e.g. 'universe-1/book-1-the-lamb' or 'test-novel')."),
2675
- universe_id: z.string().optional().describe("Universe scope for a cross-book shared character (e.g. 'universe-1')."),
2676
- notes: z.string().optional().describe("Optional starter prose content for sheet.md."),
2677
- fields: z.object({
2678
- role: z.string().optional(),
2679
- arc_summary: z.string().optional(),
2680
- first_appearance: z.string().optional(),
2681
- traits: z.array(z.string()).optional(),
2682
- }).optional().describe("Optional starter metadata fields for the character sidecar."),
2683
- },
2684
- async ({ name, project_id, universe_id, notes, fields }) => {
2685
- if (!SYNC_DIR_WRITABLE) {
2686
- return errorResponse("READ_ONLY", "Cannot create character sheet: sync dir is read-only.");
2687
- }
2688
- const hasProjectId = project_id !== undefined;
2689
- const hasUniverseId = universe_id !== undefined;
2690
- if ((hasProjectId && hasUniverseId) || (!hasProjectId && !hasUniverseId)) {
2691
- return errorResponse("VALIDATION_ERROR", "Provide exactly one of project_id or universe_id.");
2692
- }
2693
- if (hasProjectId) {
2694
- const check = validateProjectId(project_id);
2695
- if (!check.ok) return errorResponse("INVALID_PROJECT_ID", check.reason, { project_id });
2696
- }
2697
- if (hasUniverseId) {
2698
- const check = validateUniverseId(universe_id);
2699
- if (!check.ok) return errorResponse("INVALID_UNIVERSE_ID", check.reason, { universe_id });
2700
- }
2701
-
2702
- try {
2703
- const result = createCanonicalWorldEntity({
2704
- kind: "character",
2705
- name,
2706
- notes,
2707
- projectId: project_id,
2708
- universeId: universe_id,
2709
- meta: fields ?? {},
2710
- });
2711
-
2712
- return jsonResponse({ ok: true, action: result.created ? "created" : "exists", kind: "character", ...result });
2713
- } catch (err) {
2714
- return errorResponse("IO_ERROR", `Failed to create character sheet: ${err.message}`);
2715
- }
2716
- }
2717
- );
2718
-
2719
- // ---- list_places ---------------------------------------------------------
2720
- s.tool(
2721
- "list_places",
2722
- "List all indexed places with their place_id and name. Use this to find place_id values for scene filtering or to get an overview of the story's locations.",
2723
- {
2724
- project_id: z.string().optional().describe("Limit to a specific project (e.g. 'the-lamb')."),
2725
- universe_id: z.string().optional().describe("Limit to a specific universe."),
2726
- },
2727
- async ({ project_id, universe_id }) => {
2728
- let query = `SELECT place_id, name, project_id, universe_id FROM places`;
2729
- const conditions = [];
2730
- const params = [];
2731
- if (project_id) { conditions.push(`project_id = ?`); params.push(project_id); }
2732
- if (universe_id) { conditions.push(`universe_id = ?`); params.push(universe_id); }
2733
- if (conditions.length) query += " WHERE " + conditions.join(" AND ");
2734
- query += " ORDER BY name";
2735
-
2736
- const rows = db.prepare(query).all(...params);
2737
- if (rows.length === 0) {
2738
- return errorResponse("NO_RESULTS", "No places found.");
2739
- }
2740
- return { content: [{ type: "text", text: JSON.stringify(rows, null, 2) }] };
2741
- }
2742
- );
2743
-
2744
- // ---- create_place_sheet -------------------------------------------------
2745
- s.tool(
2746
- "create_place_sheet",
2747
- "Create or reuse a canonical place sheet folder with sheet.md and sheet.meta.yaml so the place can be indexed immediately. If the folder already exists, missing canonical files are backfilled and the existing sheet is preserved.",
2748
- {
2749
- name: z.string().describe("Display name of the place (e.g. 'University Hospital')."),
2750
- project_id: z.string().optional().describe("Project scope for a book-local place (e.g. 'universe-1/book-1-the-lamb' or 'test-novel')."),
2751
- universe_id: z.string().optional().describe("Universe scope for a cross-book shared place (e.g. 'universe-1')."),
2752
- notes: z.string().optional().describe("Optional starter prose content for sheet.md."),
2753
- fields: z.object({
2754
- associated_characters: z.array(z.string()).optional(),
2755
- tags: z.array(z.string()).optional(),
2756
- }).optional().describe("Optional starter metadata fields for the place sidecar."),
2757
- },
2758
- async ({ name, project_id, universe_id, notes, fields }) => {
2759
- if (!SYNC_DIR_WRITABLE) {
2760
- return errorResponse("READ_ONLY", "Cannot create place sheet: sync dir is read-only.");
2761
- }
2762
- const hasProjectId = project_id !== undefined;
2763
- const hasUniverseId = universe_id !== undefined;
2764
- if ((hasProjectId && hasUniverseId) || (!hasProjectId && !hasUniverseId)) {
2765
- return errorResponse("VALIDATION_ERROR", "Provide exactly one of project_id or universe_id.");
2766
- }
2767
- if (hasProjectId) {
2768
- const check = validateProjectId(project_id);
2769
- if (!check.ok) return errorResponse("INVALID_PROJECT_ID", check.reason, { project_id });
2770
- }
2771
- if (hasUniverseId) {
2772
- const check = validateUniverseId(universe_id);
2773
- if (!check.ok) return errorResponse("INVALID_UNIVERSE_ID", check.reason, { universe_id });
2774
- }
2775
-
2776
- try {
2777
- const result = createCanonicalWorldEntity({
2778
- kind: "place",
2779
- name,
2780
- notes,
2781
- projectId: project_id,
2782
- universeId: universe_id,
2783
- meta: fields ?? {},
2784
- });
2785
-
2786
- return jsonResponse({ ok: true, action: result.created ? "created" : "exists", kind: "place", ...result });
2787
- } catch (err) {
2788
- return errorResponse("IO_ERROR", `Failed to create place sheet: ${err.message}`);
2789
- }
2790
- }
2791
- );
2792
-
2793
- // ---- get_place_sheet -----------------------------------------------------
2794
- s.tool(
2795
- "get_place_sheet",
2796
- "Get full place details: associated_characters, tags, the canonical sheet content, and any adjacent support notes when the place uses a folder-based layout. Use list_places first to get the place_id.",
2797
- {
2798
- place_id: z.string().describe("The place_id to look up (e.g. 'place-harbor-district'). Use list_places to find valid IDs."),
2799
- },
2800
- async ({ place_id }) => {
2801
- const place = db.prepare(`SELECT * FROM places WHERE place_id = ?`).get(place_id);
2802
- if (!place) {
2803
- return errorResponse("NOT_FOUND", `Place '${place_id}' not found.`);
2804
- }
2805
-
2806
- let notes = "";
2807
- let supportingNotes = [];
2808
- let associatedCharacters = [];
2809
- let tags = [];
2810
-
2811
- if (place.file_path) {
2812
- try {
2813
- const raw = fs.readFileSync(place.file_path, "utf8");
2814
- const { content } = matter(raw);
2815
- notes = content.trim();
2816
- supportingNotes = readSupportingNotesForEntity(place.file_path);
2817
-
2818
- const meta = readEntityMetadata(place.file_path);
2819
- associatedCharacters = Array.isArray(meta.associated_characters) ? meta.associated_characters : [];
2820
- tags = Array.isArray(meta.tags) ? meta.tags : [];
2821
- } catch { /* empty */ }
2822
- }
2823
-
2824
- const result = {
2825
- ...place,
2826
- associated_characters: associatedCharacters.length ? associatedCharacters : undefined,
2827
- tags: tags.length ? tags : undefined,
2828
- notes: notes || undefined,
2829
- supporting_notes: supportingNotes.length ? supportingNotes : undefined,
2830
- };
2831
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2832
- }
2833
- );
2834
-
2835
- // ---- search_metadata -----------------------------------------------------
2836
- s.tool(
2837
- "search_metadata",
2838
- "Full-text search across scene titles, loglines (synopsis/logline text fields), and metadata keywords (tags/characters/places/versions). Use this when you don't know the exact scene_id or chapter but want to find scenes by topic, theme, or metadata keyword. Not a prose search — use get_scene_prose to read actual text. Supports pagination via page/page_size and auto-paginates large result sets with total_count.",
2839
- {
2840
- query: z.string().describe("Search terms (e.g. 'hospital' or 'Sebastian feeding'). FTS5 syntax supported."),
2841
- page: z.number().int().min(1).optional().describe("Optional page number for paginated responses (1-based)."),
2842
- page_size: z.number().int().min(1).max(200).optional().describe("Optional page size for paginated responses (default: 20, max: 200)."),
2843
- },
2844
- async ({ query, page, page_size }) => {
2845
- let totalCount;
2846
- try {
2847
- totalCount = db.prepare(`
2848
- SELECT COUNT(*) AS count
2849
- FROM scenes_fts f
2850
- JOIN scenes s ON s.scene_id = f.scene_id AND s.project_id = f.project_id
2851
- WHERE scenes_fts MATCH ?
2852
- `).get(query)?.count ?? 0;
2853
- } catch (err) {
2854
- return errorResponse("INVALID_QUERY", "Invalid search query syntax. Use plain keywords or quoted phrases.", { detail: err.message });
2855
- }
2856
-
2857
- if (totalCount === 0) {
2858
- return errorResponse("NO_RESULTS", "No scenes matched the search query.");
2859
- }
2860
-
2861
- const shouldPaginate = totalCount > DEFAULT_METADATA_PAGE_SIZE || page !== undefined || page_size !== undefined;
2862
-
2863
- if (!shouldPaginate) {
2864
- const rows = db.prepare(`
2865
- SELECT f.scene_id, f.project_id, s.title, s.logline, s.part, s.chapter, s.chapter_title, s.metadata_stale
2866
- FROM scenes_fts f
2867
- JOIN scenes s ON s.scene_id = f.scene_id AND s.project_id = f.project_id
2868
- WHERE scenes_fts MATCH ?
2869
- ORDER BY rank
2870
- `).all(query);
2871
-
2872
- return { content: [{ type: "text", text: JSON.stringify(rows, null, 2) }] };
2873
- }
2874
-
2875
- const safePageSize = Math.max(1, page_size ?? DEFAULT_METADATA_PAGE_SIZE);
2876
- const safePage = Math.max(1, page ?? 1);
2877
- const totalPages = Math.max(1, Math.ceil(totalCount / safePageSize));
2878
- const normalizedPage = Math.min(safePage, totalPages);
2879
- const offset = (normalizedPage - 1) * safePageSize;
2880
-
2881
- const rows = db.prepare(`
2882
- SELECT f.scene_id, f.project_id, s.title, s.logline, s.part, s.chapter, s.chapter_title, s.metadata_stale
2883
- FROM scenes_fts f
2884
- JOIN scenes s ON s.scene_id = f.scene_id AND s.project_id = f.project_id
2885
- WHERE scenes_fts MATCH ?
2886
- ORDER BY rank
2887
- LIMIT ? OFFSET ?
2888
- `).all(query, safePageSize, offset);
2889
-
2890
- const payload = {
2891
- results: rows,
2892
- total_count: totalCount,
2893
- page: normalizedPage,
2894
- page_size: safePageSize,
2895
- total_pages: totalPages,
2896
- has_next_page: normalizedPage < totalPages,
2897
- has_prev_page: normalizedPage > 1,
2898
- };
2899
-
2900
- return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
2901
- }
2902
- );
2903
-
2904
- // ---- list_threads --------------------------------------------------------
2905
- s.tool(
2906
- "list_threads",
2907
- "List all subplot/storyline threads for a project. Returns a structured JSON envelope with results and total_count. Use this to discover valid thread_id values before calling get_thread_arc or upsert_thread_link. Supports pagination via page/page_size.",
2908
- {
2909
- project_id: z.string().describe("Project ID."),
2910
- page: z.number().int().min(1).optional().describe("Optional page number for paginated responses (1-based)."),
2911
- page_size: z.number().int().min(1).max(200).optional().describe("Optional page size for paginated responses (default: 20, max: 200)."),
2912
- },
2913
- async ({ project_id, page, page_size }) => {
2914
- const rows = db.prepare(`SELECT * FROM threads WHERE project_id = ? ORDER BY name`).all(project_id);
2915
- const paged = paginateRows(rows, { page, pageSize: page_size, forcePagination: false });
2916
- const payload = paged.paginated
2917
- ? {
2918
- project_id,
2919
- results: paged.rows,
2920
- ...paged.meta,
2921
- }
2922
- : {
2923
- project_id,
2924
- results: rows,
2925
- total_count: rows.length,
2926
- };
2927
-
2928
- return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
2929
- }
2930
- );
2931
-
2932
- // ---- get_thread_arc ------------------------------------------------------
2933
- s.tool(
2934
- "get_thread_arc",
2935
- "Get ordered scene metadata for all scenes belonging to a thread, including the per-thread beat. Returns a structured JSON envelope with thread metadata, results, and total_count. Use list_threads first to find a valid thread_id, then call get_scene_prose for close reading of specific scenes. Supports pagination via page/page_size.",
2936
- {
2937
- thread_id: z.string().describe("Thread ID."),
2938
- page: z.number().int().min(1).optional().describe("Optional page number for paginated responses (1-based)."),
2939
- page_size: z.number().int().min(1).max(200).optional().describe("Optional page size for paginated responses (default: 20, max: 200)."),
2940
- },
2941
- async ({ thread_id, page, page_size }) => {
2942
- const thread = db.prepare(`SELECT * FROM threads WHERE thread_id = ?`).get(thread_id);
2943
- if (!thread) {
2944
- return errorResponse("NOT_FOUND", `Thread '${thread_id}' not found. Hint: call list_threads with project_id to get valid thread IDs.`);
2945
- }
2946
-
2947
- const rows = db.prepare(`
2948
- SELECT s.scene_id, s.project_id, s.part, s.chapter, s.chapter_title, s.title, s.logline,
2949
- st.beat AS thread_beat, s.timeline_position, s.story_time, s.metadata_stale
2950
- FROM scenes s
2951
- JOIN scene_threads st ON st.scene_id = s.scene_id AND st.thread_id = ?
2952
- ORDER BY s.part, s.chapter, s.timeline_position
2953
- `).all(thread_id);
2954
- const staleCount = rows.filter(r => r.metadata_stale).length;
2955
- const warning = staleCount > 0 ? `${staleCount} scene(s) have stale metadata.` : undefined;
2956
- const paged = paginateRows(rows, { page, pageSize: page_size, forcePagination: false });
2957
-
2958
- const payload = paged.paginated
2959
- ? {
2960
- thread,
2961
- results: paged.rows,
2962
- ...paged.meta,
2963
- warning,
2964
- }
2965
- : {
2966
- thread,
2967
- results: rows,
2968
- total_count: rows.length,
2969
- warning,
2970
- };
2971
-
2972
- return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
2973
- }
2974
- );
2975
-
2976
- // ---- upsert_thread_link ---------------------------------------------------
2977
- s.tool(
2978
- "upsert_thread_link",
2979
- "Create or update a thread and link it to a scene. Idempotent: if the link already exists, updates its beat. Only available when the sync dir is writable.",
2980
- {
2981
- project_id: z.string().describe("Project the thread belongs to (e.g. 'the-lamb')."),
2982
- thread_id: z.string().describe("Thread ID (e.g. 'thread-reconciliation')."),
2983
- thread_name: z.string().describe("Thread display name."),
2984
- scene_id: z.string().describe("Scene to link to the thread (e.g. 'sc-011-sebastian')."),
2985
- beat: z.string().optional().describe("Optional thread-specific beat label for this scene."),
2986
- status: z.string().optional().describe("Thread status (e.g. 'active', 'resolved'). Defaults to 'active'."),
2987
- },
2988
- async ({ project_id, thread_id, thread_name, scene_id, beat, status }) => {
2989
- if (!SYNC_DIR_WRITABLE) {
2990
- return errorResponse("READ_ONLY", "Cannot write thread links: sync dir is read-only.");
2991
- }
2992
-
2993
- const existingThread = db.prepare(`SELECT thread_id, project_id FROM threads WHERE thread_id = ?`).get(thread_id);
2994
- if (existingThread && existingThread.project_id !== project_id) {
2995
- return errorResponse(
2996
- "CONFLICT",
2997
- `Thread '${thread_id}' already exists in project '${existingThread.project_id}', cannot reuse it for project '${project_id}'.`
2998
- );
2999
- }
3000
-
3001
- const scene = db.prepare(`SELECT scene_id FROM scenes WHERE scene_id = ? AND project_id = ?`).get(scene_id, project_id);
3002
- if (!scene) {
3003
- return errorResponse("NOT_FOUND", `Scene '${scene_id}' not found in project '${project_id}'.`);
3004
- }
3005
-
3006
- db.prepare(`
3007
- INSERT INTO threads (thread_id, project_id, name, status)
3008
- VALUES (?, ?, ?, ?)
3009
- ON CONFLICT (thread_id) DO UPDATE SET
3010
- name = excluded.name,
3011
- status = excluded.status
3012
- `).run(thread_id, project_id, thread_name, status ?? "active");
3013
-
3014
- db.prepare(`
3015
- INSERT INTO scene_threads (scene_id, thread_id, beat)
3016
- VALUES (?, ?, ?)
3017
- ON CONFLICT (scene_id, thread_id) DO UPDATE SET
3018
- beat = excluded.beat
3019
- `).run(scene_id, thread_id, beat ?? null);
3020
-
3021
- const thread = db.prepare(`SELECT * FROM threads WHERE thread_id = ?`).get(thread_id);
3022
- const link = db.prepare(`SELECT scene_id, thread_id, beat FROM scene_threads WHERE scene_id = ? AND thread_id = ?`)
3023
- .get(scene_id, thread_id);
3024
-
3025
- return jsonResponse({
3026
- ok: true,
3027
- action: "upserted",
3028
- thread,
3029
- link,
3030
- });
3031
- }
3032
- );
3033
-
3034
- // ---- enrich_scene --------------------------------------------------------
3035
- s.tool(
3036
- "enrich_scene",
3037
- "Re-derive lightweight scene metadata from current prose (logline and character mentions) and clear metadata_stale for that scene. Only available when the sync dir is writable.",
3038
- {
3039
- scene_id: z.string().describe("Scene to enrich (e.g. 'sc-011-sebastian')."),
3040
- project_id: z.string().optional().describe("Project ID. Required when scene_id is duplicated across projects."),
3041
- },
3042
- async ({ scene_id, project_id }) => {
3043
- if (!SYNC_DIR_WRITABLE) {
3044
- return errorResponse("READ_ONLY", "Cannot enrich scene: sync dir is read-only.");
3045
- }
3046
-
3047
- let scene;
3048
- if (project_id) {
3049
- scene = db.prepare(`SELECT scene_id, project_id, file_path FROM scenes WHERE scene_id = ? AND project_id = ?`)
3050
- .get(scene_id, project_id);
3051
- } else {
3052
- const matches = db.prepare(`SELECT scene_id, project_id, file_path FROM scenes WHERE scene_id = ?`).all(scene_id);
3053
- if (matches.length > 1) {
3054
- return errorResponse("VALIDATION_ERROR", `Scene '${scene_id}' exists in multiple projects. Provide project_id.`);
3055
- }
3056
- scene = matches[0];
3057
- }
3058
-
3059
- if (!scene) {
3060
- return errorResponse("NOT_FOUND", `Scene '${scene_id}' not found${project_id ? ` in project '${project_id}'` : ""}.`);
3061
- }
3062
-
3063
- try {
3064
- const raw = fs.readFileSync(scene.file_path, "utf8");
3065
- const { content: prose } = matter(raw);
3066
- const { meta } = readMeta(scene.file_path, SYNC_DIR, { writable: true });
3067
-
3068
- const inferredLogline = deriveLoglineFromProse(prose);
3069
- const inferredCharacters = inferCharacterIdsFromProse(db, prose, scene.project_id);
3070
-
3071
- const updatedMeta = normalizeSceneMetaForPath(SYNC_DIR, scene.file_path, {
3072
- ...meta,
3073
- ...(inferredLogline ? { logline: inferredLogline } : {}),
3074
- ...((inferredCharacters.length > 0 || (meta.characters?.length ?? 0) > 0)
3075
- ? { characters: inferredCharacters.length > 0 ? inferredCharacters : meta.characters }
3076
- : {}),
3077
- }).meta;
3078
-
3079
- writeMeta(scene.file_path, updatedMeta);
3080
- indexSceneFile(db, SYNC_DIR, scene.file_path, updatedMeta, prose);
3081
- db.prepare(`UPDATE scenes SET metadata_stale = 0 WHERE scene_id = ? AND project_id = ?`)
3082
- .run(scene.scene_id, scene.project_id);
3083
-
3084
- return jsonResponse({
3085
- ok: true,
3086
- action: "enriched",
3087
- scene_id: scene.scene_id,
3088
- project_id: scene.project_id,
3089
- updated_fields: {
3090
- logline: Boolean(inferredLogline),
3091
- characters: inferredCharacters.length,
3092
- },
3093
- metadata_stale: false,
3094
- });
3095
- } catch (err) {
3096
- return errorResponse("IO_ERROR", `Failed to enrich scene '${scene.scene_id}': ${err.message}`);
3097
- }
3098
- }
3099
- );
3100
-
3101
- // ---- update_scene_metadata -----------------------------------------------
3102
- s.tool(
3103
- "update_scene_metadata",
3104
- "Update one or more metadata fields for a scene. Writes to the .meta.yaml sidecar — never modifies prose. Changes are immediately reflected in the index. Only available when the sync dir is writable.",
3105
- {
3106
- scene_id: z.string().describe("The scene_id to update (e.g. 'sc-011-sebastian')."),
3107
- project_id: z.string().describe("Project the scene belongs to (e.g. 'the-lamb')."),
3108
- fields: z.object({
3109
- title: z.string().optional(),
3110
- logline: z.string().optional(),
3111
- status: z.string().optional().describe("Workflow status (e.g. 'draft', 'revision', 'complete'). Free text — no fixed vocabulary."),
3112
- save_the_cat_beat: z.string().optional(),
3113
- pov: z.string().optional(),
3114
- part: z.number().int().optional(),
3115
- chapter: z.number().int().optional(),
3116
- timeline_position: z.number().int().optional(),
3117
- story_time: z.string().optional(),
3118
- tags: z.array(z.string()).optional(),
3119
- characters: z.array(z.string()).optional(),
3120
- places: z.array(z.string()).optional(),
3121
- }).describe("Fields to update. Only supplied keys are changed."),
3122
- },
3123
- async ({ scene_id, project_id, fields }) => {
3124
- if (!SYNC_DIR_WRITABLE) {
3125
- return errorResponse("READ_ONLY", "Cannot update metadata: sync dir is read-only.");
3126
- }
3127
- const scene = db.prepare(`SELECT file_path FROM scenes WHERE scene_id = ? AND project_id = ?`)
3128
- .get(scene_id, project_id);
3129
- if (!scene) {
3130
- return errorResponse("NOT_FOUND", `Scene '${scene_id}' not found in project '${project_id}'.`);
3131
- }
3132
- try {
3133
- const { meta } = readMeta(scene.file_path, SYNC_DIR, { writable: true });
3134
- const updated = normalizeSceneMetaForPath(SYNC_DIR, scene.file_path, { ...meta, ...fields }).meta;
3135
- writeMeta(scene.file_path, updated);
3136
-
3137
- // Re-index the scene immediately so the DB reflects the new metadata
3138
- const { content: prose } = matter(fs.readFileSync(scene.file_path, "utf8"));
3139
- indexSceneFile(db, SYNC_DIR, scene.file_path, updated, prose);
3140
-
3141
- return { content: [{ type: "text", text: `Updated metadata for scene '${scene_id}'.` }] };
3142
- } catch (err) {
3143
- if (err.code === "ENOENT") {
3144
- return errorResponse("STALE_PATH", `Prose file for scene '${scene_id}' not found at indexed path — the file may have moved. Run sync() to refresh.`, { indexed_path: scene.file_path });
3145
- }
3146
- return errorResponse("IO_ERROR", `Failed to write metadata for scene '${scene_id}': ${err.message}`);
3147
- }
3148
- }
3149
- );
3150
-
3151
- // ---- update_character_sheet ----------------------------------------------
3152
- s.tool(
3153
- "update_character_sheet",
3154
- "Update structured metadata fields for a character (role, arc_summary, traits, etc). Writes to the .meta.yaml sidecar — never modifies the prose notes file. Changes are immediately reflected in the index. Only available when the sync dir is writable.",
3155
- {
3156
- character_id: z.string().describe("The character_id to update (e.g. 'char-mira-nystrom'). Use list_characters to find valid IDs."),
3157
- fields: z.object({
3158
- name: z.string().optional(),
3159
- role: z.string().optional(),
3160
- arc_summary: z.string().optional(),
3161
- first_appearance: z.string().optional(),
3162
- traits: z.array(z.string()).optional(),
3163
- }).describe("Fields to update. Only supplied keys are changed."),
3164
- },
3165
- async ({ character_id, fields }) => {
3166
- if (!SYNC_DIR_WRITABLE) {
3167
- return errorResponse("READ_ONLY", "Cannot update character: sync dir is read-only.");
3168
- }
3169
- const char = db.prepare(`SELECT file_path FROM characters WHERE character_id = ?`).get(character_id);
3170
- if (!char) {
3171
- return errorResponse("NOT_FOUND", `Character '${character_id}' not found.`);
3172
- }
3173
- try {
3174
- const { meta } = readMeta(char.file_path, SYNC_DIR, { writable: true });
3175
- const updated = { ...meta, ...fields };
3176
- writeMeta(char.file_path, updated);
3177
-
3178
- // Update DB directly
3179
- db.prepare(`
3180
- UPDATE characters SET name = ?, role = ?, arc_summary = ?, first_appearance = ?
3181
- WHERE character_id = ?
3182
- `).run(
3183
- updated.name ?? meta.name, updated.role ?? null,
3184
- updated.arc_summary ?? null, updated.first_appearance ?? null,
3185
- character_id
3186
- );
3187
- if (fields.traits) {
3188
- db.prepare(`DELETE FROM character_traits WHERE character_id = ?`).run(character_id);
3189
- for (const t of fields.traits) {
3190
- db.prepare(`INSERT OR IGNORE INTO character_traits (character_id, trait) VALUES (?, ?)`).run(character_id, t);
3191
- }
3192
- }
3193
-
3194
- return { content: [{ type: "text", text: `Updated character sheet for '${character_id}'.` }] };
3195
- } catch (err) {
3196
- if (err.code === "ENOENT") {
3197
- return errorResponse("STALE_PATH", `Character file for '${character_id}' not found at indexed path — the file may have moved. Run sync() to refresh.`, { indexed_path: char.file_path });
3198
- }
3199
- return errorResponse("IO_ERROR", `Failed to write character metadata for '${character_id}': ${err.message}`);
3200
- }
3201
- }
3202
- );
3203
-
3204
- // ---- update_place_sheet --------------------------------------------------
3205
- s.tool(
3206
- "update_place_sheet",
3207
- "Update structured metadata fields for a place (name, associated_characters, tags). Writes to the .meta.yaml sidecar — never modifies the prose notes file. Changes are immediately reflected in the index. Only available when the sync dir is writable.",
3208
- {
3209
- place_id: z.string().describe("The place_id to update (e.g. 'place-harbor-district'). Use list_places to find valid IDs."),
3210
- fields: z.object({
3211
- name: z.string().optional(),
3212
- associated_characters: z.array(z.string()).optional(),
3213
- tags: z.array(z.string()).optional(),
3214
- }).describe("Fields to update. Only supplied keys are changed."),
3215
- },
3216
- async ({ place_id, fields }) => {
3217
- if (!SYNC_DIR_WRITABLE) {
3218
- return errorResponse("READ_ONLY", "Cannot update place: sync dir is read-only.");
3219
- }
3220
- const place = db.prepare(`SELECT file_path FROM places WHERE place_id = ?`).get(place_id);
3221
- if (!place) {
3222
- return errorResponse("NOT_FOUND", `Place '${place_id}' not found.`);
3223
- }
3224
- try {
3225
- const { meta } = readMeta(place.file_path, SYNC_DIR, { writable: true });
3226
- const updated = { ...meta, ...fields };
3227
- writeMeta(place.file_path, updated);
3228
-
3229
- // Update DB directly
3230
- db.prepare(`UPDATE places SET name = ? WHERE place_id = ?`)
3231
- .run(updated.name ?? meta.name ?? place_id, place_id);
3232
-
3233
- return { content: [{ type: "text", text: `Updated place sheet for '${place_id}'.` }] };
3234
- } catch (err) {
3235
- if (err.code === "ENOENT") {
3236
- return errorResponse("STALE_PATH", `Place file for '${place_id}' not found at indexed path — the file may have moved. Run sync() to refresh.`, { indexed_path: place.file_path });
3237
- }
3238
- return errorResponse("IO_ERROR", `Failed to write place metadata for '${place_id}': ${err.message}`);
3239
- }
3240
- }
3241
- );
3242
-
3243
- // ---- flag_scene ----------------------------------------------------------
3244
- s.tool(
3245
- "flag_scene",
3246
- "Attach a continuity or review note to a scene. Flags are appended to the sidecar file and accumulate over time — they are never overwritten. Use this to record continuity problems, revision notes, or questions you want to revisit.",
3247
- {
3248
- scene_id: z.string().describe("The scene_id to flag (e.g. 'sc-012-open-to-anyone')."),
3249
- project_id: z.string().describe("Project the scene belongs to (e.g. 'the-lamb')."),
3250
- note: z.string().describe("The flag note (e.g. 'Victor knows Mira\u2019s name here, but they haven\u2019t been introduced yet \u2014 contradicts sc-006')."),
3251
- },
3252
- async ({ scene_id, project_id, note }) => {
3253
- if (!SYNC_DIR_WRITABLE) {
3254
- return errorResponse("READ_ONLY", "Cannot flag scene: sync dir is read-only.");
3255
- }
3256
- const scene = db.prepare(`SELECT file_path FROM scenes WHERE scene_id = ? AND project_id = ?`)
3257
- .get(scene_id, project_id);
3258
- if (!scene) {
3259
- return errorResponse("NOT_FOUND", `Scene '${scene_id}' not found in project '${project_id}'.`);
3260
- }
3261
- try {
3262
- const { meta } = readMeta(scene.file_path, SYNC_DIR, { writable: true });
3263
- const flags = meta.flags ?? [];
3264
- flags.push({ note, flagged_at: new Date().toISOString() });
3265
- writeMeta(scene.file_path, { ...meta, flags });
3266
- return { content: [{ type: "text", text: `Flagged scene '${scene_id}': ${note}` }] };
3267
- } catch (err) {
3268
- if (err.code === "ENOENT") {
3269
- return errorResponse("STALE_PATH", `Prose file for scene '${scene_id}' not found at indexed path — the file may have moved. Run sync() to refresh.`, { indexed_path: scene.file_path });
3270
- }
3271
- return errorResponse("IO_ERROR", `Failed to flag scene '${scene_id}': ${err.message}`);
3272
- }
3273
- }
3274
- );
3275
-
3276
- // ---- get_relationship_arc ------------------------------------------------
3277
- s.tool(
3278
- "get_relationship_arc",
3279
- "Show how the relationship between two characters evolves across scenes, in order. Uses explicitly recorded relationship entries — returns nothing if no entries exist yet. Use list_characters to get character_id values.",
3280
- {
3281
- from_character: z.string().describe("character_id of the first character (e.g. 'char-sebastian')."),
3282
- to_character: z.string().describe("character_id of the second character (e.g. 'char-mira-nystrom')."),
3283
- project_id: z.string().optional().describe("Limit to a specific project (e.g. 'the-lamb')."),
3284
- },
3285
- async ({ from_character, to_character, project_id }) => {
3286
- let query = `
3287
- SELECT r.from_character, r.to_character, r.relationship_type, r.strength,
3288
- r.scene_id, r.note,
3289
- s.part, s.chapter, s.chapter_title, s.timeline_position, s.title AS scene_title
3290
- FROM character_relationships r
3291
- LEFT JOIN scenes s ON s.scene_id = r.scene_id
3292
- WHERE r.from_character = ? AND r.to_character = ?
3293
- `;
3294
- const params = [from_character, to_character];
3295
- if (project_id) { query += ` AND (s.project_id = ? OR r.scene_id IS NULL)`; params.push(project_id); }
3296
- query += ` ORDER BY s.part, s.chapter, s.timeline_position`;
3297
-
3298
- const rows = db.prepare(query).all(...params);
3299
- if (rows.length === 0) {
3300
- return errorResponse("NO_RESULTS", `No relationship data found between '${from_character}' and '${to_character}'.`);
3301
- }
3302
- return { content: [{ type: "text", text: JSON.stringify(rows, null, 2) }] };
3303
- }
3304
- );
3305
-
3306
1909
  // ---- PHASE 3: Prose Editing (git-backed) --------------------------------
3307
1910
 
3308
1911
  // ---- propose_edit --------------------------------------------------------