dravoice 0.1.0 → 0.1.2

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Dravoice contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dravoice contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,21 +1,22 @@
1
- # Dravoice
2
-
3
- Dravoice is a local-first CLI for compiling Markdown, MDX, and plain-text
4
- writing corpora into reusable voice guidance and deterministic draft review
5
- notes.
6
-
7
- It is not an AI-authorship detector, grammar checker, prose linter, or
8
- third-party author imitation tool. It helps a writer inspect and reuse their
9
- own measurable rhythm, register, evidence habits, discourse shape, and
10
- structure.
11
-
12
- ## Quick Start
13
-
14
- ```bash
15
- npx --package dravoice drav learn --examples ./articles --out ./dravoice-voice
16
- npx --package dravoice drav inspect --voice ./dravoice-voice
1
+ # Dravoice
2
+
3
+ Dravoice is a local-first CLI for compiling Markdown, MDX, and plain-text
4
+ writing corpora into reusable voice guidance and deterministic draft review
5
+ notes.
6
+
7
+ It is not an AI-authorship detector, grammar checker, prose linter, or
8
+ third-party author imitation tool. It helps a writer inspect and reuse their
9
+ own measurable rhythm, register, evidence habits, discourse shape, and
10
+ structure.
11
+
12
+ ## Quick Start
13
+
14
+ ```bash
15
+ npx --package dravoice drav learn --examples ./articles --out ./dravoice-voice
16
+ npx --package dravoice drav inspect --voice ./dravoice-voice
17
17
  npx --package dravoice drav prompt --voice ./dravoice-voice --format agents --out AGENTS.md
18
18
  npx --package dravoice drav brief --voice ./dravoice-voice --topic "A new article topic" --evidence notes.md --out brief.md
19
+ npx --package dravoice drav revise-plan draft.md --voice ./dravoice-voice
19
20
  npx --package dravoice drav review draft.md --voice ./dravoice-voice
20
21
  npx --package dravoice drav review draft.md --voice ./dravoice-voice --mode strict --format json
