@hanna84/mcp-writing 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,11 +4,31 @@ All notable changes to this project will be documented in this file. Dates are d
4
4
 
5
5
  Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
6
6
 
7
+ #### [v2.5.0](https://github.com/hannasdev/mcp-writing.git
8
+ /compare/v2.4.0...v2.5.0)
9
+
10
+ - feat(styleguide): add prose styleguide bootstrap suggestions [`#87`](https://github.com/hannasdev/mcp-writing.git
11
+ /pull/87)
12
+
13
+ #### [v2.4.0](https://github.com/hannasdev/mcp-writing.git
14
+ /compare/v2.3.0...v2.4.0)
15
+
16
+ > 26 April 2026
17
+
18
+ - feat(styleguide): add config update preview and prose drift checks [`#86`](https://github.com/hannasdev/mcp-writing.git
19
+ /pull/86)
20
+ - Release 2.4.0 [`1655c06`](https://github.com/hannasdev/mcp-writing.git
21
+ /commit/1655c06088824e608c2795b61707b963e541c3fb)
22
+
7
23
  #### [v2.3.0](https://github.com/hannasdev/mcp-writing.git
8
24
  /compare/v2.2.0...v2.3.0)
9
25
 
26
+ > 26 April 2026
27
+
10
28
  - feat(styleguide): generate prose styleguide skill from resolved config [`#85`](https://github.com/hannasdev/mcp-writing.git
11
29
  /pull/85)
30
+ - Release 2.3.0 [`3490851`](https://github.com/hannasdev/mcp-writing.git
31
+ /commit/3490851ccc94989c4a487790b4b35c6a15fac860)
12
32
 
13
33
  #### [v2.2.0](https://github.com/hannasdev/mcp-writing.git
14
34
  /compare/v2.1.0...v2.2.0)
package/index.js CHANGED
@@ -21,8 +21,16 @@ import {
21
21
  STYLEGUIDE_CONFIG_BASENAME,
22
22
  STYLEGUIDE_ENUMS,
23
23
  buildStyleguideConfigDraft,
24
+ previewStyleguideConfigUpdate,
24
25
  resolveStyleguideConfig,
26
+ summarizeStyleguideConfig,
27
+ updateStyleguideConfig,
25
28
  } from "./prose-styleguide.js";
29
+ import {
30
+ detectStyleguideSignals,
31
+ analyzeSceneStyleguideDrift,
32
+ suggestStyleguideUpdatesFromScenes,
33
+ } from "./prose-styleguide-drift.js";
26
34
  import {
27
35
  PROSE_STYLEGUIDE_SKILL_BASENAME,
28
36
  PROSE_STYLEGUIDE_SKILL_DIRNAME,
@@ -1518,6 +1526,425 @@ function createMcpServer() {
1518
1526
  }
1519
1527
  );
1520
1528
 
