calliope-ts 0.0.2 → 0.0.4

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.
Files changed (160) hide show
  1. package/README.md +32 -20
  2. package/dist/caesura.d.ts +33 -0
  3. package/dist/caesura.d.ts.map +1 -0
  4. package/dist/caesura.js +202 -0
  5. package/dist/calliope/boundaries.d.ts +19 -0
  6. package/dist/calliope/boundaries.d.ts.map +1 -0
  7. package/dist/calliope/boundaries.js +182 -0
  8. package/dist/calliope/bracketing.d.ts +11 -0
  9. package/dist/calliope/bracketing.d.ts.map +1 -0
  10. package/dist/calliope/bracketing.js +416 -0
  11. package/dist/calliope/deps.d.ts +4 -0
  12. package/dist/calliope/deps.d.ts.map +1 -0
  13. package/dist/calliope/deps.js +181 -0
  14. package/dist/calliope/engine.d.ts +3 -0
  15. package/dist/calliope/engine.d.ts.map +1 -0
  16. package/dist/calliope/engine.js +71 -0
  17. package/dist/calliope/feats.d.ts +9 -0
  18. package/dist/calliope/feats.d.ts.map +1 -0
  19. package/dist/calliope/feats.js +45 -0
  20. package/dist/calliope/names.d.ts +7 -0
  21. package/dist/calliope/names.d.ts.map +1 -0
  22. package/dist/calliope/names.js +42 -0
  23. package/dist/calliope/postag.d.ts +8 -0
  24. package/dist/calliope/postag.d.ts.map +1 -0
  25. package/dist/calliope/postag.js +250 -0
  26. package/dist/calliope/prosodic.d.ts +3 -0
  27. package/dist/calliope/prosodic.d.ts.map +1 -0
  28. package/dist/calliope/prosodic.js +275 -0
  29. package/dist/calliope/relstress.d.ts +4 -0
  30. package/dist/calliope/relstress.d.ts.map +1 -0
  31. package/dist/calliope/relstress.js +688 -0
  32. package/dist/calliope/stressrules.d.ts +28 -0
  33. package/dist/calliope/stressrules.d.ts.map +1 -0
  34. package/dist/calliope/stressrules.js +147 -0
  35. package/dist/calliope/syntax.d.ts +38 -0
  36. package/dist/calliope/syntax.d.ts.map +1 -0
  37. package/dist/calliope/syntax.js +234 -0
  38. package/dist/calliope/udpos.d.ts +13 -0
  39. package/dist/calliope/udpos.d.ts.map +1 -0
  40. package/dist/calliope/udpos.js +156 -0
  41. package/dist/clio/caesura.d.ts +27 -0
  42. package/dist/clio/caesura.d.ts.map +1 -0
  43. package/dist/clio/caesura.js +148 -0
  44. package/dist/clio/depfix.d.ts +13 -0
  45. package/dist/clio/depfix.d.ts.map +1 -0
  46. package/dist/clio/depfix.js +84 -0
  47. package/dist/clio/display.d.ts +32 -0
  48. package/dist/clio/display.d.ts.map +1 -0
  49. package/dist/clio/display.js +976 -0
  50. package/dist/clio/engine.d.ts +3 -0
  51. package/dist/clio/engine.d.ts.map +1 -0
  52. package/dist/clio/engine.js +28 -0
  53. package/dist/clio/parser.d.ts +10 -0
  54. package/dist/clio/parser.d.ts.map +1 -0
  55. package/dist/clio/parser.js +696 -0
  56. package/dist/clio/phonological.d.ts +41 -0
  57. package/dist/clio/phonological.d.ts.map +1 -0
  58. package/dist/clio/phonological.js +788 -0
  59. package/dist/clio/phrasestress.d.ts +6 -0
  60. package/dist/clio/phrasestress.d.ts.map +1 -0
  61. package/dist/clio/phrasestress.js +106 -0
  62. package/dist/clio/pipeline.d.ts +11 -0
  63. package/dist/clio/pipeline.d.ts.map +1 -0
  64. package/dist/clio/pipeline.js +147 -0
  65. package/dist/clio/rhyme.d.ts +65 -0
  66. package/dist/clio/rhyme.d.ts.map +1 -0
  67. package/dist/clio/rhyme.js +761 -0
  68. package/dist/clio/scandroid.d.ts +17 -0
  69. package/dist/clio/scandroid.d.ts.map +1 -0
  70. package/dist/clio/scandroid.js +435 -0
  71. package/dist/clio/scansion.d.ts +46 -0
  72. package/dist/clio/scansion.d.ts.map +1 -0
  73. package/dist/clio/scansion.js +1086 -0
  74. package/dist/clio/semantics.d.ts +44 -0
  75. package/dist/clio/semantics.d.ts.map +1 -0
  76. package/dist/clio/semantics.js +139 -0
  77. package/dist/clio/stress.d.ts +83 -0
  78. package/dist/clio/stress.d.ts.map +1 -0
  79. package/dist/clio/stress.js +1737 -0
  80. package/dist/clio/tagfix.d.ts +6 -0
  81. package/dist/clio/tagfix.d.ts.map +1 -0
  82. package/dist/clio/tagfix.js +101 -0
  83. package/dist/display.d.ts +0 -6
  84. package/dist/display.d.ts.map +1 -1
  85. package/dist/display.js +322 -141
  86. package/dist/engine.d.ts +9 -0
  87. package/dist/engine.d.ts.map +1 -0
  88. package/dist/engine.js +12 -0
  89. package/dist/index.d.ts +4 -3
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +169 -26
  92. package/dist/parser.d.ts +3 -3
  93. package/dist/parser.d.ts.map +1 -1
  94. package/dist/parser.js +320 -563
  95. package/dist/phonological.d.ts +1 -1
  96. package/dist/phonological.d.ts.map +1 -1
  97. package/dist/phonological.js +73 -4
  98. package/dist/phrasestress.d.ts +6 -0
  99. package/dist/phrasestress.d.ts.map +1 -0
  100. package/dist/phrasestress.js +106 -0
  101. package/dist/rhyme.d.ts +40 -1
  102. package/dist/rhyme.d.ts.map +1 -1
  103. package/dist/rhyme.js +435 -7
  104. package/dist/scansion.d.ts +9 -0
  105. package/dist/scansion.d.ts.map +1 -1
  106. package/dist/scansion.js +145 -18
  107. package/dist/semantics.d.ts +44 -0
  108. package/dist/semantics.d.ts.map +1 -0
  109. package/dist/semantics.js +139 -0
  110. package/dist/stress.d.ts +127 -4
  111. package/dist/stress.d.ts.map +1 -1
  112. package/dist/stress.js +834 -61
  113. package/dist/types.d.ts +15 -0
  114. package/dist/types.d.ts.map +1 -1
  115. package/package.json +5 -3
  116. package/src/caesura.ts +201 -0
  117. package/src/calliope/boundaries.ts +190 -0
  118. package/src/calliope/bracketing.ts +390 -0
  119. package/src/calliope/deps.ts +160 -0
  120. package/src/calliope/engine.ts +77 -0
  121. package/src/calliope/feats.ts +46 -0
  122. package/src/calliope/names.ts +44 -0
  123. package/src/calliope/postag.ts +253 -0
  124. package/src/calliope/prosodic.ts +262 -0
  125. package/src/calliope/relstress.ts +645 -0
  126. package/src/calliope/stressrules.ts +147 -0
  127. package/src/calliope/syntax.ts +218 -0
  128. package/src/calliope/udpos.ts +152 -0
  129. package/src/calliope_src_contents.md +19049 -0
  130. package/src/clio/caesura.ts +145 -0
  131. package/src/clio/depfix.ts +88 -0
  132. package/src/clio/display.ts +1042 -0
  133. package/src/clio/engine.ts +38 -0
  134. package/src/clio/parser.ts +845 -0
  135. package/src/clio/phonological.ts +849 -0
  136. package/src/clio/phrasestress.ts +108 -0
  137. package/src/clio/pipeline.ts +154 -0
  138. package/src/clio/rhyme.ts +740 -0
  139. package/src/clio/scandroid.ts +434 -0
  140. package/src/clio/scansion.ts +1130 -0
  141. package/src/clio/semantics.ts +134 -0
  142. package/src/clio/stress.ts +1731 -0
  143. package/src/clio/tagfix.ts +104 -0
  144. package/src/display.ts +321 -137
  145. package/src/engine.ts +22 -0
  146. package/src/index.ts +176 -32
  147. package/src/parser.ts +346 -682
  148. package/src/phonological.ts +72 -4
  149. package/src/phrasestress.ts +108 -0
  150. package/src/rhyme.ts +428 -8
  151. package/src/scansion.ts +136 -15
  152. package/src/semantics.ts +134 -0
  153. package/src/stress.ts +794 -64
  154. package/src/types.ts +39 -4
  155. package/tests/DataForHayesLinesOnly.txt +364 -0
  156. package/tests/DataForHayesStressSymbolsRevised.txt +728 -0
  157. package/tests/basic.test.ts +443 -37
  158. package/tests/bench-hayes.mjs +72 -0
  159. package/tests/wagner-stress.test.ts +188 -0
  160. package/vitest.config.ts +0 -15