21
22
  ```
@@ -23,13 +24,14 @@ npx --package dravoice drav review draft.md --voice ./dravoice-voice --mode stri
23
24
  `learn` writes a schemaVersion 2 `profile.json` plus local metadata. `inspect`
24
25
  makes the learned feature families visible, `prompt` turns high-confidence
25
26
  observations into drafting guidance, `brief` creates an evidence-first article
26
- plan, and `review` reports family-level drift.
27
-
28
- ## Fresh Install Smoke Test
29
-
30
- From a packed tarball:
31
-
32
- ```bash
33
- npm pack
34
- npm exec --package ./dravoice-0.1.0.tgz -- drav --help
35
- ```
27
+ plan, `revise-plan` ranks calibrated stylometric revision actions, and `review`
28
+ reports family-level drift.
29
+
30
+ ## Fresh Install Smoke Test
31
+
32
+ From a packed tarball:
33
+
34
+ ```bash
35
+ npm pack
36
+ npm exec --package ./dravoice-0.1.1.tgz -- drav --help
37
+ ```
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dravoice",
3
- "version": "0.1.0",
4
- "description": "Compile article voice profiles into reusable LLM writing context, evidence-first briefs, and deterministic draft review notes.",
3
+ "version": "0.1.2",
4
+ "description": "Compile article voice profiles into reusable LLM writing context, evidence-first briefs, and deterministic draft review notes.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "drav": "bin/dravoice.js"
package/src/index.js CHANGED
@@ -1,25 +1,27 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import {
4
- prepareVoiceBenchmark,
5
- renderBenchmarkReport,
6
- scoreVoiceBenchmark,
7
- } from "./v2/benchmark.js";
8
- import { renderVoiceBriefV2, voiceArticleBriefV2 } from "./v2/brief.js";
9
- import { renderInspectV2 } from "./v2/inspect.js";
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import {
4
+ prepareVoiceBenchmark,
5
+ renderBenchmarkReport,
6
+ scoreVoiceBenchmark,
7
+ } from "./v2/benchmark.js";
8
+ import { renderVoiceBriefV2, voiceArticleBriefV2 } from "./v2/brief.js";
9
+ import { renderInspectV2 } from "./v2/inspect.js";
10
10
  import { learnVoicePackV2, loadVoicePackV2 } from "./v2/profile.js";
11
11
  import { voicePromptPackV2 } from "./v2/prompt.js";
12
12
  import { renderVoiceReviewV2, reviewVoiceDraftV2 } from "./v2/review.js";
13
+ import { renderRevisePlanV2, revisePlanDraftV2 } from "./v2/revise-plan.js";
13
14
 
14
15
  export {
15
16
  learnVoicePackV2 as learnVoicePack,
16
- loadVoicePackV2 as loadVoicePack,
17
- reviewVoiceDraftV2 as reviewVoiceDraft,
18
- voicePromptPackV2 as voicePromptPack,
19
- };
20
- export { renderInspectV2, renderVoiceReviewV2 as renderVoiceReview };
21
- export { renderVoiceBriefV2 as renderVoiceBrief, voiceArticleBriefV2 as voiceArticleBrief };
22
- export { prepareVoiceBenchmark, renderBenchmarkReport, scoreVoiceBenchmark };
17
+ loadVoicePackV2 as loadVoicePack,
18
+ revisePlanDraftV2 as revisePlanDraft,
19
+ reviewVoiceDraftV2 as reviewVoiceDraft,
20
+ voicePromptPackV2 as voicePromptPack,
21
+ };
22
+ export { renderInspectV2, renderRevisePlanV2 as renderRevisePlan, renderVoiceReviewV2 as renderVoiceReview };
23
+ export { renderVoiceBriefV2 as renderVoiceBrief, voiceArticleBriefV2 as voiceArticleBrief };
24
+ export { prepareVoiceBenchmark, renderBenchmarkReport, scoreVoiceBenchmark };
23
25
 
24
26
  export async function runCli(args, io) {
25
27
  try {
@@ -39,7 +41,7 @@ export async function runCli(args, io) {
39
41
  return 0;
40
42
  }
41
43
 
42
- if (command === "review") {
44
+ if (command === "review") {
43
45
  const { options, positional } = parseArgs(rest, ["voice", "mode", "format"]);
44
46
  const file = positional[0];
45
47
  if (!file) {
@@ -56,46 +58,65 @@ export async function runCli(args, io) {
56
58
  } else {
57
59
  io.stdout.write(renderVoiceReviewV2(result));
58
60
  }
59
- return result.exitCode;
60
- }
61
-
62
- if (command === "prompt") {
63
- const { options } = parseArgs(rest, ["voice", "format", "out"]);
64
- const rendered = voicePromptPackV2({
65
- voice: loadVoicePackV2(resolvePath(io.cwd, options.voice ?? ".")),
66
- format: options.format ?? "agents",
67
- outPath: options.out ? resolvePath(io.cwd, options.out) : undefined,
68
- });
69
- if (!options.out) {
70
- io.stdout.write(rendered);
71
- }
72
- return 0;
61
+ return result.exitCode;
73
62
  }
74
63
 
75
- if (command === "brief") {
76
- const { options } = parseArgs(rest, ["voice", "topic", "evidence", "format", "out"]);
77
- const result = voiceArticleBriefV2({
64
+ if (command === "revise-plan") {
65
+ const { options, positional } = parseArgs(rest, ["voice", "format"]);
66
+ const file = positional[0];
67
+ if (!file) {
68
+ throw new Error("Missing draft file path for revise-plan");
69
+ }
70
+ const result = revisePlanDraftV2({
71
+ file: resolvePath(io.cwd, file),
78
72
  voice: loadVoicePackV2(resolvePath(io.cwd, options.voice ?? ".")),
79
- topic: requiredOption(options, "topic"),
80
- evidence: options.evidence ? resolvePath(io.cwd, options.evidence) : undefined,
81
73
  cwd: io.cwd,
82
74
  });
83
- const rendered = options.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderVoiceBriefV2(result);
84
- if (options.out) {
85
- const outPath = resolvePath(io.cwd, options.out);
86
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
87
- fs.writeFileSync(outPath, rendered, "utf8");
75
+ if (options.format === "json") {
76
+ io.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
88
77
  } else {
89
- io.stdout.write(rendered);
78
+ io.stdout.write(renderRevisePlanV2(result));
90
79
  }
91
80
  return 0;
92
81
  }
93
82
 
94
- if (command === "inspect") {
95
- const { options } = parseArgs(rest, ["voice"]);
96
- const profile = loadVoicePackV2(resolvePath(io.cwd, options.voice ?? "."));
97
- io.stdout.write(renderInspectV2(profile));
98
- return 0;
83
+ if (command === "prompt") {
84
+ const { options } = parseArgs(rest, ["voice", "format", "out"]);
85
+ const rendered = voicePromptPackV2({
86
+ voice: loadVoicePackV2(resolvePath(io.cwd, options.voice ?? ".")),
87
+ format: options.format ?? "agents",
88
+ outPath: options.out ? resolvePath(io.cwd, options.out) : undefined,
89
+ });
90
+ if (!options.out) {
91
+ io.stdout.write(rendered);
92
+ }
93
+ return 0;
94
+ }
95
+
96
+ if (command === "brief") {
97
+ const { options } = parseArgs(rest, ["voice", "topic", "evidence", "format", "out"]);
98
+ const result = voiceArticleBriefV2({
99
+ voice: loadVoicePackV2(resolvePath(io.cwd, options.voice ?? ".")),
100
+ topic: requiredOption(options, "topic"),
101
+ evidence: options.evidence ? resolvePath(io.cwd, options.evidence) : undefined,
102
+ cwd: io.cwd,
103
+ });
104
+ const rendered = options.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderVoiceBriefV2(result);
105
+ if (options.out) {
106
+ const outPath = resolvePath(io.cwd, options.out);
107
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
108
+ fs.writeFileSync(outPath, rendered, "utf8");
109
+ } else {
110
+ io.stdout.write(rendered);
111
+ }
112
+ return 0;
113
+ }
114
+
115
+ if (command === "inspect") {
116
+ const { options } = parseArgs(rest, ["voice"]);
117
+ const profile = loadVoicePackV2(resolvePath(io.cwd, options.voice ?? "."));
118
+ io.stdout.write(renderInspectV2(profile));
119
+ return 0;
99
120
  }
100
121
 
101
122
  if (command === "benchmark") {
@@ -190,15 +211,16 @@ function resolvePath(cwd, value) {
190
211
  return path.isAbsolute(value) ? value : path.join(cwd, value);
191
212
  }
192
213
 
193
- function helpText() {
194
- return [
195
- "drav learn --examples ./articles --out ./dravoice-voice",
196
- "drav inspect --voice ./dravoice-voice",
197
- "drav prompt --voice ./dravoice-voice --format agents --out AGENTS.md",
214
+ function helpText() {
215
+ return [
216
+ "drav learn --examples ./articles --out ./dravoice-voice",
217
+ "drav inspect --voice ./dravoice-voice",
218
+ "drav prompt --voice ./dravoice-voice --format agents --out AGENTS.md",
198
219
  "drav brief --voice ./dravoice-voice --topic \"New topic\" --evidence notes.md --out brief.md",
199
220
  "drav review draft.md --voice ./dravoice-voice --mode balanced --format text",
221
+ "drav revise-plan draft.md --voice ./dravoice-voice --format text",
200
222
  "drav benchmark prepare --examples ./articles --topic \"New topic\" --out ./bench-run --seed 42",
201
- "drav benchmark score --run ./bench-run --judge ./bench-run/judge/judgment.json",
202
- "",
203
- ].join("\n");
204
- }
223
+ "drav benchmark score --run ./bench-run --judge ./bench-run/judge/judgment.json",
224
+ "",
225
+ ].join("\n");
226
+ }
@@ -12,6 +12,7 @@ const TRANSITIONS = {
12
12
  export function analyzeDiscourse(documents) {
13
13
  const sentences = documents.flatMap((document) => document.sentences);
14
14
  const labels = sentences.map((sentence) => transitionLabel(sentence.text));
15
+ const nonPlainLabels = labels.filter((label) => label !== "plain");
15
16
  const transitionRates = {};
16
17
  for (const key of Object.keys(TRANSITIONS)) {
17
18
  transitionRates[key] = rate(labels.filter((label) => label === key).length, sentences.length, 2);
@@ -22,10 +23,12 @@ export function analyzeDiscourse(documents) {
22
23
  confidence: sentences.length >= 12 ? "medium" : "low",
23
24
  features: {
24
25
  transitionRates,
25
- transitionSequence: labels.filter(Boolean).slice(0, 12),
26
+ transitionSequence: labels.slice(0, 12),
27
+ transitionBigrams: topItems(sequenceNgrams(labels, 2), 12),
28
+ transitionTrigrams: topItems(sequenceNgrams(labels, 3), 12),
26
29
  sentenceCallbacks: callbackRate(sentences),
27
30
  },
28
- examples: topItems(labels.filter(Boolean), 5).map((item) => item.value),
31
+ examples: topItems(nonPlainLabels, 5).map((item) => item.value),
29
32
  warnings: sentences.length < 12 ? ["Discourse confidence is limited because the corpus has fewer than 12 sentences."] : [],
30
33
  revisionHandles: ["Compare how sentences turn, contrast, explain, and return to earlier ideas."],
31
34
  };
@@ -50,3 +53,11 @@ function callbackRate(sentences) {
50
53
  }
51
54
  return rate(callbacks, Math.max(1, sentences.length - 1), 2);
52
55
  }
56
+
57
+ function sequenceNgrams(values, size) {
58
+ const result = [];
59
+ for (let index = 0; index <= values.length - size; index += 1) {
60
+ result.push(values.slice(index, index + size).join(" -> "));
61
+ }
62
+ return result;
63
+ }
@@ -14,30 +14,69 @@ const EVIDENCE_PATTERNS = {
14
14
  const ABSTRACT_CLAIM_RE = /\b(always|never|everyone|everything|nothing|best|better|worse|important|obvious|clearly|should|must|need to|have to|all|none|every)\b/i;
15
15
 
16
16
  export function analyzeEvidence(documents) {
17
- const sentences = documents.flatMap((document) => document.sentences);
18
- const evidenceSentences = sentences.filter((sentence) => evidenceTypes(sentence.text).length > 0);
19
- const claimSentences = sentences.filter((sentence) => ABSTRACT_CLAIM_RE.test(sentence.text));
20
- const typeValues = evidenceSentences.flatMap((sentence) => evidenceTypes(sentence.text));
17
+ const documentResults = documents.map(documentEvidence);
18
+ const sentenceCount = documentResults.reduce((sum, item) => sum + item.sentenceCount, 0);
19
+ const evidenceSentenceCount = documentResults.reduce((sum, item) => sum + item.evidenceSentenceCount, 0);
20
+ const claimSentenceCount = documentResults.reduce((sum, item) => sum + item.claimSentenceCount, 0);
21
+ const supportedClaimCount = documentResults.reduce((sum, item) => sum + item.supportedClaimCount, 0);
22
+ const unsupportedClaimCount = documentResults.reduce((sum, item) => sum + item.unsupportedClaimCount, 0);
23
+ const typeValues = documentResults.flatMap((item) => item.typeValues);
21
24
 
22
25
  return {
23
26
  family: "evidence",
24
- confidence: sentences.length >= 12 ? "medium" : "low",
27
+ confidence: sentenceCount >= 12 ? "medium" : "low",
25
28
  features: {
26
- sentenceCount: sentences.length,
27
- evidenceSentenceCount: evidenceSentences.length,
28
- evidenceSentenceRate: rate(evidenceSentences.length, sentences.length, 2),
29
- claimSentenceRate: rate(claimSentences.length, sentences.length, 2),
30
- unsupportedClaimRate: rate(Math.max(0, claimSentences.length - evidenceSentences.length), sentences.length, 2),
29
+ sentenceCount,
30
+ evidenceSentenceCount,
31
+ evidenceSentenceRate: rate(evidenceSentenceCount, sentenceCount, 2),
32
+ claimSentenceCount,
33
+ claimSentenceRate: rate(claimSentenceCount, sentenceCount, 2),
34
+ supportedClaimRate: rate(supportedClaimCount, Math.max(1, claimSentenceCount), 2),
35
+ unsupportedClaimRate: rate(unsupportedClaimCount, Math.max(1, claimSentenceCount), 2),
31
36
  evidenceTypes: topItems(typeValues, 8),
32
37
  },
33
38
  examples: topItems(typeValues, 4).map((item) => `${item.value}: ${item.count}`),
34
- warnings: sentences.length < 12 ? ["Evidence confidence is limited because the corpus has fewer than 12 sentences."] : [],
39
+ warnings: sentenceCount < 12 ? ["Evidence confidence is limited because the corpus has fewer than 12 sentences."] : [],
35
40
  revisionHandles: ["Compare how broad claims are supported by concrete scenes, numbers, quotes, citations, or examples."],
36
41
  };
37
42
  }
38
43
 
44
+ function documentEvidence(document) {
45
+ const sentences = document.sentences;
46
+ const sentenceEvidenceTypes = sentences.map((sentence) => evidenceTypes(sentence.text));
47
+ const evidenceSentences = sentences.filter((_, index) => sentenceEvidenceTypes[index].length > 0);
48
+ const claimIndexes = sentences
49
+ .map((sentence, index) => ({ sentence, index }))
50
+ .filter(({ sentence }) => ABSTRACT_CLAIM_RE.test(sentence.text))
51
+ .map(({ index }) => index);
52
+ const supportedClaimIndexes = claimIndexes.filter((index) => hasNearbyEvidence(sentenceEvidenceTypes, index));
53
+ return {
54
+ sentenceCount: sentences.length,
55
+ evidenceSentenceCount: evidenceSentences.length,
56
+ claimSentenceCount: claimIndexes.length,
57
+ supportedClaimCount: supportedClaimIndexes.length,
58
+ unsupportedClaimCount: claimIndexes.length - supportedClaimIndexes.length,
59
+ typeValues: evidenceSentences.flatMap((sentence) => evidenceTypes(sentence.text)),
60
+ };
61
+ }
62
+
63
+ function hasNearbyEvidence(sentenceEvidenceTypes, claimIndex) {
64
+ const start = Math.max(0, claimIndex - 2);
65
+ const end = Math.min(sentenceEvidenceTypes.length - 1, claimIndex + 2);
66
+ for (let index = start; index <= end; index += 1) {
67
+ if (sentenceEvidenceTypes[index].length > 0) {
68
+ return true;
69
+ }
70
+ }
71
+ return false;
72
+ }
73
+
39
74
  export function evidenceTypes(text) {
40
75
  return Object.entries(EVIDENCE_PATTERNS)
41
76
  .filter(([, pattern]) => pattern.test(text))
42
77
  .map(([type]) => type);
43
78
  }
79
+
80
+ export function isAbstractClaim(text) {
81
+ return ABSTRACT_CLAIM_RE.test(text);
82
+ }
@@ -3,6 +3,7 @@ import {
3
3
  characterNgrams,
4
4
  contentWords,
5
5
  distribution,
6
+ normalizeText,
6
7
  rate,
7
8
  tokenizeWords,
8
9
  topItems,
@@ -27,8 +28,13 @@ export function analyzeLexical(documents) {
27
28
  },
28
29
  wordLength: distribution(words.map((word) => word.length)),
29
30
  functionWords: topItems(words.filter((word) => functionWordSet.has(word)), 24),
31
+ functionWordBigrams: topItems(tokenNgrams(words.filter((word) => functionWordSet.has(word)), 2), 36),
30
32
  characterTrigrams: topItems(characterNgrams(text, 3), 24),
33
+ maskedCharacterFourgrams: topItems(maskedCharacterNgrams(text, 4), 48),
31
34
  repeatedMotifs: topItems(content, 16).filter((item) => item.count > 1),
35
+ sentenceInitialTokens: topItems(sentences.map((sentence) => boundaryToken(sentence.tokens[0], functionWordSet)), 16),
36
+ sentenceFinalTokens: topItems(sentences.map((sentence) => boundaryToken(sentence.tokens.at(-1), functionWordSet)), 16),
37
+ punctuationNgrams: topItems(punctuationNgrams(text, 3), 16),
32
38
  punctuation: {
33
39
  commaRate: rate(count(text, /,/g), sentences.length, 2),
34
40
  semicolonRate: rate(count(text, /;/g), sentences.length, 2),
@@ -43,6 +49,56 @@ export function analyzeLexical(documents) {
43
49
  };
44
50
  }
45
51
 
52
+ function boundaryToken(word, functionWordSet) {
53
+ if (!word) {
54
+ return null;
55
+ }
56
+ if (functionWordSet.has(word)) {
57
+ return word;
58
+ }
59
+ if (/^\d+$/.test(word)) {
60
+ return "<number>";
61
+ }
62
+ return "<content>";
63
+ }
64
+
65
+ function tokenNgrams(tokens, size) {
66
+ const grams = [];
67
+ for (let index = 0; index <= tokens.length - size; index += 1) {
68
+ grams.push(tokens.slice(index, index + size).join(" "));
69
+ }
70
+ return grams;
71
+ }
72
+
73
+ function maskedCharacterNgrams(text, size) {
74
+ const functionWordSet = new Set(FUNCTION_WORDS);
75
+ const masked = normalizeText(text)
76
+ .replace(/\p{L}[\p{L}\p{N}'-]*|\p{N}+/gu, (word) => {
77
+ const normalized = word.toLowerCase().replace(/'s$/, "");
78
+ if (functionWordSet.has(normalized)) {
79
+ return normalized;
80
+ }
81
+ if (/^\p{N}+$/u.test(normalized)) {
82
+ return "@";
83
+ }
84
+ return "#";
85
+ })
86
+ .replace(/\s+/g, " ");
87
+ const grams = [];
88
+ for (let index = 0; index <= masked.length - size; index += 1) {
89
+ const gram = masked.slice(index, index + size);
90
+ if (gram.trim()) {
91
+ grams.push(gram);
92
+ }
93
+ }
94
+ return grams;
95
+ }
96
+
97
+ function punctuationNgrams(text, size) {
98
+ const marks = Array.from(String(text ?? "").matchAll(/[.,;:!?-]/g)).map((match) => match[0]);
99
+ return tokenNgrams(marks, size);
100
+ }
101
+
46
102
  function confidenceFor(wordCount) {
47
103
  if (wordCount >= 2000) {
48
104
  return "high";
@@ -6,10 +6,18 @@ export function analyzeRhetoricalShape(documents) {
6
6
  const documentMoves = documents.map((document) => document.sentences.map((sentence) => moveFor(sentence.text)));
7
7
  const sentenceMoves = documentMoves.flat();
8
8
  const openingMoves = documents.flatMap((document) => document.sentences.slice(0, 3).map((sentence) => moveFor(sentence.text)));
9
- const sequences = [];
9
+ const bigrams = [];
10
+ const trigrams = [];
11
+ const openingMovePatterns = [];
10
12
  for (const moves of documentMoves) {
13
+ if (moves.length > 0) {
14
+ openingMovePatterns.push(moves.slice(0, 3).join(" -> "));
15
+ }
11
16
  for (let index = 0; index < moves.length - 1; index += 1) {
12
- sequences.push(`${moves[index]} -> ${moves[index + 1]}`);
17
+ bigrams.push(`${moves[index]} -> ${moves[index + 1]}`);
18
+ }
19
+ for (let index = 0; index < moves.length - 2; index += 1) {
20
+ trigrams.push(`${moves[index]} -> ${moves[index + 1]} -> ${moves[index + 2]}`);
13
21
  }
14
22
  }
15
23
 
@@ -19,7 +27,10 @@ export function analyzeRhetoricalShape(documents) {
19
27
  features: {
20
28
  moveRates: topItems(sentenceMoves, 12),
21
29
  openingMoves: openingMoves.slice(0, 9),
22
- commonSequences: topItems(sequences, 12),
30
+ openingMovePatterns: topItems(openingMovePatterns, 8),
31
+ moveBigrams: topItems(bigrams, 12),
32
+ moveTrigrams: topItems(trigrams, 12),
33
+ commonSequences: topItems(bigrams, 12),
23
34
  },
24
35
  examples: openingMoves.slice(0, 5),
25
36
  warnings: sentenceMoves.length < 12 ? ["Rhetorical-shape confidence is limited because the corpus has fewer than 12 sentences."] : [],