1529
+ s.tool(
1530
+ "summarize_prose_styleguide_config",
1531
+ "Summarize the currently resolved prose styleguide config in plain language for review or confirmation.",
1532
+ {
1533
+ project_id: z.string().optional().describe("Optional project ID for project-scoped resolution (e.g. 'the-lamb' or 'universe-1/book-1')."),
1534
+ },
1535
+ async ({ project_id }) => {
1536
+ if (project_id !== undefined) {
1537
+ const projectIdCheck = validateProjectId(project_id);
1538
+ if (!projectIdCheck.ok) {
1539
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1540
+ }
1541
+ }
1542
+
1543
+ const resolved = resolveStyleguideConfig({
1544
+ syncDir: SYNC_DIR,
1545
+ projectId: project_id,
1546
+ });
1547
+ if (!resolved.ok) {
1548
+ return errorResponse(
1549
+ resolved.error.code,
1550
+ resolved.error.message,
1551
+ resolved.error.details
1552
+ );
1553
+ }
1554
+ if (resolved.setup_required || !resolved.resolved_config) {
1555
+ return errorResponse(
1556
+ "STYLEGUIDE_CONFIG_REQUIRED",
1557
+ "Cannot summarize prose styleguide config before prose-styleguide.config.yaml is set up.",
1558
+ {
1559
+ project_id: project_id ?? null,
1560
+ next_step: "Run setup_prose_styleguide_config or bootstrap_prose_styleguide_config.",
1561
+ }
1562
+ );
1563
+ }
1564
+
1565
+ const summary = summarizeStyleguideConfig({
1566
+ resolvedConfig: resolved.resolved_config,
1567
+ inferredDefaults: resolved.inferred_defaults,
1568
+ });
1569
+ if (!summary.ok) {
1570
+ return errorResponse(summary.error.code, summary.error.message);
1571
+ }
1572
+
1573
+ return jsonResponse({
1574
+ ok: true,
1575
+ project_id: project_id ?? null,
1576
+ summary_text: summary.summary_text,
1577
+ summary_lines: summary.summary_lines,
1578
+ styleguide: resolved,
1579
+ });
1580
+ }
1581
+ );
1582
+
1583
+ s.tool(
1584
+ "bootstrap_prose_styleguide_config",
1585
+ "Detect dominant prose conventions from existing scenes and suggest initial prose-styleguide config values.",
1586
+ {
1587
+ project_id: z.string().describe("Project ID to analyze (e.g. 'the-lamb' or 'universe-1/book-1')."),
1588
+ scene_ids: z.array(z.string()).optional().describe("Optional scene_id allowlist to analyze."),
1589
+ part: z.number().int().optional().describe("Optional part filter."),
1590
+ chapter: z.number().int().optional().describe("Optional chapter filter."),
1591
+ max_scenes: z.number().int().positive().optional().describe("Maximum number of scenes to analyze (default: 50)."),
1592
+ min_agreement: z.number().min(0).max(1).optional().describe("Minimum agreement ratio for suggested fields (default: 0.6)."),
1593
+ min_evidence: z.number().int().positive().optional().describe("Minimum number of observed scenes per field before suggesting it (default: 3)."),
1594
+ include_scene_signals: z.boolean().optional().describe("If true, include per-scene detected signals in the response."),
1595
+ },
1596
+ async ({
1597
+ project_id,
1598
+ scene_ids,
1599
+ part,
1600
+ chapter,
1601
+ max_scenes = 50,
1602
+ min_agreement = 0.6,
1603
+ min_evidence = 3,
1604
+ include_scene_signals = false,
1605
+ }) => {
1606
+ const projectIdCheck = validateProjectId(project_id);
1607
+ if (!projectIdCheck.ok) {
1608
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1609
+ }
1610
+
1611
+ const targetResolution = resolveBatchTargetScenes(db, {
1612
+ projectId: project_id,
1613
+ sceneIds: scene_ids,
1614
+ part,
1615
+ chapter,
1616
+ onlyStale: false,
1617
+ });
1618
+ if (!targetResolution.ok) {
1619
+ return errorResponse(targetResolution.code, targetResolution.message, targetResolution.details);
1620
+ }
1621
+
1622
+ const targetScenes = targetResolution.rows;
1623
+ if (targetScenes.length === 0) {
1624
+ return errorResponse(
1625
+ "NOT_FOUND",
1626
+ `No scenes were found for project '${project_id}' with the requested filters.`,
1627
+ { project_id, scene_ids: scene_ids ?? null, part: part ?? null, chapter: chapter ?? null }
1628
+ );
1629
+ }
1630
+
1631
+ if (targetScenes.length > max_scenes) {
1632
+ return errorResponse(
1633
+ "VALIDATION_ERROR",
1634
+ `Matched ${targetScenes.length} scenes, which exceeds max_scenes=${max_scenes}.`,
1635
+ { matched_scenes: targetScenes.length, max_scenes, project_id }
1636
+ );
1637
+ }
1638
+
1639
+ const sceneSignals = [];
1640
+ let unreadableScenes = 0;
1641
+
1642
+ for (const scene of targetScenes) {
1643
+ try {
1644
+ const raw = fs.readFileSync(scene.file_path, "utf8");
1645
+ const prose = matter(raw).content;
1646
+ sceneSignals.push({
1647
+ scene_id: scene.scene_id,
1648
+ observed: detectStyleguideSignals(prose),
1649
+ });
1650
+ } catch {
1651
+ unreadableScenes += 1;
1652
+ sceneSignals.push({
1653
+ scene_id: scene.scene_id,
1654
+ observed: {},
1655
+ });
1656
+ }
1657
+ }
1658
+
1659
+ const suggestedConfig = suggestStyleguideUpdatesFromScenes({
1660
+ sceneAnalyses: sceneSignals,
1661
+ resolvedConfig: null,
1662
+ minAgreement: min_agreement,
1663
+ minEvidence: min_evidence,
1664
+ });
1665
+
1666
+ return jsonResponse({
1667
+ ok: true,
1668
+ project_id,
1669
+ checked_scenes: sceneSignals.length,
1670
+ unreadable_scenes: unreadableScenes,
1671
+ suggested_config: suggestedConfig,
1672
+ next_step: "Review suggested_config, then write accepted fields via update_prose_styleguide_config.",
1673
+ scene_signals: include_scene_signals ? sceneSignals : undefined,
1674
+ });
1675
+ }
1676
+ );
1677
+
1678
+ s.tool(
1679
+ "update_prose_styleguide_config",
1680
+ "Update an existing prose-styleguide.config.yaml at sync-root or project-root scope by writing only explicit field changes.",
1681
+ {
1682
+ scope: z.enum(["sync_root", "project_root"]).describe("Config scope to update."),
1683
+ project_id: z.string().optional().describe("Project ID when updating project_root config (e.g. 'the-lamb' or 'universe-1/book-1')."),
1684
+ updates: z.object({
1685
+ language: z.enum(STYLEGUIDE_ENUMS.language).optional(),
1686
+ spelling: z.enum(STYLEGUIDE_ENUMS.spelling).optional(),
1687
+ quotation_style: z.enum(STYLEGUIDE_ENUMS.quotation_style).optional(),
1688
+ quotation_style_nested: z.enum(STYLEGUIDE_ENUMS.quotation_style_nested).optional(),
1689
+ em_dash_spacing: z.enum(STYLEGUIDE_ENUMS.em_dash_spacing).optional(),
1690
+ ellipsis_style: z.enum(STYLEGUIDE_ENUMS.ellipsis_style).optional(),
1691
+ abbreviation_periods: z.enum(STYLEGUIDE_ENUMS.abbreviation_periods).optional(),
1692
+ oxford_comma: z.enum(STYLEGUIDE_ENUMS.oxford_comma).optional(),
1693
+ numbers: z.enum(STYLEGUIDE_ENUMS.numbers).optional(),
1694
+ date_format: z.enum(STYLEGUIDE_ENUMS.date_format).optional(),
1695
+ time_format: z.enum(STYLEGUIDE_ENUMS.time_format).optional(),
1696
+ tense: z.string().optional(),
1697
+ pov: z.enum(STYLEGUIDE_ENUMS.pov).optional(),
1698
+ dialogue_tags: z.enum(STYLEGUIDE_ENUMS.dialogue_tags).optional(),
1699
+ sentence_fragments: z.enum(STYLEGUIDE_ENUMS.sentence_fragments).optional(),
1700
+ voice_notes: z.string().optional(),
1701
+ }).strict().describe("Explicit config field changes to write at the selected scope."),
1702
+ },
1703
+ async ({ scope, project_id, updates }) => {
1704
+ if (project_id !== undefined) {
1705
+ const projectIdCheck = validateProjectId(project_id);
1706
+ if (!projectIdCheck.ok) {
1707
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1708
+ }
1709
+ }
1710
+
1711
+ if (scope === "project_root" && !project_id) {
1712
+ return errorResponse(
1713
+ "PROJECT_ID_REQUIRED",
1714
+ "project_id is required when scope=project_root."
1715
+ );
1716
+ }
1717
+
1718
+ if (!SYNC_DIR_WRITABLE) {
1719
+ return errorResponse(
1720
+ "SYNC_DIR_NOT_WRITABLE",
1721
+ "Cannot update styleguide config because WRITING_SYNC_DIR is not writable in this runtime.",
1722
+ { sync_dir: SYNC_DIR_ABS }
1723
+ );
1724
+ }
1725
+
1726
+ const updated = updateStyleguideConfig({
1727
+ syncDir: SYNC_DIR,
1728
+ scope,
1729
+ projectId: project_id,
1730
+ updates,
1731
+ });
1732
+ if (!updated.ok) {
1733
+ return errorResponse(
1734
+ updated.error.code,
1735
+ updated.error.message,
1736
+ updated.error.details
1737
+ );
1738
+ }
1739
+
1740
+ return jsonResponse({
1741
+ ok: true,
1742
+ scope: updated.scope,
1743
+ project_id: updated.project_id,
1744
+ file_path: path.resolve(updated.file_path),
1745
+ config: updated.config,
1746
+ changed_fields: updated.changed_fields,
1747
+ noop: Boolean(updated.noop),
1748
+ message: updated.message,
1749
+ warnings: updated.warnings,
1750
+ });
1751
+ }
1752
+ );
1753
+
1754
+ s.tool(
1755
+ "preview_prose_styleguide_config_update",
1756
+ "Preview how explicit updates would change an existing prose-styleguide.config.yaml without writing any files.",
1757
+ {
1758
+ scope: z.enum(["sync_root", "project_root"]).describe("Config scope to preview updates for."),
1759
+ project_id: z.string().optional().describe("Project ID when previewing project_root config updates (e.g. 'the-lamb' or 'universe-1/book-1')."),
1760
+ updates: z.object({
1761
+ language: z.enum(STYLEGUIDE_ENUMS.language).optional(),
1762
+ spelling: z.enum(STYLEGUIDE_ENUMS.spelling).optional(),
1763
+ quotation_style: z.enum(STYLEGUIDE_ENUMS.quotation_style).optional(),
1764
+ quotation_style_nested: z.enum(STYLEGUIDE_ENUMS.quotation_style_nested).optional(),
1765
+ em_dash_spacing: z.enum(STYLEGUIDE_ENUMS.em_dash_spacing).optional(),
1766
+ ellipsis_style: z.enum(STYLEGUIDE_ENUMS.ellipsis_style).optional(),
1767
+ abbreviation_periods: z.enum(STYLEGUIDE_ENUMS.abbreviation_periods).optional(),
1768
+ oxford_comma: z.enum(STYLEGUIDE_ENUMS.oxford_comma).optional(),
1769
+ numbers: z.enum(STYLEGUIDE_ENUMS.numbers).optional(),
1770
+ date_format: z.enum(STYLEGUIDE_ENUMS.date_format).optional(),
1771
+ time_format: z.enum(STYLEGUIDE_ENUMS.time_format).optional(),
1772
+ tense: z.string().optional(),
1773
+ pov: z.enum(STYLEGUIDE_ENUMS.pov).optional(),
1774
+ dialogue_tags: z.enum(STYLEGUIDE_ENUMS.dialogue_tags).optional(),
1775
+ sentence_fragments: z.enum(STYLEGUIDE_ENUMS.sentence_fragments).optional(),
1776
+ voice_notes: z.string().optional(),
1777
+ }).strict().describe("Explicit config field changes to preview at the selected scope."),
1778
+ },
1779
+ async ({ scope, project_id, updates }) => {
1780
+ if (project_id !== undefined) {
1781
+ const projectIdCheck = validateProjectId(project_id);
1782
+ if (!projectIdCheck.ok) {
1783
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1784
+ }
1785
+ }
1786
+
1787
+ if (scope === "project_root" && !project_id) {
1788
+ return errorResponse(
1789
+ "PROJECT_ID_REQUIRED",
1790
+ "project_id is required when scope=project_root."
1791
+ );
1792
+ }
1793
+
1794
+ const preview = previewStyleguideConfigUpdate({
1795
+ syncDir: SYNC_DIR,
1796
+ scope,
1797
+ projectId: project_id,
1798
+ updates,
1799
+ });
1800
+ if (!preview.ok) {
1801
+ return errorResponse(
1802
+ preview.error.code,
1803
+ preview.error.message,
1804
+ preview.error.details
1805
+ );
1806
+ }
1807
+
1808
+ return jsonResponse({
1809
+ ok: true,
1810
+ scope: preview.scope,
1811
+ project_id: preview.project_id,
1812
+ file_path: path.resolve(preview.file_path),
1813
+ current_config: preview.current_config,
1814
+ next_config: preview.config,
1815
+ changed_fields: preview.changed_fields,
1816
+ noop: preview.changed_fields.length === 0,
1817
+ message: preview.changed_fields.length === 0
1818
+ ? "No changes detected for requested styleguide updates."
1819
+ : "Preview generated.",
1820
+ warnings: preview.warnings,
1821
+ });
1822
+ }
1823
+ );
1824
+
1825
+ s.tool(
1826
+ "check_prose_styleguide_drift",
1827
+ "Detect styleguide drift by comparing declared config conventions against observed signals in scene prose.",
1828
+ {
1829
+ project_id: z.string().describe("Project ID to analyze (e.g. 'the-lamb' or 'universe-1/book-1')."),
1830
+ scene_ids: z.array(z.string()).optional().describe("Optional scene_id allowlist to analyze."),
1831
+ part: z.number().int().optional().describe("Optional part filter."),
1832
+ chapter: z.number().int().optional().describe("Optional chapter filter."),
1833
+ max_scenes: z.number().int().positive().optional().describe("Maximum number of scenes to analyze (default: 50)."),
1834
+ min_agreement: z.number().min(0).max(1).optional().describe("Minimum agreement ratio for suggested updates (default: 0.6)."),
1835
+ include_clean_scenes: z.boolean().optional().describe("If true, include scenes with no detected drift in scene_results."),
1836
+ },
1837
+ async ({
1838
+ project_id,
1839
+ scene_ids,
1840
+ part,
1841
+ chapter,
1842
+ max_scenes = 50,
1843
+ min_agreement = 0.6,
1844
+ include_clean_scenes = false,
1845
+ }) => {
1846
+ const projectIdCheck = validateProjectId(project_id);
1847
+ if (!projectIdCheck.ok) {
1848
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
1849
+ }
1850
+
1851
+ const resolved = resolveStyleguideConfig({
1852
+ syncDir: SYNC_DIR,
1853
+ projectId: project_id,
1854
+ });
1855
+ if (!resolved.ok) {
1856
+ return errorResponse(
1857
+ resolved.error.code,
1858
+ resolved.error.message,
1859
+ resolved.error.details
1860
+ );
1861
+ }
1862
+ if (resolved.setup_required || !resolved.resolved_config) {
1863
+ return errorResponse(
1864
+ "STYLEGUIDE_CONFIG_REQUIRED",
1865
+ "Cannot check prose styleguide drift before prose-styleguide.config.yaml is set up.",
1866
+ {
1867
+ project_id,
1868
+ next_step: "Run setup_prose_styleguide_config or bootstrap_prose_styleguide_config.",
1869
+ }
1870
+ );
1871
+ }
1872
+
1873
+ const targetResolution = resolveBatchTargetScenes(db, {
1874
+ projectId: project_id,
1875
+ sceneIds: scene_ids,
1876
+ part,
1877
+ chapter,
1878
+ onlyStale: false,
1879
+ });
1880
+ if (!targetResolution.ok) {
1881
+ return errorResponse(targetResolution.code, targetResolution.message, targetResolution.details);
1882
+ }
1883
+
1884
+ const targetScenes = targetResolution.rows;
1885
+ if (targetScenes.length > max_scenes) {
1886
+ return errorResponse(
1887
+ "VALIDATION_ERROR",
1888
+ `Matched ${targetScenes.length} scenes, which exceeds max_scenes=${max_scenes}.`,
1889
+ { matched_scenes: targetScenes.length, max_scenes, project_id }
1890
+ );
1891
+ }
1892
+
1893
+ const sceneAnalyses = [];
1894
+ for (const scene of targetScenes) {
1895
+ let prose;
1896
+ try {
1897
+ const raw = fs.readFileSync(scene.file_path, "utf8");
1898
+ prose = matter(raw).content;
1899
+ } catch {
1900
+ sceneAnalyses.push({
1901
+ scene_id: scene.scene_id,
1902
+ observed: {},
1903
+ drift: [{ field: "scene_file", declared: "readable", observed: "unreadable" }],
1904
+ });
1905
+ continue;
1906
+ }
1907
+
1908
+ const analysis = analyzeSceneStyleguideDrift({
1909
+ prose,
1910
+ resolvedConfig: resolved.resolved_config,
1911
+ });
1912
+ sceneAnalyses.push({
1913
+ scene_id: scene.scene_id,
1914
+ observed: analysis.observed,
1915
+ drift: analysis.drift,
1916
+ });
1917
+ }
1918
+
1919
+ const suggestedUpdates = suggestStyleguideUpdatesFromScenes({
1920
+ sceneAnalyses,
1921
+ resolvedConfig: resolved.resolved_config,
1922
+ minAgreement: min_agreement,
1923
+ });
1924
+
1925
+ const filteredScenes = include_clean_scenes
1926
+ ? sceneAnalyses
1927
+ : sceneAnalyses.filter((scene) => scene.drift.length > 0);
1928
+
1929
+ const driftByField = {};
1930
+ for (const scene of sceneAnalyses) {
1931
+ for (const entry of scene.drift) {
1932
+ driftByField[entry.field] = (driftByField[entry.field] ?? 0) + 1;
1933
+ }
1934
+ }
1935
+
1936
+ return jsonResponse({
1937
+ ok: true,
1938
+ project_id,
1939
+ checked_scenes: sceneAnalyses.length,
1940
+ scenes_with_drift: sceneAnalyses.filter((scene) => scene.drift.length > 0).length,
1941
+ drift_by_field: driftByField,
1942
+ scene_results: filteredScenes,
1943
+ suggested_updates: suggestedUpdates,
1944
+ });
1945
+ }
1946
+ );
1947
+
1521
1948
  s.tool(
1522
1949
  "setup_prose_styleguide_skill",
1523
1950
  "Generate skills/prose-styleguide.md from the resolved prose styleguide config and universal craft rules.",
@@ -1558,7 +1985,7 @@ function createMcpServer() {
1558
1985
  "Cannot generate prose-styleguide.md before prose-styleguide.config.yaml is set up.",
1559
1986
  {
1560
1987
  project_id: project_id ?? null,
1561
- next_step: "Run setup_prose_styleguide_config first.",
1988
+ next_step: "Run setup_prose_styleguide_config or bootstrap_prose_styleguide_config first.",
1562
1989
  }
1563
1990
  );
1564
1991
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hanna84/mcp-writing",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
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",
@@ -18,6 +18,7 @@
18
18
  "scene-character-normalization.js",
19
19
  "review-bundles.js",
20
20
  "prose-styleguide.js",
21
+ "prose-styleguide-drift.js",
21
22
  "prose-styleguide-skill.js",
22
23
  "scripts/",
23
24
  "README.md",
@@ -0,0 +1,125 @@
1
+ function detectQuotationStyle(prose) {
2
+ const counts = {
3
+ double: (prose.match(/"[^"]{2,}"/g) ?? []).length,
4
+ guillemets: (prose.match(/«[^»]{2,}»/g) ?? []).length,
5
+ low9: (prose.match(/„[^“]{2,}“/g) ?? []).length,
6
+ corner_brackets: (prose.match(/「[^」]{2,}」/g) ?? []).length,
7
+ dialogue_dash_en: (prose.match(/^\s*–\s/mg) ?? []).length,
8
+ dialogue_dash_em: (prose.match(/^\s*—\s/mg) ?? []).length,
9
+ single: (prose.match(/'[^'\n]{2,}'/g) ?? []).length,
10
+ };
11
+
12
+ let best = null;
13
+ let bestCount = 0;
14
+ for (const [style, count] of Object.entries(counts)) {
15
+ if (count > bestCount) {
16
+ best = style;
17
+ bestCount = count;
18
+ }
19
+ }
20
+ return bestCount > 0 ? best : null;
21
+ }
22
+
23
+ function detectEmDashSpacing(prose) {
24
+ const spaced = (prose.match(/\s—\s/g) ?? []).length;
25
+ const closed = (prose.match(/\S—\S/g) ?? []).length;
26
+ if (spaced === 0 && closed === 0) return null;
27
+ return spaced >= closed ? "spaced" : "closed";
28
+ }
29
+
30
+ function detectSpellingVariant(prose) {
31
+ const lower = prose.toLowerCase();
32
+ const ukSignals = ["colour", "realise", "centre", "honour", "travelling"];
33
+ const usSignals = ["color", "realize", "center", "honor", "traveling"];
34
+
35
+ const countHits = (signals) => signals.reduce((sum, word) => {
36
+ const re = new RegExp(`\\b${word}\\b`, "g");
37
+ return sum + (lower.match(re) ?? []).length;
38
+ }, 0);
39
+
40
+ const uk = countHits(ukSignals);
41
+ const us = countHits(usSignals);
42
+ if (uk === 0 && us === 0) return null;
43
+ return uk >= us ? "uk" : "us";
44
+ }
45
+
46
+ function detectTenseHint(prose) {
47
+ const lower = prose.toLowerCase();
48
+ const past = (lower.match(/\b(was|were|had|did)\b/g) ?? []).length;
49
+ const present = (lower.match(/\b(is|are|has|do)\b/g) ?? []).length;
50
+ if (past === 0 && present === 0) return null;
51
+ return present >= past ? "present" : "past";
52
+ }
53
+
54
+ function mostCommonValue(values) {
55
+ const counts = new Map();
56
+ for (const value of values) {
57
+ if (!value) continue;
58
+ counts.set(value, (counts.get(value) ?? 0) + 1);
59
+ }
60
+ if (counts.size === 0) return null;
61
+
62
+ let bestValue = null;
63
+ let bestCount = 0;
64
+ for (const [value, count] of counts.entries()) {
65
+ if (count > bestCount) {
66
+ bestValue = value;
67
+ bestCount = count;
68
+ }
69
+ }
70
+ return { value: bestValue, count: bestCount, total: values.filter(Boolean).length };
71
+ }
72
+
73
+ export function detectStyleguideSignals(prose) {
74
+ return {
75
+ quotation_style: detectQuotationStyle(prose),
76
+ em_dash_spacing: detectEmDashSpacing(prose),
77
+ spelling: detectSpellingVariant(prose),
78
+ tense: detectTenseHint(prose),
79
+ };
80
+ }
81
+
82
+ export function analyzeSceneStyleguideDrift({ prose, resolvedConfig }) {
83
+ const observed = detectStyleguideSignals(prose);
84
+ const drift = [];
85
+
86
+ for (const field of ["quotation_style", "em_dash_spacing", "spelling", "tense"]) {
87
+ const declared = resolvedConfig?.[field];
88
+ const seen = observed[field];
89
+ if (!declared || !seen) continue;
90
+ if (declared !== seen) {
91
+ drift.push({ field, declared, observed: seen });
92
+ }
93
+ }
94
+
95
+ return { observed, drift };
96
+ }
97
+
98
+ export function suggestStyleguideUpdatesFromScenes({
99
+ sceneAnalyses,
100
+ resolvedConfig,
101
+ minAgreement = 0.6,
102
+ minEvidence = 3,
103
+ }) {
104
+ const suggestions = {};
105
+
106
+ for (const field of ["quotation_style", "em_dash_spacing", "spelling", "tense"]) {
107
+ const values = sceneAnalyses.map((scene) => scene.observed?.[field] ?? null);
108
+ const common = mostCommonValue(values);
109
+ if (!common) continue;
110
+ if (common.total < minEvidence) continue;
111
+
112
+ const agreement = common.total > 0 ? common.count / common.total : 0;
113
+ const fieldThreshold = field === "tense" ? Math.max(minAgreement, 0.75) : minAgreement;
114
+ if (agreement < fieldThreshold) continue;
115
+ if (resolvedConfig?.[field] === common.value) continue;
116
+
117
+ suggestions[field] = {
118
+ suggested_value: common.value,
119
+ agreement,
120
+ based_on_scenes: common.total,
121
+ };
122
+ }
123
+
124
+ return suggestions;
125
+ }
@@ -67,6 +67,25 @@ export const STYLEGUIDE_ENUMS = Object.freeze(
67
67
  )
68
68
  );
69
69
 
70
+ const STYLEGUIDE_FIELD_ORDER = [
71
+ "language",
72
+ "spelling",
73
+ "quotation_style",
74
+ "quotation_style_nested",
75
+ "em_dash_spacing",
76
+ "ellipsis_style",
77
+ "abbreviation_periods",
78
+ "oxford_comma",
79
+ "numbers",
80
+ "date_format",
81
+ "time_format",
82
+ "tense",
83
+ "pov",
84
+ "dialogue_tags",
85
+ "sentence_fragments",
86
+ "voice_notes",
87
+ ];
88
+
70
89
  // Fields that are valid in a config but are not enum-constrained.
71
90
  const SPECIAL_FIELDS = new Set(["voice_notes"]);
72
91
 
@@ -344,6 +363,98 @@ function readConfigFile(filePath) {
344
363
  };
345
364
  }
346
365
 
366
+ function configPathForScope(syncDir, scope, projectId) {
367
+ if (scope === "sync_root") {
368
+ return path.join(syncDir, STYLEGUIDE_CONFIG_BASENAME);
369
+ }
370
+ return path.join(projectRootFromId(syncDir, projectId), STYLEGUIDE_CONFIG_BASENAME);
371
+ }
372
+
373
+ function prepareStyleguideConfigUpdate({ syncDir, scope, projectId, updates = {} }) {
374
+ if (scope === "project_root" && !projectId) {
375
+ return {
376
+ ok: false,
377
+ error: {
378
+ code: "PROJECT_ID_REQUIRED",
379
+ message: "project_id is required when scope=project_root.",
380
+ details: { scope, project_id: projectId ?? null },
381
+ },
382
+ };
383
+ }
384
+
385
+ const filePath = configPathForScope(syncDir, scope, projectId);
386
+ const current = readConfigFile(filePath);
387
+
388
+ if (current === null) {
389
+ return {
390
+ ok: false,
391
+ error: {
392
+ code: "STYLEGUIDE_CONFIG_NOT_FOUND",
393
+ message: "Cannot update styleguide config because no config exists at the requested scope.",
394
+ details: { file_path: filePath, scope, project_id: projectId ?? null },
395
+ },
396
+ };
397
+ }
398
+
399
+ if (!current.ok) {
400
+ return {
401
+ ok: false,
402
+ error: {
403
+ code: "INVALID_STYLEGUIDE_CONFIG",
404
+ message: "Styleguide config validation failed.",
405
+ details: { file_path: filePath, issues: current.errors },
406
+ },
407
+ };
408
+ }
409
+
410
+ const validatedUpdates = validateConfig(updates, "<updates>");
411
+ if (validatedUpdates.errors.length > 0) {
412
+ return {
413
+ ok: false,
414
+ error: {
415
+ code: "INVALID_STYLEGUIDE_UPDATE",
416
+ message: "Requested styleguide updates failed validation.",
417
+ details: validatedUpdates.errors,
418
+ },
419
+ };
420
+ }
421
+
422
+ const merged = Object.create(null);
423
+ Object.assign(merged, current.config, validatedUpdates.normalized);
424
+
425
+ const ordered = Object.create(null);
426
+ for (const key of STYLEGUIDE_FIELD_ORDER) {
427
+ if (merged[key] !== undefined) {
428
+ ordered[key] = merged[key];
429
+ }
430
+ }
431
+
432
+ const changedFields = [];
433
+ const allKeys = new Set([...Object.keys(current.config ?? {}), ...Object.keys(ordered)]);
434
+ for (const key of allKeys) {
435
+ if (current.config?.[key] !== ordered[key]) {
436
+ changedFields.push({
437
+ field: key,
438
+ before: current.config?.[key],
439
+ after: ordered[key],
440
+ });
441
+ }
442
+ }
443
+
444
+ return {
445
+ ok: true,
446
+ file_path: filePath,
447
+ scope,
448
+ project_id: projectId ?? null,
449
+ current_config: current.config,
450
+ config: ordered,
451
+ changed_fields: changedFields,
452
+ warnings: {
453
+ unknown_fields: validatedUpdates.unknownFields,
454
+ },
455
+ };
456
+ }
457
+
347
458
  function getConfigCandidates(syncDir, projectId) {
348
459
  const candidates = [
349
460
  {
@@ -442,6 +553,80 @@ export function buildStyleguideConfigDraft({ language, overrides = {}, voice_not
442
553
  };
443
554
  }
444
555
 
556
+ export function summarizeStyleguideConfig({ resolvedConfig, inferredDefaults = {} }) {
557
+ if (!resolvedConfig || typeof resolvedConfig !== "object") {
558
+ return {
559
+ ok: false,
560
+ error: {
561
+ code: "INVALID_STYLEGUIDE_CONFIG",
562
+ message: "Cannot summarize styleguide config without a resolved config object.",
563
+ },
564
+ };
565
+ }
566
+
567
+ const lines = [];
568
+ if (resolvedConfig.language) lines.push(`Writing language: ${resolvedConfig.language}.`);
569
+ if (resolvedConfig.spelling) lines.push(`Spelling variant: ${resolvedConfig.spelling}.`);
570
+ if (resolvedConfig.quotation_style) lines.push(`Dialogue punctuation uses ${resolvedConfig.quotation_style}.`);
571
+ if (resolvedConfig.quotation_style_nested) lines.push(`Nested quotations use ${resolvedConfig.quotation_style_nested}.`);
572
+ if (resolvedConfig.tense) lines.push(`Default narrative tense: ${resolvedConfig.tense}.`);
573
+ if (resolvedConfig.pov) lines.push(`Default POV: ${resolvedConfig.pov}.`);
574
+ if (resolvedConfig.dialogue_tags) lines.push(`Dialogue tag policy: ${resolvedConfig.dialogue_tags}.`);
575
+ if (resolvedConfig.sentence_fragments) lines.push(`Sentence fragments: ${resolvedConfig.sentence_fragments}.`);
576
+ if (resolvedConfig.date_format) lines.push(`Date format: ${resolvedConfig.date_format}.`);
577
+ if (resolvedConfig.time_format) lines.push(`Time format: ${resolvedConfig.time_format}.`);
578
+ if (resolvedConfig.voice_notes) lines.push(`Voice notes: ${resolvedConfig.voice_notes}`);
579
+
580
+ const inferred = Object.keys(inferredDefaults);
581
+ if (inferred.length > 0) {
582
+ lines.push(`Inferred defaults currently fill: ${inferred.join(", ")}.`);
583
+ }
584
+
585
+ return {
586
+ ok: true,
587
+ summary_text: lines.join(" "),
588
+ summary_lines: lines,
589
+ };
590
+ }
591
+
592
+ export function updateStyleguideConfig({ syncDir, scope, projectId, updates = {} }) {
593
+ const prepared = prepareStyleguideConfigUpdate({ syncDir, scope, projectId, updates });
594
+ if (!prepared.ok) return prepared;
595
+
596
+ if (prepared.changed_fields.length === 0) {
597
+ return {
598
+ ok: true,
599
+ file_path: prepared.file_path,
600
+ scope: prepared.scope,
601
+ project_id: prepared.project_id,
602
+ config: prepared.config,
603
+ changed_fields: prepared.changed_fields,
604
+ warnings: prepared.warnings,
605
+ noop: true,
606
+ message: "No changes detected for requested styleguide updates.",
607
+ };
608
+ }
609
+
610
+ fs.mkdirSync(path.dirname(prepared.file_path), { recursive: true });
611
+ fs.writeFileSync(prepared.file_path, yaml.dump(prepared.config, { lineWidth: 120 }), "utf8");
612
+
613
+ return {
614
+ ok: true,
615
+ file_path: prepared.file_path,
616
+ scope: prepared.scope,
617
+ project_id: prepared.project_id,
618
+ config: prepared.config,
619
+ changed_fields: prepared.changed_fields,
620
+ warnings: prepared.warnings,
621
+ noop: false,
622
+ message: "Styleguide config updated.",
623
+ };
624
+ }
625
+
626
+ export function previewStyleguideConfigUpdate({ syncDir, scope, projectId, updates = {} }) {
627
+ return prepareStyleguideConfigUpdate({ syncDir, scope, projectId, updates });
628
+ }
629
+
445
630
  export function resolveStyleguideConfig({ syncDir, projectId }) {
446
631
  const candidates = getConfigCandidates(syncDir, projectId);
447
632
  const sources = [];