@@ -0,0 +1,1737 @@
1
+ // stress.ts — Lexical, compound, nuclear stress assignment using nounsing-pro
2
+ // (augmented CMU dictionary with 52+ columns), then conversion to McAleese's
3
+ // 4‑level relative system.
4
+ import * as nounsing from 'nounsing-pro';
5
+ import { isPunctuation } from './parser.js';
6
+ import { collectPPTokens, syllabifyWord } from './phonological.js';
7
+ import { isStrandedPreposition, isContrastivePossessive, isVocative, isDeicticLocative } from './semantics.js';
8
+ // ─── CONSTANTS & CLASSIFICATIONS ──────────────────────────────────
9
+ /**
10
+ * Content‑word POS tags (nouns, adjectives, lexical verbs, adverbs).
11
+ * Excludes:
12
+ * - determiners (including demonstratives) – function words
13
+ * - possessive pronouns (PRP$) – function words
14
+ * - Wh‑words (WDT, WP, WP$, WRB) – function words
15
+ * - prepositions, conjunctions, particles, etc.
16
+ */
17
+ const CONTENT_POS = new Set([
18
+ 'NN', 'NNS', 'NNP', 'NNPS', // nouns
19
+ 'JJ', 'JJR', 'JJS', // adjectives
20
+ 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', // lexical verbs (excludes modals MD)
21
+ 'RB', 'RBR', 'RBS', // adverbs
22
+ 'CD', // cardinal numbers (content-like)
23
+ 'PDT', // predeterminers / quantifiers ("all", "both", "half") — carry quantificational stress
24
+ 'RP', // phrasal-verb particles ("coming IN", "take OFF") — they bear the phrasal stress
25
+ ]);
26
+ /**
27
+ * Spatial words that act as phrasal-verb PARTICLES (stress-bearing: "coming IN",
28
+ * "moving ON", "give UP") as opposed to prepositions ("in the house" → reduced).
29
+ * The parser usually tags a true particle `RP` (handled by CONTENT_POS above),
30
+ * but often mis-tags it `IN`/`RB` with an adverbial/particle dependency on the
31
+ * verb — `isPhrasalParticle` recovers those. A genuine preposition keeps a
32
+ * `prep`/`pobj` dependency on a NOUN and is (correctly) left as a function word.
33
+ */
34
+ const PARTICLE_LEMMAS = new Set([
35
+ 'in', 'on', 'out', 'off', 'up', 'down', 'over', 'away', 'back',
36
+ 'along', 'around', 'about', 'through', 'apart', 'aside', 'forth', 'together',
37
+ ]);
38
+ /** A phrasal-verb particle the parser tagged IN/RB (not RP): stress-bearing. */
39
+ function isPhrasalParticle(word) {
40
+ if (word.lexicalClass === 'RP')
41
+ return true;
42
+ const dep = word.dependency?.dependentType;
43
+ return PARTICLE_LEMMAS.has(word.word.toLowerCase())
44
+ && (dep === 'prt' || dep === 'advmod');
45
+ }
46
+ /** Demonstratives that, used pronominally (not determining a following noun),
47
+ * are a stressed focus: "What's THAT?", "Give me THIS." */
48
+ const DEMONSTRATIVE_LEMMAS = new Set(['that', 'this', 'these', 'those']);
49
+ /**
50
+ * A demonstrative used as a *pronoun* (the clause-final focus), rather than as a
51
+ * determiner of a following noun. The parser often tags focus "that" as `IN`
52
+ * (complementizer) and it then reduces to `x` — but "What's THAT?" puts the
53
+ * sentence's prominence on it. Detected as a demonstrative lemma that is the
54
+ * last non-punctuation word of the line (so "Is THAT grass" — a determiner — is
55
+ * untouched).
56
+ */
57
+ function isFocusDemonstrative(words, wi) {
58
+ if (!DEMONSTRATIVE_LEMMAS.has(words[wi].word.toLowerCase()))
59
+ return false;
60
+ for (let k = wi + 1; k < words.length; k++) {
61
+ if (!isPunctuation(words[k].lexicalClass))
62
+ return false; // a word follows → determiner use
63
+ }
64
+ return true;
65
+ }
66
+ /**
67
+ * Clitic POS categories: function words that are *proclitic* — prepositions /
68
+ * subordinators (IN), infinitival "to" (TO), possessive determiners (PRP$) and
69
+ * wh-determiners/possessives/adverbs (WDT/WP$/WRB). A
70
+ * *monosyllabic* word in one of these classes is reduced in running speech
71
+ * (Selkirk's clitic; McAleese's "beginnings free") and should floor at 'w'
72
+ * (overt-weak, *promotable*), never 'n'. Leaving a CMU-primary monosyllable
73
+ * like "on"/"my"/"where"/"from" at 'n' produced flat function-word runs (Pound's
74
+ * "So on my" = n·n·n, "where strange" = n·n).
75
+ *
76
+ * Deliberately EXCLUDES:
77
+ * - modals (MD: "shall"/"might") and personal pronouns (PRP: "I"/"thee"/"you")
78
+ * — they carry real stress (the clause-final beat in "…fast as you MIGHT").
79
+ * - determiners (DT) entirely. The quantificational / negative / demonstrative
80
+ * ones ("no one", "all verse", "this", "each") carry stress (cf. the
81
+ * maintainer's PDT-as-content rule); and flooring even the pure articles
82
+ * a/an tips Tarlinskaja's razor-thin iambic↔anapestic line ("…else a
83
+ * laugher's license", margin 0.009) into a wrong meter. "the" already reads
84
+ * 'x' via its CMU-0 stress, so determiners need no extra handling here.
85
+ * - coordinators (CC: and/but/or). "and" already reads 'x' (CMU-0); flooring
86
+ * "but"→w fires earlier than its baseline path and ripples to suppress an
87
+ * adjacent pronoun's clash-promotion, tipping Tarlinskaja's razor-thin
88
+ * iambic↔anapestic line — and coordinators bear no part of the n-run problem.
89
+ * Polysyllabic function words are also untouched, so their internal contour is
90
+ * preserved (be·NEATH = x·n, un·der·NEATH = x·x·n).
91
+ */
92
+ // NB: deliberately NOT including DT/PRP/MD/WP here. Monosyllabic pronouns,
93
+ // determiners, and modals at 'n' are PROMOTABLE into metrical beats — which
94
+ // real iambic verse exploits constantly ("but HE gave NO one ELSE",
95
+ // "fast as you MIGHT"). Flooring them to 'w' was tried (2026-06-12) and
96
+ // flipped the Mandelstam anapest and the Tarlinskaja iambic: reverted.
97
+ const CLITIC_POS = new Set(['IN', 'TO', 'PRP$', 'WDT', 'WP$', 'WRB']);
98
+ /** A reducible monosyllabic proclitic (see CLITIC_POS). */
99
+ function isMonosyllabicClitic(word) {
100
+ return !word.isContent
101
+ && word.syllables.length === 1
102
+ && CLITIC_POS.has(word.lexicalClass);
103
+ }
104
+ /**
105
+ * Temporal, locative, and discourse adverbs that behave as function words
106
+ * in verse — they typically occupy weak metrical positions and should not
107
+ * receive the primary-stress treatment of content adverbs.
108
+ */
109
+ const FUNCTION_ADVERBS = new Set([
110
+ 'then', 'so', 'here', 'there', 'where', 'when', 'why', 'how',
111
+ 'thus', 'hence', 'thence', 'whence',
112
+ 'now', 'ago', 'afterwards', 'afterward', 'beforehand',
113
+ 'meanwhile', 'nevertheless', 'nonetheless', 'however',
114
+ 'therefore', 'furthermore', 'moreover',
115
+ 'besides', 'instead', 'rather',
116
+ 'quite', 'almost', 'nearly', 'just', 'only',
117
+ 'even', 'also', 'too', 'very', 'indeed',
118
+ 'already', 'yet', 'still', 'again', 'ever', 'never',
119
+ 'always', 'often', 'sometimes', 'usually',
120
+ 'today', 'tomorrow', 'yesterday', 'tonight',
121
+ ]);
122
+ /**
123
+ * Rising (iambic) disyllabic function words — prepositions, conjunctions, and
124
+ * deictic adverbs that stress the SECOND syllable (be·CAUSE, a·BOUT, be·TWEEN).
125
+ * A handful are recorded fully-reduced ("00") in the augmented dictionary; for
126
+ * those the all-zero re-stamp must fix the FINAL syllable, NOT take the
127
+ * disyllabic forestress default (which mis-read be·CAUSE as BE·cause). The
128
+ * re-stamp only fires on a genuine all-zero entry, so listing a word that
129
+ * already carries a peak is harmless. Trochaic IN·to / UN·to / ON·to are
130
+ * deliberately excluded — they correctly keep forestress.
131
+ */
132
+ const RISING_FUNCTION_WORDS = new Set([
133
+ 'because', 'about', 'above', 'around', 'across', 'along', 'among', 'amongst',
134
+ 'against', 'amid', 'amidst', 'apart', 'ahead', 'aside', 'away', 'aloft',
135
+ 'alone', 'aloud', 'anew', 'awhile', 'ago',
136
+ 'before', 'behind', 'below', 'beneath', 'beside', 'besides', 'between',
137
+ 'beyond', 'within', 'without',
138
+ ]);
139
+ /**
140
+ * Oblique (object/dative) pronouns. In clause-final position these are
141
+ * canonically unstressed and do NOT attract the beat ("…and beHIND me", not
142
+ * "…and behind ME"), unlike a clause-final modal or content word. Used to keep
143
+ * the "endings strict" upbeat rule from promoting a final object pronoun.
144
+ */
145
+ const OBLIQUE_PRONOUNS = new Set([
146
+ 'me', 'him', 'her', 'us', 'them', 'thee', 'ye',
147
+ ]);
148
+ /**
149
+ * Subject-pronoun contractions (pronoun + auxiliary). These are a known data
150
+ * anomaly: FinNLP mis-tags the line-initial "I"-forms as FW, and nounsing records
151
+ * "i'm" with stress 0 while its sibling "i'll" gets 1 — so "I'm" sank to 'x'
152
+ * (Zero-Provision) whereas "I'll" read 'n'. A contracted subject pronoun is an
153
+ * overt syllable, never a maximally-reduced clitic, so a dictionary-zero one is
154
+ * restamped to its siblings' weak stress (below). This is a TARGETED fix for that
155
+ * specific inconsistency — it does NOT change how clitics, prepositions, articles,
156
+ * or bare pronouns floor (those keep their broad 'x'/contour behaviour).
157
+ */
158
+ const PRONOUN_SUBJECT_CONTRACTIONS = new Set([
159
+ "i'm", "i'll", "i've", "i'd",
160
+ "you're", "you'll", "you've", "you'd",
161
+ "he'll", "he'd", "she'll", "she'd", "it'll",
162
+ "we're", "we'll", "we've", "we'd",
163
+ "they're", "they'll", "they've", "they'd",
164
+ ]);
165
+ /**
166
+ * Poetic aphaeresis / clipping forms (apostrophe-stripped, lowercased) of
167
+ * function words — prepositions and adverbs. These are OOV, so without special
168
+ * handling they default to a *stressed content* reading (the parser tags
169
+ * "'neath" as NNP → primary stress!). Only applied when an apostrophe is
170
+ * actually present (so a literal "mid"/"side"/"cross" is left alone).
171
+ */
172
+ const APHAERESIS_CLITICS = new Set([
173
+ 'neath', // beneath
174
+ 'gainst', // against
175
+ 'twixt', // betwixt
176
+ 'mid', // amid
177
+ 'midst', // amidst
178
+ 'mongst', // amongst
179
+ 'tween', // between
180
+ 'pon', // upon
181
+ 'oer', // o'er = over
182
+ 'neer', // ne'er = never
183
+ 'eer', // e'er = ever
184
+ 'tis', // 'tis = it is (apostrophe-guarded, so a literal "tis" is untouched)
185
+ 'twas', // 'twas = it was
186
+ 'twere', // 'twere = it were
187
+ 'twill', // 'twill = it will (guard protects the fabric "twill")
188
+ ]);
189
+ /**
190
+ * Augmented-CMU data anomalies: for a couple of very common monosyllables the
191
+ * dictionary's ONLY profile is the letter-name spelling pronunciation of an
192
+ * abbreviation homograph — "am" → "EY1 EH1 M" (= A.M.), "us" → "Y UW1 EH1 S"
193
+ * (= U.S.) — inflating the syllable count of any line containing them. We
194
+ * restore the ordinary CMU citation form (AE1 M / AH1 S: one heavy syllable,
195
+ * citation stress 1) before the dictionary is consulted.
196
+ */
197
+ const ANOMALOUS_MONOSYLLABLES = {
198
+ am: { syllab: '(AE m)' },
199
+ us: { syllab: '(AH s)' },
200
+ // "a" = letter-name "EY1" in the augmented dictionary; the article is the
201
+ // canonical Zero-Provision clitic (schwa, open syllable) → stress 0, light.
202
+ a: { syllab: '(AH)', stress: 0, weight: 'L' },
203
+ };
204
+ /**
205
+ * Copula, auxiliary, aspectual, and light verbs that act as function words
206
+ * in verse — they do not carry the main semantic or prosodic weight of a phrase
207
+ * and should not be treated as content words for stress rules.
208
+ */
209
+ const FUNCTION_VERBS = new Set([
210
+ 'be', 'am', 'is', 'are', 'was', 'were', 'been', 'being',
211
+ 'have', 'has', 'had', 'having',
212
+ 'do', 'does', 'did', 'done', 'doing',
213
+ 'get', 'gets', 'got', 'getting', 'gotten',
214
+ 'start', 'starts', 'started', 'starting',
215
+ 'begin', 'begins', 'began', 'beginning', 'begun',
216
+ 'keep', 'keeps', 'kept', 'keeping',
217
+ 'stop', 'stops', 'stopped', 'stopping',
218
+ 'continue', 'continues', 'continued', 'continuing',
219
+ 'let', 'lets', "let's"
220
+ ]);
221
+ /** The copula / auxiliary forms of BE — they reduce in connected speech whether
222
+ * used as copula ("she IS fair" → reduced) or auxiliary ("is going"). */
223
+ const BE_FORMS = new Set(['be', 'am', 'is', 'are', 'was', 'were', 'being']);
224
+ /**
225
+ * Exclamatory / vocative interjections. These are emphatic, expressive elements —
226
+ * never zero-provision clitics — yet FinNLP routinely mis-tags vocative "O" as a
227
+ * preposition (IN) and "Lo" as a proper noun (NNP), which would otherwise floor
228
+ * them to 'x'. Keyed off the lemma (not the unreliable tag), they are raised to at
229
+ * least 'n'; an exclaimed one ("O!", "Oh!") is lifted a further tier by the
230
+ * interjection-emphasis pass at the end of assignRelativeStresses. Apostrophe
231
+ * forms (o'er = over, e'er = ever) are NOT here — they are aphaeresis clitics.
232
+ */
233
+ const EXCLAM_INTERJECTIONS = new Set([
234
+ 'o', 'oh', 'ah', 'ay', 'aye', 'lo', 'alas', 'alack', 'hark', 'fie', 'woe',
235
+ 'ho', 'oho', 'aha', 'ahoy', 'hurrah', 'huzza',
236
+ ]);
237
+ /**
238
+ * Honest baseline relative prominence for a FUNCTION word (McAleese step 1b:
239
+ * "w=weak, n=some stress, m=subordinate strong, s=strong"). A monosyllabic
240
+ * function word bears no lexical *some-stress*; the dictionary's citation stress
241
+ * (which marks "and"/"in"/"my"/"could" as primary) is a CITATION artefact, not
242
+ * connected-speech prominence. We floor it to its true reading prominence — the
243
+ * meter layer still PROMOTES it to a beat where the metre calls for it (McAleese's
244
+ * Appendix-A Test 2: stressless "than"/"in" stay weak in the contour; the metre
245
+ * lifts only "from", which carries latent stress). Returns the tier to floor to,
246
+ * or null to leave the word untouched.
247
+ *
248
+ * 'x' (zero-provision) — pure schwa-proclitics that fully reduce: coordinators
249
+ * (CC: and/or/but/nor), monosyllabic prepositions & subordinators (IN), the
250
+ * infinitival/prepositional "to" (TO), possessive determiners (PRP$/WP$:
251
+ * my/your/his/her/its/our/their/whose).
252
+ * 'w' (overt-weak, still meter-promotable) — full-vowel function words: personal
253
+ * pronouns (PRP), modals (MD), existential "there" (EX), the copula/auxiliary
254
+ * BE forms, the AUXILIARY uses of have/do (by dependency role — a main-verb
255
+ * "have"/"did" keeps its beat), and reduced deictic/discourse adverbs.
256
+ *
257
+ * Content words and the internal contour of POLYSYLLABIC function words
258
+ * (be·NEATH = x·n, with·OUT) are returned null (untouched).
259
+ */
260
+ function relativeFloorFor(word) {
261
+ if (word.isContent)
262
+ return null;
263
+ if (word.syllables.length !== 1)
264
+ return null; // keep polysyllabic function contour
265
+ const pos = word.lexicalClass;
266
+ const lemma = word.word.toLowerCase().replace(/['’]/g, '');
267
+ // Pure schwa-proclitics → zero-provision 'x'.
268
+ if (pos === 'CC' || pos === 'PRP$' || pos === 'WP$' || pos === 'TO')
269
+ return 'x';
270
+ if (pos === 'IN')
271
+ return 'x'; // prepositions / subordinators cliticise
272
+ // Full-vowel weak function words → overt-weak 'w' (meter-promotable).
273
+ if (pos === 'PRP' || pos === 'MD' || pos === 'EX')
274
+ return 'w';
275
+ if (BE_FORMS.has(lemma))
276
+ return 'w'; // copula & auxiliary BE both reduce
277
+ // NB: have/do are deliberately NOT floored — unlike BE they routinely bear a
278
+ // beat (main-verb "have"/"do", emphatic "DID"), and even as auxiliaries they
279
+ // carry an iambic beat often enough ("what HAD I given") that flooring them
280
+ // mis-reads such lines. Their level is left to the clash filter + meter layer.
281
+ if (FUNCTION_ADVERBS.has(lemma))
282
+ return 'w'; // so/then/here/there/when/just…
283
+ return null;
284
+ }
285
+ /** Left‑stressed compound categories with example first‑word lists. */
286
+ const LEFT_STRESS_MATERIAL = new Set([
287
+ 'metal', 'wood', 'silk', 'cotton', 'glass', 'stone', 'iron', 'steel',
288
+ 'paper', 'plastic', 'gold', 'silver'
289
+ ]);
290
+ const LEFT_STRESS_TIME = new Set([
291
+ 'morning', 'evening', 'summer', 'winter', 'spring', 'autumn',
292
+ 'christmas', 'easter', 'night', 'day'
293
+ ]);
294
+ const LEFT_STRESS_MEASURE = new Set(['pint', 'dollar', 'foot', 'mile']);
295
+ const LEFT_STRESS_LOCATION = new Set([
296
+ 'city', 'mountain', 'river', 'street', 'valley', 'island',
297
+ 'town', 'village', 'country'
298
+ ]);
299
+ const LEFT_STRESS_SELF = new Set(['self']);
300
+ // "Discard / ruin / spectral" noun-modifiers (N1) that reliably forestress as
301
+ // compounds: WASTE·land, SCRAP·yard, JUNK·yard, GHOST·town, DEAD·line,
302
+ // DUST·bowl, GRAVE·yard, BONE·yard, DEATH·bed. (Eliot's "WASTE shore".)
303
+ const LEFT_STRESS_DISCARD = new Set([
304
+ 'waste', 'scrap', 'junk', 'ghost', 'dead', 'dust', 'grave', 'bone',
305
+ 'death', 'trash', 'garbage', 'ash', 'blood', 'rust', 'wreck',
306
+ ]);
307
+ // Elemental / landscape noun-modifiers (N1) that reliably forestress:
308
+ // SEA·shore, MOON·light, STORM·cloud, WIND·mill, FIRE·place, SALT·marsh,
309
+ // FROST·bite, SAND·bar, SNOW·flake, TIDE·water, SHADOW·land.
310
+ const LEFT_STRESS_ELEMENTAL = new Set([
311
+ 'sea', 'moon', 'sun', 'star', 'storm', 'wind', 'fire', 'rain', 'snow',
312
+ 'ice', 'tide', 'wave', 'frost', 'mist', 'fog', 'mud', 'sand', 'salt',
313
+ 'earth', 'sky', 'dawn', 'dusk', 'shadow', 'flame', 'ember', 'smoke',
314
+ 'cloud', 'water', 'dew', 'hail', 'marsh', 'moor', 'flood', 'foam',
315
+ ]);
316
+ // Fire / light-source N1 modifiers that forestress like the elemental set:
317
+ // TORCH·light, CANDLE·light, LAMP·light, LANTERN·light, BEACON·fire,
318
+ // HEARTH·stone, COAL·fire, GAS·light — and Pound's hyphenated TORCH·flames
319
+ // (parallel to WASTE·shore; "flames" is the head, "torch" the modifier).
320
+ const LEFT_STRESS_FIRELIGHT = new Set([
321
+ 'torch', 'candle', 'lamp', 'lantern', 'beacon', 'hearth', 'coal', 'gas',
322
+ ]);
323
+ // Vehicle / conveyance N1 modifiers that forestress: SLEIGH·bells/blades,
324
+ // CART·wheel, WAGON·train, CAR·door, TRAIN·station, BOAT·house, TROLLEY·tickets.
325
+ // (Endocentric N+N where N1 is the conveyance the N2 belongs to / is part of.)
326
+ const LEFT_STRESS_VEHICLE = new Set([
327
+ 'sleigh', 'sled', 'cart', 'wagon', 'carriage', 'coach', 'train', 'tram',
328
+ 'trolley', 'car', 'boat', 'ship', 'plane', 'truck', 'bus', 'bike', 'bicycle',
329
+ ]);
330
+ // Head nouns (N2) that keep phrasal/right stress even after a forestress
331
+ // modifier — chiefly food "made of N1" and a few lexical exceptions:
332
+ // apple PIE, summer DAY, Fifth AVenue. These carve-outs keep the rule honest
333
+ // (a wrong forestress would mis-teach learners), so they OVERRIDE the N1 sets.
334
+ const RIGHT_STRESS_HEADS = new Set([
335
+ 'pie', 'cake', 'tart', 'pudding', 'mousse', 'soup', 'salad', 'sauce',
336
+ 'juice', 'avenue', 'day',
337
+ ]);
338
+ /** Check if a pair of words forms a left‑stressed compound. */
339
+ export function isLeftStressedPair(w1, w2) {
340
+ const first = w1.toLowerCase();
341
+ const second = w2.toLowerCase().replace(/'s$/, '');
342
+ // A right-stressing head overrides any forestress modifier (apple PIE).
343
+ if (RIGHT_STRESS_HEADS.has(second))
344
+ return false;
345
+ if (LEFT_STRESS_MATERIAL.has(first))
346
+ return true;
347
+ if (LEFT_STRESS_TIME.has(first))
348
+ return true;
349
+ if (LEFT_STRESS_MEASURE.has(first))
350
+ return true;
351
+ if (LEFT_STRESS_LOCATION.has(first))
352
+ return true;
353
+ if (LEFT_STRESS_SELF.has(first))
354
+ return true;
355
+ if (LEFT_STRESS_DISCARD.has(first))
356
+ return true;
357
+ if (LEFT_STRESS_ELEMENTAL.has(first))
358
+ return true;
359
+ if (LEFT_STRESS_FIRELIGHT.has(first))
360
+ return true;
361
+ if (LEFT_STRESS_VEHICLE.has(first))
362
+ return true;
363
+ return false;
364
+ }
365
+ /** True if `w2` is a head noun that keeps phrasal/right stress against an N1
366
+ * modifier (apple PIE, summer DAY, Fifth AVenue) — the marked right-stress
367
+ * exceptions to the otherwise fore-stressing Compound Stress Rule. */
368
+ export function isRightStressedHead(w2) {
369
+ return RIGHT_STRESS_HEADS.has(w2.toLowerCase().replace(/'s$/, ''));
370
+ }
371
+ /**
372
+ * Direction of primary stress for an adjacent two-word modification structure,
373
+ * the SINGLE source of truth shared by the lexical compound pass
374
+ * (`applyCompoundStress`) and the Phrase-Stress phase (`computePhraseStress`),
375
+ * so the two layers cannot disagree.
376
+ *
377
+ * 'left' = fore-stress, primary on w1 — the Compound Stress Rule default for
378
+ * an N+N compound (Chomsky–Halle; McAleese's worked example marks
379
+ * ICE cream with primary on "ice", not "cream"): KITCHen table,
380
+ * WINdow frame, BEDroom door, plus the curated LEFT_STRESS_* sets.
381
+ * 'right' = end-stress, primary on w2 — the marked exceptions: food/temporal
382
+ * "made of N1" heads (apple PIE, summer DAY), Adj+N which is phrasal
383
+ * not compound (sweet CREAM, red CAR), and proper-name sequences
384
+ * which carry their own right-headed prosody (New YORK, John SMITH).
385
+ * null = not a compound/modification pair at all.
386
+ *
387
+ * The fore-stress default is restricted to COMMON-noun N+N: proper-noun pairs
388
+ * (NNP/NNPS) are excluded because place- and personal-name sequences are not
389
+ * reliably fore-stressed, and flipping them would mis-teach New YORK / John SMITH.
390
+ */
391
+ export function compoundStressSide(w1, pos1, w2, pos2) {
392
+ const isNN = pos1.startsWith('N') && pos2.startsWith('N');
393
+ const isAdjN = pos1.startsWith('J') && pos2.startsWith('N');
394
+ if (!isNN && !isAdjN)
395
+ return null;
396
+ if (isLeftStressedPair(w1, w2))
397
+ return 'left'; // curated fore-stress modifier
398
+ if (isRightStressedHead(w2))
399
+ return 'right'; // apple PIE, Fifth AVenue
400
+ const proper = (p) => p === 'NNP' || p === 'NNPS';
401
+ if (isNN && !proper(pos1) && !proper(pos2))
402
+ return 'left'; // common-N+N compound default
403
+ return 'right'; // Adj+N phrasal / proper-name pair
404
+ }
405
+ /**
406
+ * Lexicalised forestress COLLOCATIONS — fixed two-word phrases that stress the
407
+ * LEFT element, even though the second word is not a noun (so the N+N/J+N
408
+ * Compound Stress Rule does not reach them). "GOOD old days/friend";
409
+ * "the be-all and END-all". Each entry's optional guard suppresses spurious
410
+ * firing (e.g. "End ALL the wars" — the *verb* "end" + quantifier "all the
411
+ * wars" — must NOT forestress; there "all" is a predeterminer PDT).
412
+ */
413
+ const LEFT_STRESS_COLLOCATIONS = [
414
+ { w1: 'good', w2: 'old' }, // GOOD old days
415
+ { w1: 'end', w2: 'all', ok: w => w.lexicalClass !== 'PDT' }, // END-all (idiom), not "end ALL the wars"
416
+ ];
417
+ /** True if (w1,w2) is a lexicalised forestress collocation in this context. */
418
+ function isLeftStressedCollocation(w1, w2) {
419
+ const b1 = w1.word.toLowerCase().replace(/[^a-z]/g, '');
420
+ const b2 = w2.word.toLowerCase().replace(/[^a-z]/g, '');
421
+ for (const c of LEFT_STRESS_COLLOCATIONS) {
422
+ if (b1 === c.w1 && b2 === c.w2 && (!c.ok || c.ok(w2)))
423
+ return true;
424
+ }
425
+ return false;
426
+ }
427
+ // ─── LEXICAL STRESS (pronouncingjs) ───────────────────────────────
428
+ const VOWEL_CHARS = new Set('aeiouyAEIOUY');
429
+ /** Archaic/locative pronominal compounds whose first element ends in a MEDIAL
430
+ * silent 'e' ("where·fore", "there·in"): the plain vowel-group count reads the
431
+ * 'e' as a nucleus and over-counts. Count the parts instead. */
432
+ const SILENT_E_COMPOUND_RE = /^(where|there|here)(fore|in|by|of|on|upon|at|to|with|out|after|under|unto|abouts?|soever)$/;
433
+ function countVowelGroups(word) {
434
+ {
435
+ const m = word.toLowerCase().replace(/[^a-z]/g, '').match(SILENT_E_COMPOUND_RE);
436
+ // Closed-class second elements; counted directly ("fore" would otherwise
437
+ // read 2 — the small-word guard blocks the final-silent-e deduction).
438
+ if (m)
439
+ return 1 + (m[2] === 'soever' ? 3
440
+ : /^(upon|after|under|unto|about)/.test(m[2]) ? 2 : 1);
441
+ }
442
+ const lower = word.toLowerCase().replace(/-/g, '').replace(/'s/g, '').replace(/'/g, '');
443
+ const n = lower.length;
444
+ let groups = 0;
445
+ let inVowel = false;
446
+ const vowelPositions = [];
447
+ for (let i = 0; i < n; i++) {
448
+ if (VOWEL_CHARS.has(lower[i])) {
449
+ if (!inVowel) {
450
+ groups++;
451
+ vowelPositions.push(i);
452
+ inVowel = true;
453
+ }
454
+ }
455
+ else {
456
+ inVowel = false;
457
+ }
458
+ }
459
+ if (groups >= 3 && n > 2 && lower[n - 1] === 'e' && VOWEL_CHARS.has(lower[n - 1])) {
460
+ const lastVowelStart = vowelPositions[vowelPositions.length - 1];
461
+ if (lastVowelStart === n - 1) {
462
+ groups--;
463
+ }
464
+ }
465
+ return groups;
466
+ }
467
+ // ─── OUT-OF-VOCABULARY STRESS (two-tier fallback) ─────────────────
468
+ //
469
+ // When a word is absent from the augmented CMU dictionary, the old fallback
470
+ // blindly forestressed it (primary on syllable 0). That mis-stresses the most
471
+ // common OOV case — *inflected/derived forms of common words* whose base IS in
472
+ // the lexicon ("voyaging" OOV, "voyage" present) — and many true OOV words too
473
+ // ("anfractuous" → AN·fractuous rather than an·FRAC·tuous). We replace it with:
474
+ // (1) MORPHOLOGICAL decomposition — strip a stress-neutral productive suffix,
475
+ // reconstruct the stem's orthography, look it up, and reuse the stem's
476
+ // *real* lexical stress (the suffix syllables are unstressed).
477
+ // (2) the English Stress Rule (quantity-sensitive) for the genuine residual
478
+ // (names, neologisms) with no recognisable stem.
479
+ // Both run ONLY in the OOV branch, so in-vocabulary scansion is untouched.
480
+ /** Strip one trailing doubled consonant (run·ning → run, stop·ped → stop). */
481
+ function deDouble(b) {
482
+ const m = b.match(/([^aeiou])\1$/i);
483
+ return m ? b.slice(0, -1) : b;
484
+ }
485
+ /** True if a stem ends in a sibilant/affricate, so a following -s/-es is its own
486
+ * syllable (kiss·es, box·es, voy·a·ges) rather than a bare coda (cats). */
487
+ function isSibilantEnd(s) {
488
+ return /(s|z|x|sh|ch|ce|ge|se|ze|dge|tch)$/i.test(s);
489
+ }
490
+ /**
491
+ * Stress-neutral productive suffixes (Hayes: these do not shift the stem's
492
+ * stress). `stems(base)` lists candidate stem spellings to try (order = most
493
+ * likely first); `added(stem)` is how many *syllables* the suffix contributes.
494
+ * Stress-SHIFTING suffixes (-ion/-ity/-ic/-ial/-ious/-ify…) are deliberately
495
+ * omitted — treating them as neutral would mis-place the peak; they fall through
496
+ * to the English Stress Rule (and are common enough to usually be in-lexicon).
497
+ */
498
+ const SUFFIX_RULES = [
499
+ { suffix: 'iness', stems: b => [b + 'y'], added: () => 1 }, // happi·ness ← happy
500
+ { suffix: 'ily', stems: b => [b + 'y'], added: () => 1 }, // happi·ly ← happy
501
+ { suffix: 'ies', stems: b => [b + 'y'], added: () => 0 }, // car·ries ← carry
502
+ { suffix: 'ied', stems: b => [b + 'y'], added: () => 0 }, // car·ried ← carry
503
+ { suffix: 'ness', stems: b => [b], added: () => 1 },
504
+ { suffix: 'ment', stems: b => [b], added: () => 1 },
505
+ { suffix: 'less', stems: b => [b], added: () => 1 },
506
+ { suffix: 'ful', stems: b => [b], added: () => 1 },
507
+ { suffix: 'ings', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 },
508
+ { suffix: 'ing', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 }, // voy·a·ging ← voyage
509
+ { suffix: 'est', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 },
510
+ { suffix: 'ed', stems: b => [b + 'e', b, deDouble(b)], added: stem => /[td]$/.test(stem) ? 1 : 0 },
511
+ { suffix: 'eth', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 }, // archaic 3sg: go·eth, fall·eth, mak·eth
512
+ { suffix: 'ith', stems: b => [b + 'y', b + 'e', b], added: () => 1 }, // archaic 3sg of -y verbs: sa·ith ← say
513
+ { suffix: 'er', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 },
514
+ { suffix: 'ly', stems: b => [b], added: () => 1 }, // soft·ly ← soft
515
+ { suffix: 'es', stems: b => [b, b + 'e'], added: stem => isSibilantEnd(stem) ? 1 : 0 },
516
+ { suffix: 's', stems: b => [b, b + 'e'], added: stem => isSibilantEnd(stem) ? 1 : 0 },
517
+ ];
518
+ /**
519
+ * Tier 1 — derive an OOV word's numeric stress (2=primary, 1=secondary, 0=none)
520
+ * by stripping a stress-neutral suffix and reusing the in-lexicon stem's stress.
521
+ * Returns null if no productive suffix yields a known stem.
522
+ */
523
+ function morphologicalStress(w) {
524
+ for (const rule of SUFFIX_RULES) {
525
+ if (!w.endsWith(rule.suffix))
526
+ continue;
527
+ const base = w.slice(0, w.length - rule.suffix.length);
528
+ if (base.length < 2)
529
+ continue; // guard tiny stems (sing → s+ing)
530
+ for (const stem of rule.stems(base)) {
531
+ if (stem.length < 2)
532
+ continue;
533
+ const data = nounsing.all(stem);
534
+ const raw = data && data.length ? (data[0].stress?.stressTrans || '') : '';
535
+ if (!raw)
536
+ continue;
537
+ const stemNumeric = [...raw].map(c => mapCMUStress(parseInt(c, 10)));
538
+ if (stemNumeric.length === 0)
539
+ continue;
540
+ const added = rule.added(stem);
541
+ return { pattern: [...stemNumeric, ...new Array(added).fill(0)], suffix: added >= 1 ? rule.suffix : '' };
542
+ }
543
+ }
544
+ return null;
545
+ }
546
+ /** Archaic verbal suffixes whose orthographic peel cleanly separates a silent-
547
+ * consonant stem from the suffix for DISPLAY (know·est not kno·west). Other
548
+ * suffixes keep the default orthographic syllabifier (it handles them well). */
549
+ const DISPLAY_PEEL_SUFFIXES = new Set(['est', 'eth', 'ith']);
550
+ /** Heavy syllable (orthographic estimate): long vowel (digraph/VCe) or closed
551
+ * by a coda consonant. Light = open with a single short vowel. */
552
+ function syllableIsHeavy(syl) {
553
+ const s = syl.toLowerCase();
554
+ if (/[aeiouy]{2}/.test(s))
555
+ return true; // vowel digraph / diphthong → long
556
+ if (/[aeiou][^aeiouy]e$/.test(s))
557
+ return true; // V·C·e → long ("ate", "ime")
558
+ if (/[^aeiouy]$/.test(s))
559
+ return true; // closed syllable (coda present)
560
+ return false;
561
+ }
562
+ /**
563
+ * Pre-stressing derivational suffixes (Hayes' "pre-stress 1/2"): they fix the
564
+ * primary on a syllable counted from the word's end (`offset` = syllables back,
565
+ * so primary index = n − offset). -ic/-tion fix the penult (offset 2),
566
+ * -ity/-graphy/-ical fix the antepenult (offset 3). Longest-match-first
567
+ * (enforced by the length sort below).
568
+ *
569
+ * The 2026-06-10 batch was DERIVED from the augmented CMU data itself
570
+ * (nounsing's `suffixType` shift classes cross-checked against the `mainStress`
571
+ * column over 3+-syllable words; every adopted ending ≥ 0.90 purity, most ≥ 0.96,
572
+ * N ≥ 60). This includes onomastic endings (-ski/-sky/-son/-berg/-gton …) that
573
+ * matter for OOV proper names — frequent in translation work. `-ary` is
574
+ * preantepenult and only fires on 4+-syllable words (the n ≥ offset guard),
575
+ * so BI-na-ry / ca-NA-ry style 3-syllable words fall through safely.
576
+ * NOTE: vowel-hiatus suffixes (-ion/-ial/-ious) can be undercounted by the
577
+ * orthographic syllable counter, so those stay approximate (documented limit).
578
+ */
579
+ const PRESTRESS_SUFFIXES = [
580
+ // hand-curated originals (Hayes)
581
+ { suffix: 'graphy', offset: 3 }, { suffix: 'ically', offset: 4 },
582
+ { suffix: 'ation', offset: 2 }, { suffix: 'ition', offset: 2 },
583
+ { suffix: 'itude', offset: 3 }, { suffix: 'ical', offset: 3 },
584
+ { suffix: 'logy', offset: 3 }, { suffix: 'nomy', offset: 3 },
585
+ { suffix: 'cracy', offset: 3 }, { suffix: 'pathy', offset: 3 },
586
+ { suffix: 'meter', offset: 3 }, { suffix: 'tion', offset: 2 },
587
+ { suffix: 'sion', offset: 2 }, { suffix: 'ity', offset: 3 },
588
+ { suffix: 'ety', offset: 3 }, { suffix: 'ify', offset: 3 },
589
+ { suffix: 'ics', offset: 2 }, { suffix: 'ic', offset: 2 },
590
+ // data-derived 2026-06-10: final-stressing (ultShift)
591
+ { suffix: 'ette', offset: 1 }, { suffix: 'ese', offset: 1 },
592
+ { suffix: 'eer', offset: 1 }, { suffix: 'ique', offset: 1 },
593
+ // -oon is a reliable final-stresser (bal·LOON, car·TOON, co·COON, after·NOON);
594
+ // OOV-only. -ee/-ade are deliberately NOT added: they are impure (COF·fee,
595
+ // com·RADE, DEC·ade) and would mis-stress more than they fix.
596
+ { suffix: 'oon', offset: 1 },
597
+ // data-derived: penult-stressing
598
+ { suffix: 'ion', offset: 2 }, { suffix: 'sive', offset: 2 },
599
+ { suffix: 'lla', offset: 2 }, { suffix: 'llo', offset: 2 },
600
+ { suffix: 'lli', offset: 2 }, { suffix: 'tti', offset: 2 },
601
+ { suffix: 'ina', offset: 2 }, { suffix: 'ino', offset: 2 },
602
+ { suffix: 'ano', offset: 2 }, { suffix: 'ana', offset: 2 },
603
+ { suffix: 'ini', offset: 2 },
604
+ { suffix: 'ski', offset: 2 }, { suffix: 'sky', offset: 2 },
605
+ // data-derived: antepenult-stressing
606
+ { suffix: 'ate', offset: 3 }, { suffix: 'cal', offset: 3 },
607
+ { suffix: 'onal', offset: 3 }, { suffix: 'nger', offset: 3 },
608
+ { suffix: 'son', offset: 3 }, { suffix: 'man', offset: 3 },
609
+ { suffix: 'berg', offset: 3 }, { suffix: 'gton', offset: 3 },
610
+ // data-derived: preantepenult-stressing (4+ syllables only via the guard)
611
+ { suffix: 'ary', offset: 4 },
612
+ ].sort((a, b) => b.suffix.length - a.suffix.length);
613
+ /**
614
+ * Tier 2 — the English Stress Rule for genuine OOV (no recognisable stem).
615
+ * First honours a pre-stressing derivational suffix (terRIF·ic, ac·TIV·i·ty,
616
+ * pho·TOG·ra·phy). Otherwise it is quantity-sensitive with final-syllable
617
+ * extrametricality: monosyllables take primary; disyllables keep the English
618
+ * forestress default; for 3+ syllables the final is extrametrical and stress
619
+ * falls on a heavy penult, else the antepenult (Hayes 1982). This fixes e.g.
620
+ * an·FRAC·tuous / e·NIG·ma where blind forestress erred.
621
+ */
622
+ function englishStressRule(w, isContent) {
623
+ const n = countVowelGroups(w);
624
+ const primary = isContent ? 2 : 1;
625
+ if (n <= 1)
626
+ return [primary];
627
+ for (const { suffix, offset } of PRESTRESS_SUFFIXES) {
628
+ if (w.endsWith(suffix) && n >= offset) {
629
+ const pattern = new Array(n).fill(0);
630
+ pattern[n - offset] = primary;
631
+ return pattern;
632
+ }
633
+ }
634
+ if (n === 2)
635
+ return [primary, 0]; // English disyllabic default (trochaic)
636
+ const sylls = syllabifyWord(w, n);
637
+ const pattern = new Array(n).fill(0);
638
+ const penult = n - 2; // final (n-1) is extrametrical
639
+ const heavyPenult = sylls[penult] ? syllableIsHeavy(sylls[penult]) : true;
640
+ pattern[heavyPenult ? penult : Math.max(0, n - 3)] = primary;
641
+ return pattern;
642
+ }
643
+ /**
644
+ * Per-syllable heaviness from nounsing's `syllStruct` CV transcription
645
+ * ("L.CL.CLC": C = consonant, L = lax/short nucleus, T = tense/long nucleus).
646
+ * Heavy = tense nucleus OR closed syllable (a coda consonant after the nucleus).
647
+ * Returns undefined when the segment count doesn't match the syllable count, so
648
+ * callers fall back to the orthographic estimate.
649
+ */
650
+ function heavyFromSyllStruct(syllStruct, n) {
651
+ if (!syllStruct)
652
+ return undefined;
653
+ const segs = syllStruct.split('.');
654
+ if (segs.length !== n)
655
+ return undefined;
656
+ return segs.map(seg => {
657
+ const vi = seg.search(/[LT]/);
658
+ if (vi < 0)
659
+ return false;
660
+ return seg[vi] === 'T' || vi < seg.length - 1;
661
+ });
662
+ }
663
+ /**
664
+ * The syllable index that should bear the default stress of a polysyllabic word
665
+ * whose dictionary entry records NO stress at all (an all-zero pattern — the
666
+ * maximally-reduced citation form of a few function words, chiefly "into"=00).
667
+ * Every lexical word bears at least one stress, so we restore it: a pre-stressing
668
+ * suffix fixes the count-from-end syllable; otherwise the English forestress
669
+ * default for disyllables (IN-to, ON-to), and the quantity-sensitive penult/
670
+ * antepenult (Hayes) for longer words. Mirrors englishStressRule's placement.
671
+ * `heavyFlags` (real per-syllable quantity from nounsing's syllStruct) replaces
672
+ * the orthographic heaviness guess when the word is in-vocabulary.
673
+ */
674
+ function defaultStressIndex(word, n, heavyFlags) {
675
+ for (const { suffix, offset } of PRESTRESS_SUFFIXES) {
676
+ if (word.endsWith(suffix) && n >= offset)
677
+ return n - offset;
678
+ }
679
+ if (n <= 2)
680
+ return 0; // English disyllabic forestress default
681
+ const penult = n - 2; // final (n-1) extrametrical
682
+ const heavyPenult = heavyFlags
683
+ ? heavyFlags[penult]
684
+ : (() => { const sylls = syllabifyWord(word, n); return sylls[penult] ? syllableIsHeavy(sylls[penult]) : true; })();
685
+ return heavyPenult ? penult : Math.max(0, n - 3);
686
+ }
687
+ /**
688
+ * Map CMU stress (0=unstressed, 1=primary, 2=secondary) to
689
+ * McAleese's numeric scale: 0=unstressed, 1=secondary, 2=primary.
690
+ */
691
+ function mapCMUStress(cmuStress) {
692
+ if (cmuStress === 1)
693
+ return 2; // primary → 2
694
+ if (cmuStress === 2)
695
+ return 1; // secondary → 1
696
+ return 0; // unstressed → 0
697
+ }
698
+ /**
699
+ * Assign per‑syllable lexical stress to each word in a sentence.
700
+ *
701
+ * Uses the first CMU pronunciation. Function words have their
702
+ * primary stress downgraded to secondary (2 → 1).
703
+ */
704
+ export function assignLexicalStress(words) {
705
+ for (let wi = 0; wi < words.length; wi++) {
706
+ const word = words[wi];
707
+ if (isPunctuation(word.lexicalClass)) {
708
+ word.syllables = [];
709
+ continue;
710
+ }
711
+ // Explicitly assign 0 syllables to possessive/contraction clitic "'s"
712
+ if (word.word === "'s") {
713
+ word.syllables = [];
714
+ continue;
715
+ }
716
+ // Poetic aphaeresis clipping ('neath, o'er, 'gainst…) → treat as the reduced
717
+ // function word it stands for, instead of the OOV default (NNP → stressed).
718
+ // Guard on an actual apostrophe (split off as the prior token, or internal),
719
+ // so a literal "mid"/"side"/"cross" is untouched.
720
+ {
721
+ const bare = word.word.toLowerCase().replace(/['’]/g, '');
722
+ const hasApostrophe = /['’]/.test(word.word)
723
+ || (wi > 0 && (words[wi - 1].word === "'" || words[wi - 1].word === '’'));
724
+ if (hasApostrophe && APHAERESIS_CLITICS.has(bare)) {
725
+ word.isContent = false;
726
+ // One weak monosyllable; lexical 0 + function ⇒ maps to 'x' (reduced clitic).
727
+ word.syllables = [{ text: word.word, phones: '', stress: 0, lexicalStress: 0 }];
728
+ continue;
729
+ }
730
+ }
731
+ let lookupWord = word.word.toLowerCase();
732
+ // Letter-name dictionary anomalies ("am" = A.M., "us" = U.S.): stamp the
733
+ // ordinary citation monosyllable directly (see ANOMALOUS_MONOSYLLABLES).
734
+ {
735
+ const fix = ANOMALOUS_MONOSYLLABLES[lookupWord];
736
+ if (fix) {
737
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
738
+ word.isContent = isContent;
739
+ const numeric = fix.stress ?? (isContent ? 2 : 1); // citation primary; function words reduce to secondary
740
+ word.syllables = [{ text: word.word, phones: fix.syllab, weight: fix.weight ?? 'H', stress: numeric, lexicalStress: numeric }];
741
+ continue;
742
+ }
743
+ }
744
+ // Elided article fused to its host (th'expense, th'inconstant): "th'" is
745
+ // non-syllabic, so the HOST word's dictionary entry is the right source for
746
+ // stress and syllable count — otherwise the fused token goes OOV and takes
747
+ // the disyllabic forestress default (TH'EX-pense instead of th'ex-PENSE).
748
+ {
749
+ const m = lookupWord.match(/^th['’](.+)$/);
750
+ if (m && m[1].length >= 2)
751
+ lookupWord = m[1];
752
+ }
753
+ let allData = nounsing.all(lookupWord);
754
+ if (!allData && lookupWord.includes('-')) {
755
+ const noHyphen = lookupWord.replace(/-/g, '');
756
+ allData = nounsing.all(noHyphen);
757
+ }
758
+ if ((!allData || allData.length === 0) && lookupWord.includes('-')) {
759
+ const parts = lookupWord.split('-');
760
+ const partStresses = [];
761
+ const partWeights = [];
762
+ for (const part of parts) {
763
+ const partData = nounsing.all(part);
764
+ if (partData && partData.length > 0) {
765
+ partStresses.push(partData[0].stress.stressTrans || '');
766
+ partWeights.push(partData[0].weightPattern || '');
767
+ }
768
+ }
769
+ if (partStresses.length === parts.length && partStresses.every(s => s.length > 0)) {
770
+ const combinedStress = partStresses.join('');
771
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
772
+ word.isContent = isContent;
773
+ const syls = [];
774
+ for (let i = 0; i < combinedStress.length; i++) {
775
+ const cmu = parseInt(combinedStress[i], 10);
776
+ let numeric = mapCMUStress(cmu);
777
+ if (!isContent && numeric === 2)
778
+ numeric = 1;
779
+ syls.push({ text: word.word, phones: '', stress: numeric, lexicalStress: numeric });
780
+ }
781
+ word.syllables = syls;
782
+ continue;
783
+ }
784
+ }
785
+ if (!allData || allData.length === 0) {
786
+ const cleanWord = word.word.toLowerCase().replace(/-/g, '').replace(/['’]/g, '');
787
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
788
+ word.isContent = isContent;
789
+ // Tier 1: morphological stem (reuse real lexical stress); Tier 2: ESR.
790
+ const morph = morphologicalStress(cleanWord);
791
+ const pattern = morph ? morph.pattern : englishStressRule(cleanWord, isContent);
792
+ // Record an archaic verbal suffix so the display splits know·est, not kno·west.
793
+ if (morph && DISPLAY_PEEL_SUFFIXES.has(morph.suffix))
794
+ word.morphSuffix = morph.suffix;
795
+ const syls = pattern.map(numeric => {
796
+ // Mirror the in-vocab function-word reduction (primary → secondary).
797
+ const n = (!isContent && numeric === 2) ? 1 : numeric;
798
+ return { text: word.word, phones: '', stress: n, lexicalStress: n };
799
+ });
800
+ word.syllables = syls;
801
+ continue;
802
+ }
803
+ // For nouns with multiple pronunciations, prefer front‑stressed (noun form).
804
+ let profile = allData[0];
805
+ if (allData.length > 1 && word.lexicalClass.startsWith('N')) {
806
+ for (const p of allData) {
807
+ const stressStr = p.stress.stressTrans;
808
+ if (stressStr && stressStr.length > 0 && (stressStr[0] === '1' || stressStr[0] === '2')) {
809
+ profile = p;
810
+ break;
811
+ }
812
+ }
813
+ }
814
+ let rawStress = profile.stress.stressTrans || ''; // e.g., "010"
815
+ // The CMU syllabification is authoritative for the syllable count. The
816
+ // orthographic vowel-group count UNDER-counts vowel-hiatus / glide words
817
+ // (goo·ey, play·ers, be·ing each read as a single vowel run), so it must NOT
818
+ // truncate the dictionary's count — doing so collapsed those to one syllable.
819
+ // Only clamp when stressTrans is genuinely LONGER than the CMU
820
+ // syllabification (a rare data inconsistency).
821
+ const syllsMatch = (profile.phonology.syllabification || '').match(/\([^)]+\)/g) || [];
822
+ if (syllsMatch.length > 0 && rawStress.length > syllsMatch.length) {
823
+ rawStress = rawStress.slice(0, syllsMatch.length);
824
+ }
825
+ // Synaeresis (verse vowel-gliding): an UNSTRESSED open syllable ending in a
826
+ // high-front vowel (IY/IH), followed by an UNSTRESSED vowel-initial syllable,
827
+ // glides into one syllable in verse — As·syr·i·an → as·syr·yan, var·i·ous →
828
+ // var·yous, glor·i·ous → glor·yous. It does NOT fire on a stressed nucleus
829
+ // (be·ing, i·DE·a) or before a stressed vowel (cre·ATE), so those keep their
830
+ // full count. Distinct from the (removed) orthographic truncation: it merges
831
+ // only genuine glide pairs, leaving goo·ey / play·ers / po·et intact.
832
+ if (syllsMatch.length === rawStress.length && rawStress.length >= 2) {
833
+ const tokensOf = (s) => s.replace(/[()]/g, '').trim().split(/\s+/).filter(Boolean);
834
+ const mStress = [];
835
+ const mSylls = [];
836
+ for (let i = 0; i < rawStress.length; i++) {
837
+ const cur = tokensOf(syllsMatch[i]);
838
+ const last = cur[cur.length - 1] ?? '';
839
+ const next = i + 1 < rawStress.length ? tokensOf(syllsMatch[i + 1]) : [];
840
+ if (i + 1 < rawStress.length
841
+ && rawStress[i] === '0' && rawStress[i + 1] === '0'
842
+ && (last === 'IY' || last === 'IH')
843
+ && /^[AEIOU]/.test(next[0] ?? '')) {
844
+ mStress.push('0');
845
+ mSylls.push('(' + cur.concat(next).join(' ') + ')');
846
+ i++; // absorb the glided syllable
847
+ }
848
+ else {
849
+ mStress.push(rawStress[i]);
850
+ mSylls.push(syllsMatch[i]);
851
+ }
852
+ }
853
+ rawStress = mStress.join('');
854
+ syllsMatch.splice(0, syllsMatch.length, ...mSylls);
855
+ }
856
+ // All-zero CMU pattern on a polysyllabic word: restore the default stress.
857
+ // A handful of reduced function words (chiefly "into"=00) are recorded with
858
+ // NO stress at all, which left every syllable at 'x' (in·to = x·x) — both
859
+ // unlike careful usage (IN-to) and metrically inert. Every lexical word
860
+ // bears a stress, so we re-stamp a CMU primary on the default-stress syllable
861
+ // (forestress for disyllables); function-word demotion downstream turns this
862
+ // into a secondary, giving the natural IN-to contour. Only fires on the
863
+ // genuine all-zero artifact, so words that already carry a peak are untouched.
864
+ if (rawStress.length >= 2 && /^0+$/.test(rawStress)) {
865
+ const cw = word.word.toLowerCase().replace(/-/g, '').replace(/['’]/g, '');
866
+ const heavy = heavyFromSyllStruct(profile.phonology.syllStruct, rawStress.length);
867
+ // Rising/iambic function words (be·CAUSE, a·BOUT) recorded fully-reduced
868
+ // take FINAL-syllable stress; everything else keeps the forestress default
869
+ // (IN·to, and polysyllabic content artifacts).
870
+ const idx = RISING_FUNCTION_WORDS.has(cw)
871
+ ? rawStress.length - 1
872
+ : defaultStressIndex(cw, rawStress.length, heavy);
873
+ rawStress = rawStress.split('').map((c, i) => (i === idx ? '1' : '0')).join('');
874
+ }
875
+ // Targeted fix for the "I'm" anomaly: a subject-pronoun contraction the
876
+ // dictionary records as fully unstressed ("i'm"=0, while "i'll"=1) is restamped
877
+ // to a weak (function) stress, so it reads like its siblings ('n') rather than
878
+ // sinking to Zero-Provision 'x'. Narrow by construction — only fires on a
879
+ // monosyllabic, genuinely all-zero pronoun contraction; everything else is
880
+ // left exactly as it was.
881
+ if (rawStress === '0' && PRONOUN_SUBJECT_CONTRACTIONS.has(lookupWord)) {
882
+ rawStress = '1';
883
+ }
884
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
885
+ word.isContent = isContent;
886
+ const syllables = [];
887
+ const weightsArray = (profile.weightPattern || '').split(' ').filter(x => x === 'H' || x === 'L');
888
+ // Determine extrametricality classification for the final syllable.
889
+ // Uses Hayes (1980) constraints: only Light edge syllables, only noun final syllables,
890
+ // morphological s/z (plural/tense) markers, and derivational suffixes in adjectives.
891
+ const sClassifier = profile.S ?? '';
892
+ // Extrametricality is a property of nouns / derived adjectives. Key it off
893
+ // the word's actual sentence POS (from the parser), NOT nounsing's lexical
894
+ // pos — otherwise function words like the preposition "underneath" (which the
895
+ // CMU data may tag nominally) wrongly lose the stress on their final syllable.
896
+ const isNoun = word.lexicalClass.startsWith('N');
897
+ const isAdj = word.lexicalClass.startsWith('JJ');
898
+ const finalWeight = profile.weight.find(w => w.syllable === 'final')?.heaviness ?? '';
899
+ const nsylls = rawStress.length;
900
+ let extrametricalType = undefined;
901
+ if (nsylls >= 2) {
902
+ if ((sClassifier === 'S' || sClassifier === 'SCluster') && isNoun) {
903
+ extrametricalType = 'morphological';
904
+ }
905
+ else if (isNoun && finalWeight === 'L' && nsylls >= 3) {
906
+ extrametricalType = 'light_noun';
907
+ }
908
+ else if (isAdj && profile.morphology.suffix === 'suffix') {
909
+ extrametricalType = 'derivational';
910
+ }
911
+ }
912
+ const phonesTokens = profile.phonology.phones.split(' ');
913
+ let phoneIdx = 0;
914
+ for (let i = 0; i < rawStress.length; i++) {
915
+ const ch = rawStress[i];
916
+ const cmu = parseInt(ch, 10);
917
+ let numeric = mapCMUStress(cmu);
918
+ // Function words are reduced in running speech, but their INTERNAL stress
919
+ // contour must be preserved: demote the primary syllable to secondary AND
920
+ // the secondary syllables to none, so the lexical peak stays the peak.
921
+ // (Flattening primary→secondary alone would tie "un" and "neath" in
922
+ // "underneath", letting a later clash invert it to ÚN-der-neath.)
923
+ if (!isContent) {
924
+ if (numeric === 2)
925
+ numeric = 1;
926
+ else if (numeric === 1)
927
+ numeric = 0;
928
+ }
929
+ const wPatLen = weightsArray.length;
930
+ const rLen = rawStress.length;
931
+ const wIdx = wPatLen - (rLen - i);
932
+ const weight = wIdx >= 0 && wIdx < wPatLen ? weightsArray[wIdx] : 'L';
933
+ const sylTextMatch = syllsMatch[i];
934
+ const sylText = sylTextMatch ? sylTextMatch.replace(/[()]/g, '') : word.word;
935
+ const sylPhonesMatch = syllsMatch[i] || '';
936
+ const isLastSyl = i === rawStress.length - 1;
937
+ syllables.push({
938
+ text: sylText,
939
+ phones: sylPhonesMatch,
940
+ weight,
941
+ stress: numeric,
942
+ lexicalStress: numeric,
943
+ relativeStress: undefined,
944
+ extrametrical: isLastSyl ? extrametricalType : undefined,
945
+ });
946
+ }
947
+ if (extrametricalType) {
948
+ word.lexicalDetails = `extrametrical_${extrametricalType}`;
949
+ }
950
+ // A focus demonstrative ("What's THAT?", "Give me THIS.") carries PRIMARY
951
+ // stress; CMU lists the weak/reduced (complementizer) form, which would leave
952
+ // it merely 'n' after the nuclear boost. Force its peak to primary so the
953
+ // sentence's prominence lands on it.
954
+ if (isFocusDemonstrative(words, wi) && syllables.length > 0) {
955
+ const pk = syllables.reduce((a, b) => (b.stress >= a.stress ? b : a));
956
+ pk.stress = 2;
957
+ pk.lexicalStress = 2;
958
+ }
959
+ word.syllables = syllables;
960
+ }
961
+ }
962
+ // ─── COMPOUND STRESS RULE ─────────────────────────────────────────
963
+ /**
964
+ * Adjust stresses for nominal compounds.
965
+ *
966
+ * Fore-stressed by default: an N+N compound puts primary (2) on the first
967
+ * element, secondary (1) on the second — the Compound Stress Rule (Chomsky–
968
+ * Halle; McAleese marks ICE cream with primary on "ice", KITCHen table,
969
+ * WINdow frame). The marked right-stress exceptions — food/temporal "made of"
970
+ * heads (apple PIE), Adj+N phrases (sweet CREAM), and proper-name sequences
971
+ * (New YORK) — reverse it. All of this lives in `compoundStressSide`.
972
+ */
973
+ export function applyCompoundStress(ius) {
974
+ for (const iu of ius) {
975
+ for (const pp of iu.phonologicalPhrases) {
976
+ const words = collectPPTokens(pp);
977
+ // We don't want compound stress applied between arbitrary words across a phrase!
978
+ // Only apply to ADJACENT content words!
979
+ const contentWords = words.filter(w => w.isContent);
980
+ for (let i = 0; i < contentWords.length - 1; i++) {
981
+ const w1 = contentWords[i];
982
+ const w2 = contentWords[i + 1];
983
+ // Wait, they must be adjacent in the sentence!
984
+ if (Math.abs(w1.absoluteIndex - w2.absoluteIndex) !== 1)
985
+ continue;
986
+ const side = compoundStressSide(w1.word, w1.lexicalClass, w2.word, w2.lexicalClass);
987
+ if (side === null)
988
+ continue;
989
+ if (side === 'left') {
990
+ setPrimaryStress(w1, 2);
991
+ setPrimaryStress(w2, 1);
992
+ }
993
+ else {
994
+ setPrimaryStress(w1, 1);
995
+ setPrimaryStress(w2, 2);
996
+ }
997
+ }
998
+ }
999
+ }
1000
+ }
1001
+ /** Locate the syllable with the highest stress and set it to `value`. */
1002
+ export function setPrimaryStress(word, value) {
1003
+ let maxIdx = -1;
1004
+ let maxVal = -1;
1005
+ for (let i = 0; i < word.syllables.length; i++) {
1006
+ if (word.syllables[i].stress > maxVal) {
1007
+ maxVal = word.syllables[i].stress;
1008
+ maxIdx = i;
1009
+ }
1010
+ }
1011
+ if (maxIdx >= 0) {
1012
+ word.syllables[maxIdx].stress = value;
1013
+ }
1014
+ }
1015
+ // ─── NUCLEAR STRESS RULE ──────────────────────────────────────────
1016
+ /**
1017
+ * Recursively assign higher stress to content words from right to left.
1018
+ * Only the rightmost content word receives a boost (+1 above lexical primary).
1019
+ * All other content words keep their lexical stress.
1020
+ * This preserves lexical stress for meter detection while still indicating
1021
+ * the nuclear accent for phonological phrasing.
1022
+ */
1023
+ export function applyNuclearStress(ius) {
1024
+ for (const iu of ius) {
1025
+ for (const pp of iu.phonologicalPhrases) {
1026
+ const words = collectPPTokens(pp).sort((a, b) => a.index - b.index);
1027
+ // The nuclear accent normally lands on the rightmost CONTENT word.
1028
+ let target = null;
1029
+ for (let i = words.length - 1; i >= 0; i--) {
1030
+ if (words[i].isContent) {
1031
+ target = words[i];
1032
+ break;
1033
+ }
1034
+ }
1035
+ // But a content-less phrase ending in a non-oblique personal pronoun puts
1036
+ // the nuclear accent on that final pronoun (NSR: the accent falls on the
1037
+ // last accentable item; a clause-final addressee/focus pronoun bears it —
1038
+ // "…to YOU"). Only when there is no content word to carry it, so "I KNOW
1039
+ // you" is untouched; oblique objects (me/him/them) stay deaccented.
1040
+ if (!target) {
1041
+ let lastIdx = -1;
1042
+ for (let i = words.length - 1; i >= 0; i--) {
1043
+ if (!isPunctuation(words[i].lexicalClass)) {
1044
+ lastIdx = i;
1045
+ break;
1046
+ }
1047
+ }
1048
+ if (lastIdx >= 0) {
1049
+ const w = words[lastIdx];
1050
+ if (w.lexicalClass === 'PRP'
1051
+ && !OBLIQUE_PRONOUNS.has(w.word.toLowerCase().replace(/['’]/g, ''))) {
1052
+ target = w;
1053
+ }
1054
+ }
1055
+ }
1056
+ if (target) {
1057
+ let maxIdx = -1;
1058
+ let maxVal = -1;
1059
+ for (let j = 0; j < target.syllables.length; j++) {
1060
+ if (target.syllables[j].stress > maxVal) {
1061
+ maxVal = target.syllables[j].stress;
1062
+ maxIdx = j;
1063
+ }
1064
+ }
1065
+ if (maxIdx >= 0)
1066
+ target.syllables[maxIdx].stress += 1;
1067
+ }
1068
+ }
1069
+ }
1070
+ }
1071
+ // ─── RELATIVE STRESS ASSIGNMENT (4‑LEVEL) ─────────────────────────
1072
+ /**
1073
+ * Phrase-edge sets used for the "endings strict / beginnings loose" floor gate.
1074
+ * McAleese (after Hayes & Kaun): metrical and lexical stress coincide at the
1075
+ * ENDS of phonological units (clitic phrase 90% / phonological phrase 97% /
1076
+ * intonational unit 99%); Selkirk notes a function word is not reduced at the
1077
+ * end of a clitic phrase ("of" never → "o'" there). So a function word at the
1078
+ * right edge of a PP or IU — or the phrase-stress PEAK (nucleus) of its PP —
1079
+ * resists the citation-floor reduction, while interior / left-edge function
1080
+ * words reduce as before. Reads the Phrase-Stress phase (word.phraseStress).
1081
+ */
1082
+ function phraseEdgeSets(ius) {
1083
+ const ppFinal = new Set();
1084
+ const iuFinal = new Set();
1085
+ const ppPeak = new Set();
1086
+ for (const iu of ius) {
1087
+ let iuLast = null;
1088
+ for (const pp of iu.phonologicalPhrases) {
1089
+ const toks = collectPPTokens(pp)
1090
+ .filter(w => !isPunctuation(w.lexicalClass))
1091
+ .sort((a, b) => a.index - b.index);
1092
+ if (toks.length === 0)
1093
+ continue;
1094
+ const last = toks[toks.length - 1];
1095
+ ppFinal.add(last);
1096
+ iuLast = last;
1097
+ let peak = toks[0];
1098
+ let peakVal = peak.phraseStress ?? 0;
1099
+ for (const t of toks) {
1100
+ const v = t.phraseStress ?? 0;
1101
+ if (v > peakVal) {
1102
+ peak = t;
1103
+ peakVal = v;
1104
+ }
1105
+ }
1106
+ // Only protect a genuine nuclear ramp peak (phraseStress ≥ 2): an all-floor
1107
+ // PP (all function words, or the Phase-Stress phase not run) has no nucleus
1108
+ // to protect, so we must not spuriously shield its first token.
1109
+ if (peakVal >= 2)
1110
+ ppPeak.add(peak);
1111
+ }
1112
+ if (iuLast)
1113
+ iuFinal.add(iuLast);
1114
+ }
1115
+ return { ppFinal, iuFinal, ppPeak };
1116
+ }
1117
+ /**
1118
+ * Convert numeric per‑syllable stress to McAleese’s symbolic levels
1119
+ * (w, n, m, s) and resolve adjacent identical stresses using dependency
1120
+ * information.
1121
+ */
1122
+ export function assignRelativeStresses(words, ius) {
1123
+ // Phrase-edge sets for the endings-strict floor gate (read from Phase-Stress).
1124
+ const edges = phraseEdgeSets(ius);
1125
+ // Syllables raised by dependency-mined prominence (stranded preposition,
1126
+ // contrastive possessive, vocative): protected from the per-PP trailing-run
1127
+ // flatten so the recovered beat survives.
1128
+ const prominenceProtected = new Set();
1129
+ // First pass: numeric → symbolic (0→w, 1→n, 2→m, 3+→s)
1130
+ // Use lexicalStress (pre-nuclear) so nuclear stress doesn't corrupt meter detection.
1131
+ for (const word of words) {
1132
+ for (const syl of word.syllables) {
1133
+ const val = syl.lexicalStress ?? syl.stress;
1134
+ if (val === 0) {
1135
+ // Zero-Provision (`x`) for a maximally-reduced clitic: a stressless
1136
+ // syllable of a function word reads *below* a stressless content
1137
+ // syllable (the/a/of/and… vs. the weak syllable of a content word).
1138
+ // EXCEPTION: an aphaeresis clipping ('neath/o'er/'gainst…) is the
1139
+ // *lexically-stressed* syllable of its base word surviving the clip — an
1140
+ // overt syllable carrying real stress, merely reduced in context. `x`
1141
+ // means extrametrical (Hayes' zero-provision), which it is NOT; so it
1142
+ // floors at `w` (overt weak), promotable like any weak syllable.
1143
+ const bare = word.word.toLowerCase().replace(/['’]/g, '');
1144
+ // Function VERBS (copula/aux/aspectual: be/is/keeps/began…) and
1145
+ // function ADVERBS (deictic/scalar: just/now/then/here/there…) floor
1146
+ // at 'w', not 'x': both classes carry full, unreducible vowels —
1147
+ // 'x' is for schwa-able clitics (the/a/of/and). At 'w' they remain
1148
+ // Attridge-promotable, recovering e.g. the dactylic opening beat of
1149
+ // "JUST for a riband to STICK in his coat" (Browning).
1150
+ if (word.isContent || APHAERESIS_CLITICS.has(bare)
1151
+ || FUNCTION_VERBS.has(bare) || FUNCTION_ADVERBS.has(bare)) {
1152
+ syl.relativeStress = 'w';
1153
+ }
1154
+ else {
1155
+ syl.relativeStress = 'x';
1156
+ }
1157
+ }
1158
+ else if (val === 1) {
1159
+ syl.relativeStress = 'n';
1160
+ }
1161
+ else if (val === 2) {
1162
+ syl.relativeStress = 'm';
1163
+ }
1164
+ else {
1165
+ syl.relativeStress = 's';
1166
+ }
1167
+ // Monosyllabic function clitic → floor at 'w' (overt-weak, promotable),
1168
+ // never 'n'. A CMU-primary monosyllabic preposition/determiner/possessive/
1169
+ // wh-word/coordinator is reduced in running speech; flooring it at 'n' is
1170
+ // what produced the flat function-word runs ("So on my", "where strange").
1171
+ // (Pure clitics the/a/of already read 'x' via the val===0 branch.)
1172
+ if (syl.relativeStress === 'n'
1173
+ && (isMonosyllabicClitic(word) || word.word.toLowerCase() === 'am')) {
1174
+ // "am" (1sg copula) is reliably reduced — far more so than beat-bearing
1175
+ // is/are/was/were — so it floors at 'w' (still Attridge-promotable) rather
1176
+ // than surfacing at 'm' as a spurious beat in "As I am BLOOD…". Kept to
1177
+ // this one form: flooring all be-verbs regressed Wyatt's accentual + corpus.
1178
+ syl.relativeStress = 'w';
1179
+ }
1180
+ // Downgrade extrametrical syllables by one level. We do NOT push a weak
1181
+ // syllable to 'x' here: 'x' (zero-provision) is reserved for maximally-
1182
+ // reduced *clitics*, whereas a weak *content* syllable (e.g. the feminine
1183
+ // ending "li·cense") stays 'w' per the maintainer's tier semantics.
1184
+ if (syl.extrametrical === 'morphological') {
1185
+ if (syl.relativeStress === 'n')
1186
+ syl.relativeStress = 'w';
1187
+ else if (syl.relativeStress === 'm')
1188
+ syl.relativeStress = 'n';
1189
+ else if (syl.relativeStress === 's')
1190
+ syl.relativeStress = 'm';
1191
+ }
1192
+ }
1193
+ // Honest baseline prominence: floor a monosyllabic function word to its true
1194
+ // reading prominence ('x' schwa-clitic / 'w' overt-weak), never raising it.
1195
+ // The dictionary's citation stress on "and"/"in"/"my"/"could" is an artefact;
1196
+ // the meter layer re-promotes these where the metre needs a beat.
1197
+ //
1198
+ // ENDINGS STRICT / BEGINNINGS LOOSE (McAleese; Selkirk): withhold the floor
1199
+ // for a function word at the right edge of a PP or IU, or one that is its
1200
+ // PP's phrase-stress peak — it resists reduction there (a stranded/clause-
1201
+ // final "to"/"you"/"of" is not crushed to a clitic). Oblique object
1202
+ // pronouns (me/him/thee…) are excepted: they stay default-deaccented even
1203
+ // phrase-finally ("I gave it to HIM" only under focus, handled later).
1204
+ const lemma = word.word.toLowerCase().replace(/['’]/g, '');
1205
+ const edgeProtected = (edges.iuFinal.has(word) || edges.ppFinal.has(word) || edges.ppPeak.has(word))
1206
+ && !OBLIQUE_PRONOUNS.has(lemma);
1207
+ const floor = relativeFloorFor(word);
1208
+ if (floor && !edgeProtected) {
1209
+ const fr = STRESS_RANK[floor];
1210
+ for (const syl of word.syllables) {
1211
+ if (STRESS_RANK[syl.relativeStress ?? 'w'] > fr)
1212
+ syl.relativeStress = floor;
1213
+ }
1214
+ }
1215
+ // Dependency-mined prominence (the parse IS the semantic layer): recover the
1216
+ // beat a flat POS floor would crush. A STRANDED preposition ("waiting FOR",
1217
+ // "stare AT") and a CONTRASTIVE possessive ("THY choice, not mine") bear
1218
+ // real stress → raise the peak to at least 'n' (promotable); a VOCATIVE
1219
+ // address ("Sing, O GODDESS") to at least 'm'. Raise-only; the raised peak
1220
+ // is protected from the per-PP trailing-run flatten below.
1221
+ let promoteTo = null;
1222
+ if (isVocative(word, words) || isDeicticLocative(word, words))
1223
+ promoteTo = 'm';
1224
+ else if (isStrandedPreposition(word, words) || isContrastivePossessive(word, words))
1225
+ promoteTo = 'n';
1226
+ if (promoteTo) {
1227
+ const pk = wordPeak(word);
1228
+ if (pk && STRESS_RANK[pk.relativeStress ?? 'w'] < STRESS_RANK[promoteTo]) {
1229
+ pk.relativeStress = promoteTo;
1230
+ }
1231
+ if (pk)
1232
+ prominenceProtected.add(pk);
1233
+ }
1234
+ // Exclamatory interjection ("O", "Oh", "Ah", "Lo", "Alas"): emphatic, never
1235
+ // reduced — raise its peak to at least 'n' (corrects the mis-tag that floored
1236
+ // vocative "O"→IN→'x'). Raise-only; an exclaimed one is lifted further below.
1237
+ if (EXCLAM_INTERJECTIONS.has(word.word.toLowerCase())) {
1238
+ const pk = wordPeak(word);
1239
+ if (pk && STRESS_RANK[pk.relativeStress ?? 'w'] < STRESS_RANK.n)
1240
+ pk.relativeStress = 'n';
1241
+ }
1242
+ }
1243
+ // Apply nuclear stress boosts to relative stress.
1244
+ // `syl.stress` may be higher than `syl.lexicalStress` after applyNuclearStress
1245
+ // boosted the rightmost content word. Each level of increase promotes the
1246
+ // relative stress by one tier: w→n, n→m, m→s.
1247
+ for (const word of words) {
1248
+ for (const syl of word.syllables) {
1249
+ const base = syl.lexicalStress ?? 0;
1250
+ const boost = syl.stress - base;
1251
+ if (boost > 0) {
1252
+ let current = syl.relativeStress ?? 'w';
1253
+ for (let i = 0; i < boost; i++) {
1254
+ if (current === 'x')
1255
+ current = 'w';
1256
+ else if (current === 'w')
1257
+ current = 'n';
1258
+ else if (current === 'n')
1259
+ current = 'm';
1260
+ else if (current === 'm')
1261
+ current = 's';
1262
+ }
1263
+ syl.relativeStress = current;
1264
+ }
1265
+ }
1266
+ }
1267
+ // Second pass: resolve adjacent identical stresses within each phonological phrase
1268
+ for (const iu of ius) {
1269
+ for (const pp of iu.phonologicalPhrases) {
1270
+ const ppWords = collectPPTokens(pp);
1271
+ resolveAdjacentClashes(ppWords, prominenceProtected);
1272
+ }
1273
+ }
1274
+ // Third pass: resolve clashes across prosodic boundaries (PP and IU).
1275
+ // McAleese: when two adjacent syllables at a prosodic boundary have equal stress
1276
+ // and one is a function word, demote the function word (beginnings-free principle).
1277
+ resolveCrossBoundaryClashes(words, ius);
1278
+ // Compound forestress (linear surface order): a left-stressed compound's
1279
+ // prominence sits on its LEFT element (WASTE·shore, SEA·shore, GHOST·town).
1280
+ // The phrasal compound/nuclear rules run in hierarchy order, which a mis-
1281
+ // grouped parse can split (e.g. "a cavernous waste shore" separating
1282
+ // waste/shore), so we re-assert forestress here on true surface adjacency,
1283
+ // after the clash passes, so it survives the rightmost-content nuclear boost.
1284
+ resolveCompoundForestress(words);
1285
+ resolveCollocationForestress(words);
1286
+ resolveHyphenCompounds(words);
1287
+ // Fourth pass: resolve clashes on the LINEAR SURFACE order. A stress clash is
1288
+ // a property of *contiguous pronounced* syllables (Hayes' "two contiguous
1289
+ // syllables"), i.e. surface order — but the phrasal passes above run in
1290
+ // hierarchy order, which a mis-grouped parse can scramble (e.g. "a cavernous
1291
+ // waste shore" leaving "waste"/"shore" non-adjacent in the tree though
1292
+ // contiguous in speech). Catch any residual cardinal s–s clash here.
1293
+ resolveLinearClashes(words);
1294
+ // Exclaimed interjection: an interjection immediately followed by "!" (Oh!, Ah!,
1295
+ // O!, Lo!) is an emphatic peak — raise it one tier so it stands out from a flat
1296
+ // run of neighbouring function words ("But—Oh! ye lords…" was a monotone n·n·n,
1297
+ // with the interjection no louder than the conjunction beside it). Narrow by
1298
+ // construction: only an UH whose very next token is "!".
1299
+ for (let i = 0; i < words.length - 1; i++) {
1300
+ const w = words[i];
1301
+ if (w.lexicalClass !== 'UH' || w.syllables.length === 0)
1302
+ continue;
1303
+ if (words[i + 1].word !== '!')
1304
+ continue;
1305
+ const pk = wordPeak(w);
1306
+ if (!pk)
1307
+ continue;
1308
+ const r = STRESS_RANK[pk.relativeStress ?? 'w'];
1309
+ if (r < STRESS_RANK.s)
1310
+ pk.relativeStress = STRESS_LEVELS[r + 1];
1311
+ }
1312
+ }
1313
+ /** Ascending rank of the 5 relative-stress tiers, for level arithmetic. */
1314
+ const STRESS_RANK = { x: 0, w: 1, n: 2, m: 3, s: 4 };
1315
+ const STRESS_LEVELS = ['x', 'w', 'n', 'm', 's'];
1316
+ /**
1317
+ * Re-assert left-stress on forestressed compounds over the LINEAR surface
1318
+ * sequence (e.g. WASTE·shore, SEA·shore, GHOST·town, STORM·cloud). For each
1319
+ * pair of truly-adjacent content words (by absoluteIndex) that the Compound
1320
+ * Stress Rule marks left-stressed, the left element's peak is raised to the
1321
+ * pair's maximum prominence and the right element's peak is demoted one rung
1322
+ * below it — never raising the subordinate. Runs on surface order so it works
1323
+ * even when the parse mis-groups the two into different phrases.
1324
+ */
1325
+ function resolveCompoundForestress(words) {
1326
+ const content = words.filter(w => w.isContent && !isPunctuation(w.lexicalClass));
1327
+ for (let i = 0; i < content.length - 1; i++) {
1328
+ const w1 = content[i];
1329
+ const w2 = content[i + 1];
1330
+ if (Math.abs(w1.absoluteIndex - w2.absoluteIndex) !== 1)
1331
+ continue; // truly adjacent
1332
+ const pos1 = w1.lexicalClass, pos2 = w2.lexicalClass;
1333
+ if (!(pos2.startsWith('N') && (pos1.startsWith('N') || pos1.startsWith('J'))))
1334
+ continue;
1335
+ if (!isLeftStressedPair(w1.word, w2.word))
1336
+ continue;
1337
+ const s1 = wordPeak(w1);
1338
+ const s2 = wordPeak(w2);
1339
+ if (!s1 || !s2)
1340
+ continue;
1341
+ const r1 = STRESS_RANK[s1.relativeStress ?? 'w'];
1342
+ const r2 = STRESS_RANK[s2.relativeStress ?? 'w'];
1343
+ const hi = Math.max(r1, r2);
1344
+ s1.relativeStress = STRESS_LEVELS[hi]; // head ≥ both
1345
+ s2.relativeStress = STRESS_LEVELS[Math.min(r2, Math.max(0, hi - 1))]; // demote-only
1346
+ }
1347
+ }
1348
+ /**
1349
+ * Forestress lexicalised collocations (GOOD old, END-all) over the LINEAR
1350
+ * surface sequence. Unlike `resolveCompoundForestress` this iterates ALL words
1351
+ * (not just content), because a collocation's second element may be a function
1352
+ * word ("end ALL" — "all" is a determiner): raise the left element's peak to the
1353
+ * pair maximum and demote the right one rung (demote-only, never raises the
1354
+ * subordinate).
1355
+ */
1356
+ function resolveCollocationForestress(words) {
1357
+ const seq = words
1358
+ .filter(w => !isPunctuation(w.lexicalClass) && w.syllables.length > 0)
1359
+ .sort((a, b) => a.absoluteIndex - b.absoluteIndex);
1360
+ for (let i = 0; i < seq.length - 1; i++) {
1361
+ const w1 = seq[i];
1362
+ const w2 = seq[i + 1];
1363
+ if (w2.absoluteIndex - w1.absoluteIndex !== 1)
1364
+ continue; // truly adjacent
1365
+ if (!isLeftStressedCollocation(w1, w2))
1366
+ continue;
1367
+ const s1 = wordPeak(w1);
1368
+ const s2 = wordPeak(w2);
1369
+ if (!s1 || !s2)
1370
+ continue;
1371
+ const r1 = STRESS_RANK[s1.relativeStress ?? 'w'];
1372
+ const r2 = STRESS_RANK[s2.relativeStress ?? 'w'];
1373
+ const hi = Math.max(r1, r2);
1374
+ s1.relativeStress = STRESS_LEVELS[hi]; // left element ≥ both
1375
+ s2.relativeStress = STRESS_LEVELS[Math.min(r2, Math.max(0, hi - 1))]; // demote-only
1376
+ }
1377
+ }
1378
+ /**
1379
+ * Resolve the dual-strong clash at a hyphen seam inside a compound word
1380
+ * ("torch-flames", "blood-red"). The parser keeps a hyphenated compound as a
1381
+ * single token, so the word-level compound and clash passes never see its two
1382
+ * halves — left alone, both keep primary stress (s·s). For a hyphenated content
1383
+ * word whose hyphen parts align 1:1 with its syllables, an adjacent s·s seam is
1384
+ * resolved with the same logic as a two-word compound: forestress the left if it
1385
+ * is a known forestress modifier, otherwise retract the left (the nuclear /
1386
+ * right-stress default, e.g. torch-FLAMES).
1387
+ */
1388
+ function resolveHyphenCompounds(words) {
1389
+ for (const w of words) {
1390
+ if (!w.isContent || !w.word.includes('-'))
1391
+ continue;
1392
+ const parts = w.word.split('-').filter(p => p.length > 0);
1393
+ if (parts.length < 2 || parts.length !== w.syllables.length)
1394
+ continue;
1395
+ for (let i = 0; i < w.syllables.length - 1; i++) {
1396
+ const a = w.syllables[i];
1397
+ const b = w.syllables[i + 1];
1398
+ // An equal-strong seam (s·s or m·m) is the unresolved compound clash.
1399
+ const equalStrong = a.relativeStress === b.relativeStress
1400
+ && (a.relativeStress === 's' || a.relativeStress === 'm');
1401
+ if (equalStrong) {
1402
+ if (isLeftStressedPair(parts[i], parts[i + 1]))
1403
+ demoteOneLevel(b); // BLOOD-red
1404
+ else
1405
+ demoteOneLevel(a); // torch-FLAMES
1406
+ }
1407
+ }
1408
+ }
1409
+ }
1410
+ /**
1411
+ * THE CLASH FILTER — an absolute surface well-formedness constraint.
1412
+ *
1413
+ * On the STRESSED tier {n, m, s} no two *contiguous* syllables may carry the SAME
1414
+ * level: that is a stress clash (two equal prominences with no gradation between
1415
+ * them), which English categorically disallows. Gradient pairs (sm/ms/sn/ns/mn/nm)
1416
+ * are fine — there is still a step down — as are runs of the unstressed tiers
1417
+ * {w, x} (an unstressed sequence is tolerated, if not ideal). This generalises
1418
+ * McAleese's Appendix-A step 3d-ii ("stress clashes (ss, ms) > s-s") and Liberman
1419
+ * & Prince's (1977) grid alternation to every level of the strong tier.
1420
+ *
1421
+ * Resolution is DEMOTE-ONLY (never promote — promotion is the meter layer's job,
1422
+ * McAleese Test 2), so the contour is never inflated to break a clash; we iterate
1423
+ * to a fixed point (each change strictly lowers total stress mass, so it
1424
+ * terminates). Which member yields is decided by `demoteRightOfClash` (grid-based
1425
+ * relative prominence). Runs on the LINEAR surface order because a clash is a
1426
+ * property of contiguous *pronounced* syllables (Hayes), which a mis-grouped
1427
+ * dependency parse can scatter across phrases.
1428
+ */
1429
+ export function resolveLinearClashes(words) {
1430
+ const flat = [];
1431
+ for (const w of words)
1432
+ for (const s of w.syllables)
1433
+ flat.push({ word: w, syl: s });
1434
+ let changed = true;
1435
+ let guard = 0;
1436
+ while (changed && guard++ < 24) {
1437
+ changed = false;
1438
+ for (let i = 0; i < flat.length - 1; i++) {
1439
+ const a = flat[i];
1440
+ const b = flat[i + 1];
1441
+ const lvl = a.syl.relativeStress;
1442
+ if (lvl !== b.syl.relativeStress)
1443
+ continue;
1444
+ if (lvl !== 'n' && lvl !== 'm' && lvl !== 's')
1445
+ continue; // only the stressed tier clashes
1446
+ // Intra-word clashes are NOT skipped: a hyphenated-compound seam
1447
+ // (deep·voiced, snow·storm, gate·bolts) or any word with two adjacent equal
1448
+ // stresses is still a clash, and must be made gradient like any other.
1449
+ if (demoteRightOfClash(flat, i))
1450
+ demoteOneLevel(b.syl);
1451
+ else
1452
+ demoteOneLevel(a.syl);
1453
+ changed = true;
1454
+ }
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Decide which member of an equal-stress clash at (i, i+1) yields. Rather than a
1459
+ * blunt leftward retraction, a layered cascade consults — in descending
1460
+ * authority — lexical, syntactic, and phonological context, so the demotion is
1461
+ * theory-grounded and the arbitrary default fires only as a last resort. Returns
1462
+ * true to demote the RIGHT member (i+1), false to demote the LEFT (i).
1463
+ *
1464
+ * 1. Lexical integrity (Kiparsky): never demote a polysyllable's own stress
1465
+ * peak for an adjacent monosyllable — the monosyllable yields.
1466
+ * 2. Inherent lexical prominence: a primary-stressed syllable outranks a
1467
+ * secondary one — the lower-lexical-stress member yields.
1468
+ * 3. Syntactic headedness (Nuclear Stress Rule; Liberman & Prince 1977; Cinque
1469
+ * 1993): when the two words stand in a direct head–dependent relation, the
1470
+ * DEPENDENT yields to its governor (the phrasal head is the more prominent).
1471
+ * 4. Content/function asymmetry — a coarse proxy for headedness when no direct
1472
+ * dependency links the pair: the function word yields.
1473
+ * 5. Phonological weight: a light (open, short-vowel) syllable reduces more
1474
+ * readily than a heavy (closed / long-vowel) one — the lighter member yields.
1475
+ * 6. Rhythm Rule (Liberman & Prince 1977; Hayes 1984): the clash member abutting
1476
+ * the stronger OUTER beat is that beat's off-beat, so it retracts — "wet
1477
+ * CHURCH" retracts wet (church is nuclear), "LATE last NIGHT" retracts last
1478
+ * onto late (night is the following beat).
1479
+ * 7. Default (Hayes): retract the LEFT stress.
1480
+ */
1481
+ function demoteRightOfClash(flat, i) {
1482
+ const a = flat[i];
1483
+ const b = flat[i + 1];
1484
+ // (1) lexical integrity
1485
+ const aPeak = a.word.syllables.length > 1 && a.syl === wordPeak(a.word);
1486
+ const bPeak = b.word.syllables.length > 1 && b.syl === wordPeak(b.word);
1487
+ if (aPeak && !bPeak && b.word.syllables.length === 1)
1488
+ return true;
1489
+ if (bPeak && !aPeak && a.word.syllables.length === 1)
1490
+ return false;
1491
+ // (2) inherent lexical prominence
1492
+ const la = a.syl.lexicalStress ?? a.syl.stress ?? 0;
1493
+ const lb = b.syl.lexicalStress ?? b.syl.stress ?? 0;
1494
+ if (la !== lb)
1495
+ return la > lb;
1496
+ // (3) syntactic headedness — the dependent yields to its governor
1497
+ if (a.word !== b.word) {
1498
+ const gov = getGovernor(a.word, b.word);
1499
+ if (gov === a.word)
1500
+ return true; // a heads b → demote b
1501
+ if (gov === b.word)
1502
+ return false; // b heads a → demote a
1503
+ }
1504
+ // (4) content/function asymmetry — the function word yields
1505
+ if (a.word.isContent !== b.word.isContent)
1506
+ return a.word.isContent;
1507
+ // (5) phonological weight — the lighter syllable yields
1508
+ if (a.syl.weight && b.syl.weight && a.syl.weight !== b.syl.weight) {
1509
+ return a.syl.weight === 'H'; // a heavy → demote the lighter b
1510
+ }
1511
+ // (6) Rhythm Rule — yield to the stronger adjacent (outer) beat
1512
+ const outerA = i - 1 >= 0 ? STRESS_RANK[flat[i - 1].syl.relativeStress ?? 'w'] : -1;
1513
+ const outerB = i + 2 < flat.length ? STRESS_RANK[flat[i + 2].syl.relativeStress ?? 'w'] : -1;
1514
+ if (outerA !== outerB)
1515
+ return outerB > outerA;
1516
+ // (7) default: retract the left
1517
+ return false;
1518
+ }
1519
+ /**
1520
+ * Scan across the linear sequence of syllables and adjust any adjacent
1521
+ * identical relative stress levels using syntactic governance.
1522
+ */
1523
+ function resolveAdjacentClashes(words, protect) {
1524
+ // "Endings strict": when a phrase ends in a run of two or more bare function
1525
+ // words (e.g. "…fast as you MIGHT"), the metrical beat gravitates to one of
1526
+ // them; the others are upbeat. Demote the others so a leftward governance
1527
+ // clash can't promote a medial off-beat ("you") over the phrase-final beat.
1528
+ // Phrases ending in a content word are untouched.
1529
+ {
1530
+ let runStart = words.length;
1531
+ while (runStart > 0 && !words[runStart - 1].isContent)
1532
+ runStart--;
1533
+ if (words.length - runStart >= 2) {
1534
+ // The beat is normally the run's last word, UNLESS that is a clause-final
1535
+ // oblique pronoun (me/him/them…), which is canonically unstressed — then
1536
+ // the beat falls on the preceding member ("and beHIND me", not "behind ME").
1537
+ let beatIdx = words.length - 1;
1538
+ if (OBLIQUE_PRONOUNS.has(words[beatIdx].word.toLowerCase()) && beatIdx > runStart) {
1539
+ beatIdx--;
1540
+ }
1541
+ for (let wi = runStart; wi < words.length; wi++) {
1542
+ if (wi === beatIdx)
1543
+ continue;
1544
+ const w = words[wi];
1545
+ const peak = wordPeak(w);
1546
+ for (const s of w.syllables) {
1547
+ // Protect a polysyllabic word's own lexical peak: never flatten a real
1548
+ // internal stress (be·HIND) to 'w' just because the word is functional.
1549
+ if (w.syllables.length > 1 && s === peak && (s.lexicalStress ?? s.stress) >= 1)
1550
+ continue;
1551
+ // Protect a dependency-mined prominence (stranded preposition etc.).
1552
+ if (protect && protect.has(s))
1553
+ continue;
1554
+ s.relativeStress = 'w';
1555
+ }
1556
+ }
1557
+ }
1558
+ }
1559
+ // Flatten all syllables with reference to their owning word.
1560
+ const flat = [];
1561
+ for (const w of words) {
1562
+ for (const s of w.syllables) {
1563
+ flat.push({ word: w, syl: s });
1564
+ }
1565
+ }
1566
+ for (let i = 0; i < flat.length - 1; i++) {
1567
+ const a = flat[i];
1568
+ const b = flat[i + 1];
1569
+ if (a.syl.relativeStress !== b.syl.relativeStress)
1570
+ continue;
1571
+ // Only the stressed tier {n,m,s} clashes; {w,x} may repeat (maintainer's rule:
1572
+ // an unstressed run is tolerated, never "resolved" by demoting a clitic to 'x').
1573
+ const lvl = a.syl.relativeStress;
1574
+ if (lvl !== 'n' && lvl !== 'm' && lvl !== 's')
1575
+ continue;
1576
+ // Within-word strictness (Kiparsky): a polysyllabic word's own stress peak
1577
+ // must not be demoted below its word-mates by a clash with an adjacent
1578
+ // monosyllable. Protect the peak; demote the monosyllable instead.
1579
+ const aPeak = a.word.syllables.length > 1 && a.syl === wordPeak(a.word);
1580
+ const bPeak = b.word.syllables.length > 1 && b.syl === wordPeak(b.word);
1581
+ if (aPeak && b.word.syllables.length === 1) {
1582
+ adjustAdjacent(a.syl, b.syl, governorDependentDirection);
1583
+ continue;
1584
+ }
1585
+ if (bPeak && a.word.syllables.length === 1) {
1586
+ adjustAdjacent(b.syl, a.syl, governorDependentDirection);
1587
+ continue;
1588
+ }
1589
+ // Otherwise use the syntactic governor relationship.
1590
+ const governor = getGovernor(a.word, b.word);
1591
+ if (governor === a.word) {
1592
+ // a governs b → a stronger, b weaker
1593
+ adjustAdjacent(a.syl, b.syl, governorDependentDirection);
1594
+ }
1595
+ else if (governor === b.word) {
1596
+ // b governs a → b stronger, a weaker
1597
+ adjustAdjacent(b.syl, a.syl, governorDependentDirection);
1598
+ }
1599
+ // If no relationship, leave untouched.
1600
+ }
1601
+ }
1602
+ /** The syllable bearing a word's lexical stress peak (used for within-word protection). */
1603
+ function wordPeak(word) {
1604
+ let best;
1605
+ let bestVal = -Infinity;
1606
+ for (const s of word.syllables) {
1607
+ const v = s.lexicalStress ?? s.stress;
1608
+ if (v > bestVal) {
1609
+ bestVal = v;
1610
+ best = s;
1611
+ }
1612
+ }
1613
+ return best;
1614
+ }
1615
+ /** Return the governor word if one directly governs the other, else null. */
1616
+ function getGovernor(w1, w2) {
1617
+ const dep1 = w1.dependency;
1618
+ const dep2 = w2.dependency;
1619
+ if (!dep1 || !dep2)
1620
+ return null;
1621
+ // Check if w2 is a dependent of w1.
1622
+ if (dep2.governor === w1)
1623
+ return w1;
1624
+ // Check if w1 is a dependent of w2.
1625
+ if (dep1.governor === w2)
1626
+ return w2;
1627
+ return null;
1628
+ }
1629
+ /** Adjustment direction: governor stronger (promote), dependent weaker (demote). */
1630
+ function governorDependentDirection(gov, dep) {
1631
+ const govStress = gov.relativeStress;
1632
+ const depStress = dep.relativeStress;
1633
+ // Promote governor (if possible)
1634
+ if (govStress === 'n')
1635
+ gov.relativeStress = 'm';
1636
+ else if (govStress === 'm')
1637
+ gov.relativeStress = 's';
1638
+ // 'w' or 's' stay the same (can't promote 's', can't easily promote 'w' to 'n' without risking equal)
1639
+ // Demote dependent (if possible)
1640
+ if (depStress === 's')
1641
+ dep.relativeStress = 'm';
1642
+ else if (depStress === 'm')
1643
+ dep.relativeStress = 'n';
1644
+ else if (depStress === 'n')
1645
+ dep.relativeStress = 'w';
1646
+ else if (depStress === 'w')
1647
+ dep.relativeStress = 'x';
1648
+ }
1649
+ /** Simple adjustment for two adjacent syllables. */
1650
+ function adjustAdjacent(stronger, weaker, direction) {
1651
+ direction(stronger, weaker);
1652
+ }
1653
+ /** Demote a syllable's relative stress by one level: s→m, m→n, n→w, w→x, x stays x. */
1654
+ function demoteOneLevel(syl) {
1655
+ const cur = syl.relativeStress;
1656
+ if (cur === 's')
1657
+ syl.relativeStress = 'm';
1658
+ else if (cur === 'm')
1659
+ syl.relativeStress = 'n';
1660
+ else if (cur === 'n')
1661
+ syl.relativeStress = 'w';
1662
+ else if (cur === 'w')
1663
+ syl.relativeStress = 'x';
1664
+ }
1665
+ /**
1666
+ * Resolve stress clashes across prosodic boundaries (PP and IU).
1667
+ * When adjacent syllables at a boundary have equal stress:
1668
+ * - If one word is function and the other content, demote the function word
1669
+ * (per "beginnings free": the start of a new unit can be weakened)
1670
+ * - If both are same type, use dependency relationship
1671
+ * - If no relationship exists, leave untouched
1672
+ */
1673
+ function resolveCrossBoundaryClashes(words, ius) {
1674
+ // Build flat array with prosodic position tracking
1675
+ const flat = [];
1676
+ for (let iuIdx = 0; iuIdx < ius.length; iuIdx++) {
1677
+ const iu = ius[iuIdx];
1678
+ for (let ppIdx = 0; ppIdx < iu.phonologicalPhrases.length; ppIdx++) {
1679
+ const pp = iu.phonologicalPhrases[ppIdx];
1680
+ const ppWords = collectPPTokens(pp);
1681
+ for (const w of ppWords) {
1682
+ for (const s of w.syllables) {
1683
+ flat.push({ word: w, syl: s, ppKey: `${iuIdx}:${ppIdx}` });
1684
+ }
1685
+ }
1686
+ }
1687
+ }
1688
+ for (let i = 0; i < flat.length - 1; i++) {
1689
+ const a = flat[i];
1690
+ const b = flat[i + 1];
1691
+ if (a.syl.relativeStress !== b.syl.relativeStress)
1692
+ continue;
1693
+ // Only the stressed tier {n,m,s} clashes; {w,x} may repeat (maintainer's rule).
1694
+ const lvl = a.syl.relativeStress;
1695
+ if (lvl !== 'n' && lvl !== 'm' && lvl !== 's')
1696
+ continue;
1697
+ // Only adjust if they span a prosodic boundary
1698
+ if (a.ppKey === b.ppKey)
1699
+ continue;
1700
+ const aContent = a.word.isContent;
1701
+ const bContent = b.word.isContent;
1702
+ if (aContent && !bContent) {
1703
+ demoteOneLevel(b.syl);
1704
+ }
1705
+ else if (!aContent && bContent) {
1706
+ demoteOneLevel(a.syl);
1707
+ }
1708
+ else {
1709
+ // Both same content/function type — try dependency relationship.
1710
+ // (A blanket Selkirk "demote the PP-initial" was tried and regressed
1711
+ // litlab/prosodic: the linear-clash cascade's nuanced resolution — weight,
1712
+ // Rhythm Rule, governance — captures "beginnings loose" better than a flat
1713
+ // directional rule, so a clash with no governance is left for it.)
1714
+ const governor = getGovernor(a.word, b.word);
1715
+ if (governor === a.word) {
1716
+ adjustAdjacent(a.syl, b.syl, governorDependentDirection);
1717
+ }
1718
+ else if (governor === b.word) {
1719
+ adjustAdjacent(b.syl, a.syl, governorDependentDirection);
1720
+ }
1721
+ }
1722
+ }
1723
+ }
1724
+ /** Check whether a POS tag belongs to a content word category. */
1725
+ function isContentWord(tag, word) {
1726
+ if (CONTENT_POS.has(tag)) {
1727
+ if (word) {
1728
+ const lower = word.toLowerCase();
1729
+ if (FUNCTION_ADVERBS.has(lower))
1730
+ return false;
1731
+ if (FUNCTION_VERBS.has(lower))
1732
+ return false;
1733
+ }
1734
+ return true;
1735
+ }
1736
+ return false;
1737
+ }