calliope-ts 0.0.1

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 (50) hide show
  1. package/.claude/settings.local.json +8 -0
  2. package/.opencode/skills/calliope-ts/SKILL.md +74 -0
  3. package/LICENSE +201 -0
  4. package/README.md +485 -0
  5. package/dist/depfix.d.ts +13 -0
  6. package/dist/depfix.d.ts.map +1 -0
  7. package/dist/depfix.js +84 -0
  8. package/dist/display.d.ts +38 -0
  9. package/dist/display.d.ts.map +1 -0
  10. package/dist/display.js +890 -0
  11. package/dist/index.d.ts +50 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +504 -0
  14. package/dist/parser.d.ts +10 -0
  15. package/dist/parser.d.ts.map +1 -0
  16. package/dist/parser.js +688 -0
  17. package/dist/phonological.d.ts +41 -0
  18. package/dist/phonological.d.ts.map +1 -0
  19. package/dist/phonological.js +788 -0
  20. package/dist/rhyme.d.ts +26 -0
  21. package/dist/rhyme.d.ts.map +1 -0
  22. package/dist/rhyme.js +340 -0
  23. package/dist/scandroid.d.ts +17 -0
  24. package/dist/scandroid.d.ts.map +1 -0
  25. package/dist/scandroid.js +435 -0
  26. package/dist/scansion.d.ts +37 -0
  27. package/dist/scansion.d.ts.map +1 -0
  28. package/dist/scansion.js +1007 -0
  29. package/dist/scansion_debug.js +586 -0
  30. package/dist/stress.d.ts +32 -0
  31. package/dist/stress.d.ts.map +1 -0
  32. package/dist/stress.js +1372 -0
  33. package/dist/tagfix.d.ts +6 -0
  34. package/dist/tagfix.d.ts.map +1 -0
  35. package/dist/tagfix.js +101 -0
  36. package/dist/types.d.ts +173 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +4 -0
  39. package/package.json +62 -0
  40. package/src/depfix.ts +88 -0
  41. package/src/display.ts +954 -0
  42. package/src/index.ts +541 -0
  43. package/src/parser.ts +837 -0
  44. package/src/phonological.ts +849 -0
  45. package/src/rhyme.ts +328 -0
  46. package/src/scandroid.ts +434 -0
  47. package/src/scansion.ts +1053 -0
  48. package/src/stress.ts +1381 -0
  49. package/src/tagfix.ts +104 -0
  50. package/src/types.ts +230 -0
package/dist/stress.js ADDED
@@ -0,0 +1,1372 @@
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
+ // ─── CONSTANTS & CLASSIFICATIONS ──────────────────────────────────
8
+ /**
9
+ * Content‑word POS tags (nouns, adjectives, lexical verbs, adverbs).
10
+ * Excludes:
11
+ * - determiners (including demonstratives) – function words
12
+ * - possessive pronouns (PRP$) – function words
13
+ * - Wh‑words (WDT, WP, WP$, WRB) – function words
14
+ * - prepositions, conjunctions, particles, etc.
15
+ */
16
+ const CONTENT_POS = new Set([
17
+ 'NN', 'NNS', 'NNP', 'NNPS', // nouns
18
+ 'JJ', 'JJR', 'JJS', // adjectives
19
+ 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', // lexical verbs (excludes modals MD)
20
+ 'RB', 'RBR', 'RBS', // adverbs
21
+ 'CD', // cardinal numbers (content-like)
22
+ 'PDT', // predeterminers / quantifiers ("all", "both", "half") — carry quantificational stress
23
+ 'RP', // phrasal-verb particles ("coming IN", "take OFF") — they bear the phrasal stress
24
+ ]);
25
+ /**
26
+ * Spatial words that act as phrasal-verb PARTICLES (stress-bearing: "coming IN",
27
+ * "moving ON", "give UP") as opposed to prepositions ("in the house" → reduced).
28
+ * The parser usually tags a true particle `RP` (handled by CONTENT_POS above),
29
+ * but often mis-tags it `IN`/`RB` with an adverbial/particle dependency on the
30
+ * verb — `isPhrasalParticle` recovers those. A genuine preposition keeps a
31
+ * `prep`/`pobj` dependency on a NOUN and is (correctly) left as a function word.
32
+ */
33
+ const PARTICLE_LEMMAS = new Set([
34
+ 'in', 'on', 'out', 'off', 'up', 'down', 'over', 'away', 'back',
35
+ 'along', 'around', 'about', 'through', 'apart', 'aside', 'forth', 'together',
36
+ ]);
37
+ /** A phrasal-verb particle the parser tagged IN/RB (not RP): stress-bearing. */
38
+ function isPhrasalParticle(word) {
39
+ if (word.lexicalClass === 'RP')
40
+ return true;
41
+ const dep = word.dependency?.dependentType;
42
+ return PARTICLE_LEMMAS.has(word.word.toLowerCase())
43
+ && (dep === 'prt' || dep === 'advmod');
44
+ }
45
+ /** Demonstratives that, used pronominally (not determining a following noun),
46
+ * are a stressed focus: "What's THAT?", "Give me THIS." */
47
+ const DEMONSTRATIVE_LEMMAS = new Set(['that', 'this', 'these', 'those']);
48
+ /**
49
+ * A demonstrative used as a *pronoun* (the clause-final focus), rather than as a
50
+ * determiner of a following noun. The parser often tags focus "that" as `IN`
51
+ * (complementizer) and it then reduces to `x` — but "What's THAT?" puts the
52
+ * sentence's prominence on it. Detected as a demonstrative lemma that is the
53
+ * last non-punctuation word of the line (so "Is THAT grass" — a determiner — is
54
+ * untouched).
55
+ */
56
+ function isFocusDemonstrative(words, wi) {
57
+ if (!DEMONSTRATIVE_LEMMAS.has(words[wi].word.toLowerCase()))
58
+ return false;
59
+ for (let k = wi + 1; k < words.length; k++) {
60
+ if (!isPunctuation(words[k].lexicalClass))
61
+ return false; // a word follows → determiner use
62
+ }
63
+ return true;
64
+ }
65
+ /**
66
+ * Clitic POS categories: function words that are *proclitic* — prepositions /
67
+ * subordinators (IN), infinitival "to" (TO), possessive determiners (PRP$) and
68
+ * wh-determiners/possessives/adverbs (WDT/WP$/WRB). A
69
+ * *monosyllabic* word in one of these classes is reduced in running speech
70
+ * (Selkirk's clitic; McAleese's "beginnings free") and should floor at 'w'
71
+ * (overt-weak, *promotable*), never 'n'. Leaving a CMU-primary monosyllable
72
+ * like "on"/"my"/"where"/"from" at 'n' produced flat function-word runs (Pound's
73
+ * "So on my" = n·n·n, "where strange" = n·n).
74
+ *
75
+ * Deliberately EXCLUDES:
76
+ * - modals (MD: "shall"/"might") and personal pronouns (PRP: "I"/"thee"/"you")
77
+ * — they carry real stress (the clause-final beat in "…fast as you MIGHT").
78
+ * - determiners (DT) entirely. The quantificational / negative / demonstrative
79
+ * ones ("no one", "all verse", "this", "each") carry stress (cf. the
80
+ * maintainer's PDT-as-content rule); and flooring even the pure articles
81
+ * a/an tips Tarlinskaja's razor-thin iambic↔anapestic line ("…else a
82
+ * laugher's license", margin 0.009) into a wrong meter. "the" already reads
83
+ * 'x' via its CMU-0 stress, so determiners need no extra handling here.
84
+ * - coordinators (CC: and/but/or). "and" already reads 'x' (CMU-0); flooring
85
+ * "but"→w fires earlier than its baseline path and ripples to suppress an
86
+ * adjacent pronoun's clash-promotion, tipping Tarlinskaja's razor-thin
87
+ * iambic↔anapestic line — and coordinators bear no part of the n-run problem.
88
+ * Polysyllabic function words are also untouched, so their internal contour is
89
+ * preserved (be·NEATH = x·n, un·der·NEATH = x·x·n).
90
+ */
91
+ // NB: deliberately NOT including DT/PRP/MD/WP here. Monosyllabic pronouns,
92
+ // determiners, and modals at 'n' are PROMOTABLE into metrical beats — which
93
+ // real iambic verse exploits constantly ("but HE gave NO one ELSE",
94
+ // "fast as you MIGHT"). Flooring them to 'w' was tried (2026-06-12) and
95
+ // flipped the Mandelstam anapest and the Tarlinskaja iambic: reverted.
96
+ const CLITIC_POS = new Set(['IN', 'TO', 'PRP$', 'WDT', 'WP$', 'WRB']);
97
+ /** A reducible monosyllabic proclitic (see CLITIC_POS). */
98
+ function isMonosyllabicClitic(word) {
99
+ return !word.isContent
100
+ && word.syllables.length === 1
101
+ && CLITIC_POS.has(word.lexicalClass);
102
+ }
103
+ /**
104
+ * Temporal, locative, and discourse adverbs that behave as function words
105
+ * in verse — they typically occupy weak metrical positions and should not
106
+ * receive the primary-stress treatment of content adverbs.
107
+ */
108
+ const FUNCTION_ADVERBS = new Set([
109
+ 'then', 'so', 'here', 'there', 'where', 'when', 'why', 'how',
110
+ 'thus', 'hence', 'thence', 'whence',
111
+ 'now', 'ago', 'afterwards', 'afterward', 'beforehand',
112
+ 'meanwhile', 'nevertheless', 'nonetheless', 'however',
113
+ 'therefore', 'furthermore', 'moreover',
114
+ 'besides', 'instead', 'rather',
115
+ 'quite', 'almost', 'nearly', 'just', 'only',
116
+ 'even', 'also', 'too', 'very', 'indeed',
117
+ 'already', 'yet', 'still', 'again', 'ever', 'never',
118
+ 'always', 'often', 'sometimes', 'usually',
119
+ 'today', 'tomorrow', 'yesterday', 'tonight',
120
+ ]);
121
+ /**
122
+ * Oblique (object/dative) pronouns. In clause-final position these are
123
+ * canonically unstressed and do NOT attract the beat ("…and beHIND me", not
124
+ * "…and behind ME"), unlike a clause-final modal or content word. Used to keep
125
+ * the "endings strict" upbeat rule from promoting a final object pronoun.
126
+ */
127
+ const OBLIQUE_PRONOUNS = new Set([
128
+ 'me', 'him', 'her', 'us', 'them', 'thee', 'ye',
129
+ ]);
130
+ /**
131
+ * Subject-pronoun contractions (pronoun + auxiliary). These are a known data
132
+ * anomaly: FinNLP mis-tags the line-initial "I"-forms as FW, and nounsing records
133
+ * "i'm" with stress 0 while its sibling "i'll" gets 1 — so "I'm" sank to 'x'
134
+ * (Zero-Provision) whereas "I'll" read 'n'. A contracted subject pronoun is an
135
+ * overt syllable, never a maximally-reduced clitic, so a dictionary-zero one is
136
+ * restamped to its siblings' weak stress (below). This is a TARGETED fix for that
137
+ * specific inconsistency — it does NOT change how clitics, prepositions, articles,
138
+ * or bare pronouns floor (those keep their broad 'x'/contour behaviour).
139
+ */
140
+ const PRONOUN_SUBJECT_CONTRACTIONS = new Set([
141
+ "i'm", "i'll", "i've", "i'd",
142
+ "you're", "you'll", "you've", "you'd",
143
+ "he'll", "he'd", "she'll", "she'd", "it'll",
144
+ "we're", "we'll", "we've", "we'd",
145
+ "they're", "they'll", "they've", "they'd",
146
+ ]);
147
+ /**
148
+ * Poetic aphaeresis / clipping forms (apostrophe-stripped, lowercased) of
149
+ * function words — prepositions and adverbs. These are OOV, so without special
150
+ * handling they default to a *stressed content* reading (the parser tags
151
+ * "'neath" as NNP → primary stress!). Only applied when an apostrophe is
152
+ * actually present (so a literal "mid"/"side"/"cross" is left alone).
153
+ */
154
+ const APHAERESIS_CLITICS = new Set([
155
+ 'neath', // beneath
156
+ 'gainst', // against
157
+ 'twixt', // betwixt
158
+ 'mid', // amid
159
+ 'midst', // amidst
160
+ 'mongst', // amongst
161
+ 'tween', // between
162
+ 'pon', // upon
163
+ 'oer', // o'er = over
164
+ 'neer', // ne'er = never
165
+ 'eer', // e'er = ever
166
+ 'tis', // 'tis = it is (apostrophe-guarded, so a literal "tis" is untouched)
167
+ 'twas', // 'twas = it was
168
+ 'twere', // 'twere = it were
169
+ 'twill', // 'twill = it will (guard protects the fabric "twill")
170
+ ]);
171
+ /**
172
+ * Augmented-CMU data anomalies: for a couple of very common monosyllables the
173
+ * dictionary's ONLY profile is the letter-name spelling pronunciation of an
174
+ * abbreviation homograph — "am" → "EY1 EH1 M" (= A.M.), "us" → "Y UW1 EH1 S"
175
+ * (= U.S.) — inflating the syllable count of any line containing them. We
176
+ * restore the ordinary CMU citation form (AE1 M / AH1 S: one heavy syllable,
177
+ * citation stress 1) before the dictionary is consulted.
178
+ */
179
+ const ANOMALOUS_MONOSYLLABLES = {
180
+ am: { syllab: '(AE m)' },
181
+ us: { syllab: '(AH s)' },
182
+ // "a" = letter-name "EY1" in the augmented dictionary; the article is the
183
+ // canonical Zero-Provision clitic (schwa, open syllable) → stress 0, light.
184
+ a: { syllab: '(AH)', stress: 0, weight: 'L' },
185
+ };
186
+ /**
187
+ * Copula, auxiliary, aspectual, and light verbs that act as function words
188
+ * in verse — they do not carry the main semantic or prosodic weight of a phrase
189
+ * and should not be treated as content words for stress rules.
190
+ */
191
+ const FUNCTION_VERBS = new Set([
192
+ 'be', 'am', 'is', 'are', 'was', 'were', 'been', 'being',
193
+ 'have', 'has', 'had', 'having',
194
+ 'do', 'does', 'did', 'done', 'doing',
195
+ 'get', 'gets', 'got', 'getting', 'gotten',
196
+ 'start', 'starts', 'started', 'starting',
197
+ 'begin', 'begins', 'began', 'beginning', 'begun',
198
+ 'keep', 'keeps', 'kept', 'keeping',
199
+ 'stop', 'stops', 'stopped', 'stopping',
200
+ 'continue', 'continues', 'continued', 'continuing',
201
+ 'let', 'lets', "let's"
202
+ ]);
203
+ /** Left‑stressed compound categories with example first‑word lists. */
204
+ const LEFT_STRESS_MATERIAL = new Set([
205
+ 'metal', 'wood', 'silk', 'cotton', 'glass', 'stone', 'iron', 'steel',
206
+ 'paper', 'plastic', 'gold', 'silver'
207
+ ]);
208
+ const LEFT_STRESS_TIME = new Set([
209
+ 'morning', 'evening', 'summer', 'winter', 'spring', 'autumn',
210
+ 'christmas', 'easter', 'night', 'day'
211
+ ]);
212
+ const LEFT_STRESS_MEASURE = new Set(['pint', 'dollar', 'foot', 'mile']);
213
+ const LEFT_STRESS_LOCATION = new Set([
214
+ 'city', 'mountain', 'river', 'street', 'valley', 'island',
215
+ 'town', 'village', 'country'
216
+ ]);
217
+ const LEFT_STRESS_SELF = new Set(['self']);
218
+ // "Discard / ruin / spectral" noun-modifiers (N1) that reliably forestress as
219
+ // compounds: WASTE·land, SCRAP·yard, JUNK·yard, GHOST·town, DEAD·line,
220
+ // DUST·bowl, GRAVE·yard, BONE·yard, DEATH·bed. (Eliot's "WASTE shore".)
221
+ const LEFT_STRESS_DISCARD = new Set([
222
+ 'waste', 'scrap', 'junk', 'ghost', 'dead', 'dust', 'grave', 'bone',
223
+ 'death', 'trash', 'garbage', 'ash', 'blood', 'rust', 'wreck',
224
+ ]);
225
+ // Elemental / landscape noun-modifiers (N1) that reliably forestress:
226
+ // SEA·shore, MOON·light, STORM·cloud, WIND·mill, FIRE·place, SALT·marsh,
227
+ // FROST·bite, SAND·bar, SNOW·flake, TIDE·water, SHADOW·land.
228
+ const LEFT_STRESS_ELEMENTAL = new Set([
229
+ 'sea', 'moon', 'sun', 'star', 'storm', 'wind', 'fire', 'rain', 'snow',
230
+ 'ice', 'tide', 'wave', 'frost', 'mist', 'fog', 'mud', 'sand', 'salt',
231
+ 'earth', 'sky', 'dawn', 'dusk', 'shadow', 'flame', 'ember', 'smoke',
232
+ 'cloud', 'water', 'dew', 'hail', 'marsh', 'moor', 'flood', 'foam',
233
+ ]);
234
+ // Fire / light-source N1 modifiers that forestress like the elemental set:
235
+ // TORCH·light, CANDLE·light, LAMP·light, LANTERN·light, BEACON·fire,
236
+ // HEARTH·stone, COAL·fire, GAS·light — and Pound's hyphenated TORCH·flames
237
+ // (parallel to WASTE·shore; "flames" is the head, "torch" the modifier).
238
+ const LEFT_STRESS_FIRELIGHT = new Set([
239
+ 'torch', 'candle', 'lamp', 'lantern', 'beacon', 'hearth', 'coal', 'gas',
240
+ ]);
241
+ // Vehicle / conveyance N1 modifiers that forestress: SLEIGH·bells/blades,
242
+ // CART·wheel, WAGON·train, CAR·door, TRAIN·station, BOAT·house, TROLLEY·tickets.
243
+ // (Endocentric N+N where N1 is the conveyance the N2 belongs to / is part of.)
244
+ const LEFT_STRESS_VEHICLE = new Set([
245
+ 'sleigh', 'sled', 'cart', 'wagon', 'carriage', 'coach', 'train', 'tram',
246
+ 'trolley', 'car', 'boat', 'ship', 'plane', 'truck', 'bus', 'bike', 'bicycle',
247
+ ]);
248
+ // Head nouns (N2) that keep phrasal/right stress even after a forestress
249
+ // modifier — chiefly food "made of N1" and a few lexical exceptions:
250
+ // apple PIE, summer DAY, Fifth AVenue. These carve-outs keep the rule honest
251
+ // (a wrong forestress would mis-teach learners), so they OVERRIDE the N1 sets.
252
+ const RIGHT_STRESS_HEADS = new Set([
253
+ 'pie', 'cake', 'tart', 'pudding', 'mousse', 'soup', 'salad', 'sauce',
254
+ 'juice', 'avenue', 'day',
255
+ ]);
256
+ /** Check if a pair of words forms a left‑stressed compound. */
257
+ function isLeftStressedPair(w1, w2) {
258
+ const first = w1.toLowerCase();
259
+ const second = w2.toLowerCase().replace(/'s$/, '');
260
+ // A right-stressing head overrides any forestress modifier (apple PIE).
261
+ if (RIGHT_STRESS_HEADS.has(second))
262
+ return false;
263
+ if (LEFT_STRESS_MATERIAL.has(first))
264
+ return true;
265
+ if (LEFT_STRESS_TIME.has(first))
266
+ return true;
267
+ if (LEFT_STRESS_MEASURE.has(first))
268
+ return true;
269
+ if (LEFT_STRESS_LOCATION.has(first))
270
+ return true;
271
+ if (LEFT_STRESS_SELF.has(first))
272
+ return true;
273
+ if (LEFT_STRESS_DISCARD.has(first))
274
+ return true;
275
+ if (LEFT_STRESS_ELEMENTAL.has(first))
276
+ return true;
277
+ if (LEFT_STRESS_FIRELIGHT.has(first))
278
+ return true;
279
+ if (LEFT_STRESS_VEHICLE.has(first))
280
+ return true;
281
+ return false;
282
+ }
283
+ /**
284
+ * Lexicalised forestress COLLOCATIONS — fixed two-word phrases that stress the
285
+ * LEFT element, even though the second word is not a noun (so the N+N/J+N
286
+ * Compound Stress Rule does not reach them). "GOOD old days/friend";
287
+ * "the be-all and END-all". Each entry's optional guard suppresses spurious
288
+ * firing (e.g. "End ALL the wars" — the *verb* "end" + quantifier "all the
289
+ * wars" — must NOT forestress; there "all" is a predeterminer PDT).
290
+ */
291
+ const LEFT_STRESS_COLLOCATIONS = [
292
+ { w1: 'good', w2: 'old' }, // GOOD old days
293
+ { w1: 'end', w2: 'all', ok: w => w.lexicalClass !== 'PDT' }, // END-all (idiom), not "end ALL the wars"
294
+ ];
295
+ /** True if (w1,w2) is a lexicalised forestress collocation in this context. */
296
+ function isLeftStressedCollocation(w1, w2) {
297
+ const b1 = w1.word.toLowerCase().replace(/[^a-z]/g, '');
298
+ const b2 = w2.word.toLowerCase().replace(/[^a-z]/g, '');
299
+ for (const c of LEFT_STRESS_COLLOCATIONS) {
300
+ if (b1 === c.w1 && b2 === c.w2 && (!c.ok || c.ok(w2)))
301
+ return true;
302
+ }
303
+ return false;
304
+ }
305
+ // ─── LEXICAL STRESS (pronouncingjs) ───────────────────────────────
306
+ const VOWEL_CHARS = new Set('aeiouyAEIOUY');
307
+ /** Archaic/locative pronominal compounds whose first element ends in a MEDIAL
308
+ * silent 'e' ("where·fore", "there·in"): the plain vowel-group count reads the
309
+ * 'e' as a nucleus and over-counts. Count the parts instead. */
310
+ const SILENT_E_COMPOUND_RE = /^(where|there|here)(fore|in|by|of|on|upon|at|to|with|out|after|under|unto|abouts?|soever)$/;
311
+ function countVowelGroups(word) {
312
+ {
313
+ const m = word.toLowerCase().replace(/[^a-z]/g, '').match(SILENT_E_COMPOUND_RE);
314
+ // Closed-class second elements; counted directly ("fore" would otherwise
315
+ // read 2 — the small-word guard blocks the final-silent-e deduction).
316
+ if (m)
317
+ return 1 + (m[2] === 'soever' ? 3
318
+ : /^(upon|after|under|unto|about)/.test(m[2]) ? 2 : 1);
319
+ }
320
+ const lower = word.toLowerCase().replace(/-/g, '').replace(/'s/g, '').replace(/'/g, '');
321
+ const n = lower.length;
322
+ let groups = 0;
323
+ let inVowel = false;
324
+ const vowelPositions = [];
325
+ for (let i = 0; i < n; i++) {
326
+ if (VOWEL_CHARS.has(lower[i])) {
327
+ if (!inVowel) {
328
+ groups++;
329
+ vowelPositions.push(i);
330
+ inVowel = true;
331
+ }
332
+ }
333
+ else {
334
+ inVowel = false;
335
+ }
336
+ }
337
+ if (groups >= 3 && n > 2 && lower[n - 1] === 'e' && VOWEL_CHARS.has(lower[n - 1])) {
338
+ const lastVowelStart = vowelPositions[vowelPositions.length - 1];
339
+ if (lastVowelStart === n - 1) {
340
+ groups--;
341
+ }
342
+ }
343
+ return groups;
344
+ }
345
+ // ─── OUT-OF-VOCABULARY STRESS (two-tier fallback) ─────────────────
346
+ //
347
+ // When a word is absent from the augmented CMU dictionary, the old fallback
348
+ // blindly forestressed it (primary on syllable 0). That mis-stresses the most
349
+ // common OOV case — *inflected/derived forms of common words* whose base IS in
350
+ // the lexicon ("voyaging" OOV, "voyage" present) — and many true OOV words too
351
+ // ("anfractuous" → AN·fractuous rather than an·FRAC·tuous). We replace it with:
352
+ // (1) MORPHOLOGICAL decomposition — strip a stress-neutral productive suffix,
353
+ // reconstruct the stem's orthography, look it up, and reuse the stem's
354
+ // *real* lexical stress (the suffix syllables are unstressed).
355
+ // (2) the English Stress Rule (quantity-sensitive) for the genuine residual
356
+ // (names, neologisms) with no recognisable stem.
357
+ // Both run ONLY in the OOV branch, so in-vocabulary scansion is untouched.
358
+ /** Strip one trailing doubled consonant (run·ning → run, stop·ped → stop). */
359
+ function deDouble(b) {
360
+ const m = b.match(/([^aeiou])\1$/i);
361
+ return m ? b.slice(0, -1) : b;
362
+ }
363
+ /** True if a stem ends in a sibilant/affricate, so a following -s/-es is its own
364
+ * syllable (kiss·es, box·es, voy·a·ges) rather than a bare coda (cats). */
365
+ function isSibilantEnd(s) {
366
+ return /(s|z|x|sh|ch|ce|ge|se|ze|dge|tch)$/i.test(s);
367
+ }
368
+ /**
369
+ * Stress-neutral productive suffixes (Hayes: these do not shift the stem's
370
+ * stress). `stems(base)` lists candidate stem spellings to try (order = most
371
+ * likely first); `added(stem)` is how many *syllables* the suffix contributes.
372
+ * Stress-SHIFTING suffixes (-ion/-ity/-ic/-ial/-ious/-ify…) are deliberately
373
+ * omitted — treating them as neutral would mis-place the peak; they fall through
374
+ * to the English Stress Rule (and are common enough to usually be in-lexicon).
375
+ */
376
+ const SUFFIX_RULES = [
377
+ { suffix: 'iness', stems: b => [b + 'y'], added: () => 1 }, // happi·ness ← happy
378
+ { suffix: 'ily', stems: b => [b + 'y'], added: () => 1 }, // happi·ly ← happy
379
+ { suffix: 'ies', stems: b => [b + 'y'], added: () => 0 }, // car·ries ← carry
380
+ { suffix: 'ied', stems: b => [b + 'y'], added: () => 0 }, // car·ried ← carry
381
+ { suffix: 'ness', stems: b => [b], added: () => 1 },
382
+ { suffix: 'ment', stems: b => [b], added: () => 1 },
383
+ { suffix: 'less', stems: b => [b], added: () => 1 },
384
+ { suffix: 'ful', stems: b => [b], added: () => 1 },
385
+ { suffix: 'ings', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 },
386
+ { suffix: 'ing', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 }, // voy·a·ging ← voyage
387
+ { suffix: 'est', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 },
388
+ { suffix: 'ed', stems: b => [b + 'e', b, deDouble(b)], added: stem => /[td]$/.test(stem) ? 1 : 0 },
389
+ { suffix: 'eth', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 }, // archaic 3sg: go·eth, fall·eth, mak·eth
390
+ { suffix: 'ith', stems: b => [b + 'y', b + 'e', b], added: () => 1 }, // archaic 3sg of -y verbs: sa·ith ← say
391
+ { suffix: 'er', stems: b => [b + 'e', b, deDouble(b)], added: () => 1 },
392
+ { suffix: 'ly', stems: b => [b], added: () => 1 }, // soft·ly ← soft
393
+ { suffix: 'es', stems: b => [b, b + 'e'], added: stem => isSibilantEnd(stem) ? 1 : 0 },
394
+ { suffix: 's', stems: b => [b, b + 'e'], added: stem => isSibilantEnd(stem) ? 1 : 0 },
395
+ ];
396
+ /**
397
+ * Tier 1 — derive an OOV word's numeric stress (2=primary, 1=secondary, 0=none)
398
+ * by stripping a stress-neutral suffix and reusing the in-lexicon stem's stress.
399
+ * Returns null if no productive suffix yields a known stem.
400
+ */
401
+ function morphologicalStress(w) {
402
+ for (const rule of SUFFIX_RULES) {
403
+ if (!w.endsWith(rule.suffix))
404
+ continue;
405
+ const base = w.slice(0, w.length - rule.suffix.length);
406
+ if (base.length < 2)
407
+ continue; // guard tiny stems (sing → s+ing)
408
+ for (const stem of rule.stems(base)) {
409
+ if (stem.length < 2)
410
+ continue;
411
+ const data = nounsing.all(stem);
412
+ const raw = data && data.length ? (data[0].stress?.stressTrans || '') : '';
413
+ if (!raw)
414
+ continue;
415
+ const stemNumeric = [...raw].map(c => mapCMUStress(parseInt(c, 10)));
416
+ if (stemNumeric.length === 0)
417
+ continue;
418
+ const added = rule.added(stem);
419
+ return { pattern: [...stemNumeric, ...new Array(added).fill(0)], suffix: added >= 1 ? rule.suffix : '' };
420
+ }
421
+ }
422
+ return null;
423
+ }
424
+ /** Archaic verbal suffixes whose orthographic peel cleanly separates a silent-
425
+ * consonant stem from the suffix for DISPLAY (know·est not kno·west). Other
426
+ * suffixes keep the default orthographic syllabifier (it handles them well). */
427
+ const DISPLAY_PEEL_SUFFIXES = new Set(['est', 'eth', 'ith']);
428
+ /** Heavy syllable (orthographic estimate): long vowel (digraph/VCe) or closed
429
+ * by a coda consonant. Light = open with a single short vowel. */
430
+ function syllableIsHeavy(syl) {
431
+ const s = syl.toLowerCase();
432
+ if (/[aeiouy]{2}/.test(s))
433
+ return true; // vowel digraph / diphthong → long
434
+ if (/[aeiou][^aeiouy]e$/.test(s))
435
+ return true; // V·C·e → long ("ate", "ime")
436
+ if (/[^aeiouy]$/.test(s))
437
+ return true; // closed syllable (coda present)
438
+ return false;
439
+ }
440
+ /**
441
+ * Pre-stressing derivational suffixes (Hayes' "pre-stress 1/2"): they fix the
442
+ * primary on a syllable counted from the word's end (`offset` = syllables back,
443
+ * so primary index = n − offset). -ic/-tion fix the penult (offset 2),
444
+ * -ity/-graphy/-ical fix the antepenult (offset 3). Longest-match-first
445
+ * (enforced by the length sort below).
446
+ *
447
+ * The 2026-06-10 batch was DERIVED from the augmented CMU data itself
448
+ * (nounsing's `suffixType` shift classes cross-checked against the `mainStress`
449
+ * column over 3+-syllable words; every adopted ending ≥ 0.90 purity, most ≥ 0.96,
450
+ * N ≥ 60). This includes onomastic endings (-ski/-sky/-son/-berg/-gton …) that
451
+ * matter for OOV proper names — frequent in translation work. `-ary` is
452
+ * preantepenult and only fires on 4+-syllable words (the n ≥ offset guard),
453
+ * so BI-na-ry / ca-NA-ry style 3-syllable words fall through safely.
454
+ * NOTE: vowel-hiatus suffixes (-ion/-ial/-ious) can be undercounted by the
455
+ * orthographic syllable counter, so those stay approximate (documented limit).
456
+ */
457
+ const PRESTRESS_SUFFIXES = [
458
+ // hand-curated originals (Hayes)
459
+ { suffix: 'graphy', offset: 3 }, { suffix: 'ically', offset: 4 },
460
+ { suffix: 'ation', offset: 2 }, { suffix: 'ition', offset: 2 },
461
+ { suffix: 'itude', offset: 3 }, { suffix: 'ical', offset: 3 },
462
+ { suffix: 'logy', offset: 3 }, { suffix: 'nomy', offset: 3 },
463
+ { suffix: 'cracy', offset: 3 }, { suffix: 'pathy', offset: 3 },
464
+ { suffix: 'meter', offset: 3 }, { suffix: 'tion', offset: 2 },
465
+ { suffix: 'sion', offset: 2 }, { suffix: 'ity', offset: 3 },
466
+ { suffix: 'ety', offset: 3 }, { suffix: 'ify', offset: 3 },
467
+ { suffix: 'ics', offset: 2 }, { suffix: 'ic', offset: 2 },
468
+ // data-derived 2026-06-10: final-stressing (ultShift)
469
+ { suffix: 'ette', offset: 1 }, { suffix: 'ese', offset: 1 },
470
+ { suffix: 'eer', offset: 1 }, { suffix: 'ique', offset: 1 },
471
+ // data-derived: penult-stressing
472
+ { suffix: 'ion', offset: 2 }, { suffix: 'sive', offset: 2 },
473
+ { suffix: 'lla', offset: 2 }, { suffix: 'llo', offset: 2 },
474
+ { suffix: 'lli', offset: 2 }, { suffix: 'tti', offset: 2 },
475
+ { suffix: 'ina', offset: 2 }, { suffix: 'ino', offset: 2 },
476
+ { suffix: 'ano', offset: 2 }, { suffix: 'ana', offset: 2 },
477
+ { suffix: 'ini', offset: 2 },
478
+ { suffix: 'ski', offset: 2 }, { suffix: 'sky', offset: 2 },
479
+ // data-derived: antepenult-stressing
480
+ { suffix: 'ate', offset: 3 }, { suffix: 'cal', offset: 3 },
481
+ { suffix: 'onal', offset: 3 }, { suffix: 'nger', offset: 3 },
482
+ { suffix: 'son', offset: 3 }, { suffix: 'man', offset: 3 },
483
+ { suffix: 'berg', offset: 3 }, { suffix: 'gton', offset: 3 },
484
+ // data-derived: preantepenult-stressing (4+ syllables only via the guard)
485
+ { suffix: 'ary', offset: 4 },
486
+ ].sort((a, b) => b.suffix.length - a.suffix.length);
487
+ /**
488
+ * Tier 2 — the English Stress Rule for genuine OOV (no recognisable stem).
489
+ * First honours a pre-stressing derivational suffix (terRIF·ic, ac·TIV·i·ty,
490
+ * pho·TOG·ra·phy). Otherwise it is quantity-sensitive with final-syllable
491
+ * extrametricality: monosyllables take primary; disyllables keep the English
492
+ * forestress default; for 3+ syllables the final is extrametrical and stress
493
+ * falls on a heavy penult, else the antepenult (Hayes 1982). This fixes e.g.
494
+ * an·FRAC·tuous / e·NIG·ma where blind forestress erred.
495
+ */
496
+ function englishStressRule(w, isContent) {
497
+ const n = countVowelGroups(w);
498
+ const primary = isContent ? 2 : 1;
499
+ if (n <= 1)
500
+ return [primary];
501
+ for (const { suffix, offset } of PRESTRESS_SUFFIXES) {
502
+ if (w.endsWith(suffix) && n >= offset) {
503
+ const pattern = new Array(n).fill(0);
504
+ pattern[n - offset] = primary;
505
+ return pattern;
506
+ }
507
+ }
508
+ if (n === 2)
509
+ return [primary, 0]; // English disyllabic default (trochaic)
510
+ const sylls = syllabifyWord(w, n);
511
+ const pattern = new Array(n).fill(0);
512
+ const penult = n - 2; // final (n-1) is extrametrical
513
+ const heavyPenult = sylls[penult] ? syllableIsHeavy(sylls[penult]) : true;
514
+ pattern[heavyPenult ? penult : Math.max(0, n - 3)] = primary;
515
+ return pattern;
516
+ }
517
+ /**
518
+ * Per-syllable heaviness from nounsing's `syllStruct` CV transcription
519
+ * ("L.CL.CLC": C = consonant, L = lax/short nucleus, T = tense/long nucleus).
520
+ * Heavy = tense nucleus OR closed syllable (a coda consonant after the nucleus).
521
+ * Returns undefined when the segment count doesn't match the syllable count, so
522
+ * callers fall back to the orthographic estimate.
523
+ */
524
+ function heavyFromSyllStruct(syllStruct, n) {
525
+ if (!syllStruct)
526
+ return undefined;
527
+ const segs = syllStruct.split('.');
528
+ if (segs.length !== n)
529
+ return undefined;
530
+ return segs.map(seg => {
531
+ const vi = seg.search(/[LT]/);
532
+ if (vi < 0)
533
+ return false;
534
+ return seg[vi] === 'T' || vi < seg.length - 1;
535
+ });
536
+ }
537
+ /**
538
+ * The syllable index that should bear the default stress of a polysyllabic word
539
+ * whose dictionary entry records NO stress at all (an all-zero pattern — the
540
+ * maximally-reduced citation form of a few function words, chiefly "into"=00).
541
+ * Every lexical word bears at least one stress, so we restore it: a pre-stressing
542
+ * suffix fixes the count-from-end syllable; otherwise the English forestress
543
+ * default for disyllables (IN-to, ON-to), and the quantity-sensitive penult/
544
+ * antepenult (Hayes) for longer words. Mirrors englishStressRule's placement.
545
+ * `heavyFlags` (real per-syllable quantity from nounsing's syllStruct) replaces
546
+ * the orthographic heaviness guess when the word is in-vocabulary.
547
+ */
548
+ function defaultStressIndex(word, n, heavyFlags) {
549
+ for (const { suffix, offset } of PRESTRESS_SUFFIXES) {
550
+ if (word.endsWith(suffix) && n >= offset)
551
+ return n - offset;
552
+ }
553
+ if (n <= 2)
554
+ return 0; // English disyllabic forestress default
555
+ const penult = n - 2; // final (n-1) extrametrical
556
+ const heavyPenult = heavyFlags
557
+ ? heavyFlags[penult]
558
+ : (() => { const sylls = syllabifyWord(word, n); return sylls[penult] ? syllableIsHeavy(sylls[penult]) : true; })();
559
+ return heavyPenult ? penult : Math.max(0, n - 3);
560
+ }
561
+ /**
562
+ * Map CMU stress (0=unstressed, 1=primary, 2=secondary) to
563
+ * McAleese's numeric scale: 0=unstressed, 1=secondary, 2=primary.
564
+ */
565
+ function mapCMUStress(cmuStress) {
566
+ if (cmuStress === 1)
567
+ return 2; // primary → 2
568
+ if (cmuStress === 2)
569
+ return 1; // secondary → 1
570
+ return 0; // unstressed → 0
571
+ }
572
+ /**
573
+ * Assign per‑syllable lexical stress to each word in a sentence.
574
+ *
575
+ * Uses the first CMU pronunciation. Function words have their
576
+ * primary stress downgraded to secondary (2 → 1).
577
+ */
578
+ export function assignLexicalStress(words) {
579
+ for (let wi = 0; wi < words.length; wi++) {
580
+ const word = words[wi];
581
+ if (isPunctuation(word.lexicalClass)) {
582
+ word.syllables = [];
583
+ continue;
584
+ }
585
+ // Explicitly assign 0 syllables to possessive/contraction clitic "'s"
586
+ if (word.word === "'s") {
587
+ word.syllables = [];
588
+ continue;
589
+ }
590
+ // Poetic aphaeresis clipping ('neath, o'er, 'gainst…) → treat as the reduced
591
+ // function word it stands for, instead of the OOV default (NNP → stressed).
592
+ // Guard on an actual apostrophe (split off as the prior token, or internal),
593
+ // so a literal "mid"/"side"/"cross" is untouched.
594
+ {
595
+ const bare = word.word.toLowerCase().replace(/['’]/g, '');
596
+ const hasApostrophe = /['’]/.test(word.word)
597
+ || (wi > 0 && (words[wi - 1].word === "'" || words[wi - 1].word === '’'));
598
+ if (hasApostrophe && APHAERESIS_CLITICS.has(bare)) {
599
+ word.isContent = false;
600
+ // One weak monosyllable; lexical 0 + function ⇒ maps to 'x' (reduced clitic).
601
+ word.syllables = [{ text: word.word, phones: '', stress: 0, lexicalStress: 0 }];
602
+ continue;
603
+ }
604
+ }
605
+ let lookupWord = word.word.toLowerCase();
606
+ // Letter-name dictionary anomalies ("am" = A.M., "us" = U.S.): stamp the
607
+ // ordinary citation monosyllable directly (see ANOMALOUS_MONOSYLLABLES).
608
+ {
609
+ const fix = ANOMALOUS_MONOSYLLABLES[lookupWord];
610
+ if (fix) {
611
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
612
+ word.isContent = isContent;
613
+ const numeric = fix.stress ?? (isContent ? 2 : 1); // citation primary; function words reduce to secondary
614
+ word.syllables = [{ text: word.word, phones: fix.syllab, weight: fix.weight ?? 'H', stress: numeric, lexicalStress: numeric }];
615
+ continue;
616
+ }
617
+ }
618
+ // Elided article fused to its host (th'expense, th'inconstant): "th'" is
619
+ // non-syllabic, so the HOST word's dictionary entry is the right source for
620
+ // stress and syllable count — otherwise the fused token goes OOV and takes
621
+ // the disyllabic forestress default (TH'EX-pense instead of th'ex-PENSE).
622
+ {
623
+ const m = lookupWord.match(/^th['’](.+)$/);
624
+ if (m && m[1].length >= 2)
625
+ lookupWord = m[1];
626
+ }
627
+ let allData = nounsing.all(lookupWord);
628
+ if (!allData && lookupWord.includes('-')) {
629
+ const noHyphen = lookupWord.replace(/-/g, '');
630
+ allData = nounsing.all(noHyphen);
631
+ }
632
+ if ((!allData || allData.length === 0) && lookupWord.includes('-')) {
633
+ const parts = lookupWord.split('-');
634
+ const partStresses = [];
635
+ const partWeights = [];
636
+ for (const part of parts) {
637
+ const partData = nounsing.all(part);
638
+ if (partData && partData.length > 0) {
639
+ partStresses.push(partData[0].stress.stressTrans || '');
640
+ partWeights.push(partData[0].weightPattern || '');
641
+ }
642
+ }
643
+ if (partStresses.length === parts.length && partStresses.every(s => s.length > 0)) {
644
+ const combinedStress = partStresses.join('');
645
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
646
+ word.isContent = isContent;
647
+ const syls = [];
648
+ for (let i = 0; i < combinedStress.length; i++) {
649
+ const cmu = parseInt(combinedStress[i], 10);
650
+ let numeric = mapCMUStress(cmu);
651
+ if (!isContent && numeric === 2)
652
+ numeric = 1;
653
+ syls.push({ text: word.word, phones: '', stress: numeric, lexicalStress: numeric });
654
+ }
655
+ word.syllables = syls;
656
+ continue;
657
+ }
658
+ }
659
+ if (!allData || allData.length === 0) {
660
+ const cleanWord = word.word.toLowerCase().replace(/-/g, '').replace(/['’]/g, '');
661
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
662
+ word.isContent = isContent;
663
+ // Tier 1: morphological stem (reuse real lexical stress); Tier 2: ESR.
664
+ const morph = morphologicalStress(cleanWord);
665
+ const pattern = morph ? morph.pattern : englishStressRule(cleanWord, isContent);
666
+ // Record an archaic verbal suffix so the display splits know·est, not kno·west.
667
+ if (morph && DISPLAY_PEEL_SUFFIXES.has(morph.suffix))
668
+ word.morphSuffix = morph.suffix;
669
+ const syls = pattern.map(numeric => {
670
+ // Mirror the in-vocab function-word reduction (primary → secondary).
671
+ const n = (!isContent && numeric === 2) ? 1 : numeric;
672
+ return { text: word.word, phones: '', stress: n, lexicalStress: n };
673
+ });
674
+ word.syllables = syls;
675
+ continue;
676
+ }
677
+ // For nouns with multiple pronunciations, prefer front‑stressed (noun form).
678
+ let profile = allData[0];
679
+ if (allData.length > 1 && word.lexicalClass.startsWith('N')) {
680
+ for (const p of allData) {
681
+ const stressStr = p.stress.stressTrans;
682
+ if (stressStr && stressStr.length > 0 && (stressStr[0] === '1' || stressStr[0] === '2')) {
683
+ profile = p;
684
+ break;
685
+ }
686
+ }
687
+ }
688
+ let rawStress = profile.stress.stressTrans || ''; // e.g., "010"
689
+ // The CMU syllabification is authoritative for the syllable count. The
690
+ // orthographic vowel-group count UNDER-counts vowel-hiatus / glide words
691
+ // (goo·ey, play·ers, be·ing each read as a single vowel run), so it must NOT
692
+ // truncate the dictionary's count — doing so collapsed those to one syllable.
693
+ // Only clamp when stressTrans is genuinely LONGER than the CMU
694
+ // syllabification (a rare data inconsistency).
695
+ const syllsMatch = (profile.phonology.syllabification || '').match(/\([^)]+\)/g) || [];
696
+ if (syllsMatch.length > 0 && rawStress.length > syllsMatch.length) {
697
+ rawStress = rawStress.slice(0, syllsMatch.length);
698
+ }
699
+ // Synaeresis (verse vowel-gliding): an UNSTRESSED open syllable ending in a
700
+ // high-front vowel (IY/IH), followed by an UNSTRESSED vowel-initial syllable,
701
+ // glides into one syllable in verse — As·syr·i·an → as·syr·yan, var·i·ous →
702
+ // var·yous, glor·i·ous → glor·yous. It does NOT fire on a stressed nucleus
703
+ // (be·ing, i·DE·a) or before a stressed vowel (cre·ATE), so those keep their
704
+ // full count. Distinct from the (removed) orthographic truncation: it merges
705
+ // only genuine glide pairs, leaving goo·ey / play·ers / po·et intact.
706
+ if (syllsMatch.length === rawStress.length && rawStress.length >= 2) {
707
+ const tokensOf = (s) => s.replace(/[()]/g, '').trim().split(/\s+/).filter(Boolean);
708
+ const mStress = [];
709
+ const mSylls = [];
710
+ for (let i = 0; i < rawStress.length; i++) {
711
+ const cur = tokensOf(syllsMatch[i]);
712
+ const last = cur[cur.length - 1] ?? '';
713
+ const next = i + 1 < rawStress.length ? tokensOf(syllsMatch[i + 1]) : [];
714
+ if (i + 1 < rawStress.length
715
+ && rawStress[i] === '0' && rawStress[i + 1] === '0'
716
+ && (last === 'IY' || last === 'IH')
717
+ && /^[AEIOU]/.test(next[0] ?? '')) {
718
+ mStress.push('0');
719
+ mSylls.push('(' + cur.concat(next).join(' ') + ')');
720
+ i++; // absorb the glided syllable
721
+ }
722
+ else {
723
+ mStress.push(rawStress[i]);
724
+ mSylls.push(syllsMatch[i]);
725
+ }
726
+ }
727
+ rawStress = mStress.join('');
728
+ syllsMatch.splice(0, syllsMatch.length, ...mSylls);
729
+ }
730
+ // All-zero CMU pattern on a polysyllabic word: restore the default stress.
731
+ // A handful of reduced function words (chiefly "into"=00) are recorded with
732
+ // NO stress at all, which left every syllable at 'x' (in·to = x·x) — both
733
+ // unlike careful usage (IN-to) and metrically inert. Every lexical word
734
+ // bears a stress, so we re-stamp a CMU primary on the default-stress syllable
735
+ // (forestress for disyllables); function-word demotion downstream turns this
736
+ // into a secondary, giving the natural IN-to contour. Only fires on the
737
+ // genuine all-zero artifact, so words that already carry a peak are untouched.
738
+ if (rawStress.length >= 2 && /^0+$/.test(rawStress)) {
739
+ const cw = word.word.toLowerCase().replace(/-/g, '').replace(/['’]/g, '');
740
+ const heavy = heavyFromSyllStruct(profile.phonology.syllStruct, rawStress.length);
741
+ const idx = defaultStressIndex(cw, rawStress.length, heavy);
742
+ rawStress = rawStress.split('').map((c, i) => (i === idx ? '1' : '0')).join('');
743
+ }
744
+ // Targeted fix for the "I'm" anomaly: a subject-pronoun contraction the
745
+ // dictionary records as fully unstressed ("i'm"=0, while "i'll"=1) is restamped
746
+ // to a weak (function) stress, so it reads like its siblings ('n') rather than
747
+ // sinking to Zero-Provision 'x'. Narrow by construction — only fires on a
748
+ // monosyllabic, genuinely all-zero pronoun contraction; everything else is
749
+ // left exactly as it was.
750
+ if (rawStress === '0' && PRONOUN_SUBJECT_CONTRACTIONS.has(lookupWord)) {
751
+ rawStress = '1';
752
+ }
753
+ const isContent = isContentWord(word.lexicalClass, word.word) || isPhrasalParticle(word) || isFocusDemonstrative(words, wi);
754
+ word.isContent = isContent;
755
+ const syllables = [];
756
+ const weightsArray = (profile.weightPattern || '').split(' ').filter(x => x === 'H' || x === 'L');
757
+ // Determine extrametricality classification for the final syllable.
758
+ // Uses Hayes (1980) constraints: only Light edge syllables, only noun final syllables,
759
+ // morphological s/z (plural/tense) markers, and derivational suffixes in adjectives.
760
+ const sClassifier = profile.S ?? '';
761
+ // Extrametricality is a property of nouns / derived adjectives. Key it off
762
+ // the word's actual sentence POS (from the parser), NOT nounsing's lexical
763
+ // pos — otherwise function words like the preposition "underneath" (which the
764
+ // CMU data may tag nominally) wrongly lose the stress on their final syllable.
765
+ const isNoun = word.lexicalClass.startsWith('N');
766
+ const isAdj = word.lexicalClass.startsWith('JJ');
767
+ const finalWeight = profile.weight.find(w => w.syllable === 'final')?.heaviness ?? '';
768
+ const nsylls = rawStress.length;
769
+ let extrametricalType = undefined;
770
+ if (nsylls >= 2) {
771
+ if ((sClassifier === 'S' || sClassifier === 'SCluster') && isNoun) {
772
+ extrametricalType = 'morphological';
773
+ }
774
+ else if (isNoun && finalWeight === 'L' && nsylls >= 3) {
775
+ extrametricalType = 'light_noun';
776
+ }
777
+ else if (isAdj && profile.morphology.suffix === 'suffix') {
778
+ extrametricalType = 'derivational';
779
+ }
780
+ }
781
+ const phonesTokens = profile.phonology.phones.split(' ');
782
+ let phoneIdx = 0;
783
+ for (let i = 0; i < rawStress.length; i++) {
784
+ const ch = rawStress[i];
785
+ const cmu = parseInt(ch, 10);
786
+ let numeric = mapCMUStress(cmu);
787
+ // Function words are reduced in running speech, but their INTERNAL stress
788
+ // contour must be preserved: demote the primary syllable to secondary AND
789
+ // the secondary syllables to none, so the lexical peak stays the peak.
790
+ // (Flattening primary→secondary alone would tie "un" and "neath" in
791
+ // "underneath", letting a later clash invert it to ÚN-der-neath.)
792
+ if (!isContent) {
793
+ if (numeric === 2)
794
+ numeric = 1;
795
+ else if (numeric === 1)
796
+ numeric = 0;
797
+ }
798
+ const wPatLen = weightsArray.length;
799
+ const rLen = rawStress.length;
800
+ const wIdx = wPatLen - (rLen - i);
801
+ const weight = wIdx >= 0 && wIdx < wPatLen ? weightsArray[wIdx] : 'L';
802
+ const sylTextMatch = syllsMatch[i];
803
+ const sylText = sylTextMatch ? sylTextMatch.replace(/[()]/g, '') : word.word;
804
+ const sylPhonesMatch = syllsMatch[i] || '';
805
+ const isLastSyl = i === rawStress.length - 1;
806
+ syllables.push({
807
+ text: sylText,
808
+ phones: sylPhonesMatch,
809
+ weight,
810
+ stress: numeric,
811
+ lexicalStress: numeric,
812
+ relativeStress: undefined,
813
+ extrametrical: isLastSyl ? extrametricalType : undefined,
814
+ });
815
+ }
816
+ if (extrametricalType) {
817
+ word.lexicalDetails = `extrametrical_${extrametricalType}`;
818
+ }
819
+ // A focus demonstrative ("What's THAT?", "Give me THIS.") carries PRIMARY
820
+ // stress; CMU lists the weak/reduced (complementizer) form, which would leave
821
+ // it merely 'n' after the nuclear boost. Force its peak to primary so the
822
+ // sentence's prominence lands on it.
823
+ if (isFocusDemonstrative(words, wi) && syllables.length > 0) {
824
+ const pk = syllables.reduce((a, b) => (b.stress >= a.stress ? b : a));
825
+ pk.stress = 2;
826
+ pk.lexicalStress = 2;
827
+ }
828
+ word.syllables = syllables;
829
+ }
830
+ }
831
+ // ─── COMPOUND STRESS RULE ─────────────────────────────────────────
832
+ /**
833
+ * Adjust stresses for nominal compounds.
834
+ *
835
+ * Right‑stressed by default: the second content word keeps primary (2),
836
+ * the first is reduced to secondary (1).
837
+ * Known left‑stressed compounds (material, time, measure, location, self)
838
+ * reverse the pattern.
839
+ */
840
+ export function applyCompoundStress(ius) {
841
+ for (const iu of ius) {
842
+ for (const pp of iu.phonologicalPhrases) {
843
+ const words = collectPPTokens(pp);
844
+ // We don't want compound stress applied between arbitrary words across a phrase!
845
+ // Only apply to ADJACENT content words!
846
+ const contentWords = words.filter(w => w.isContent);
847
+ for (let i = 0; i < contentWords.length - 1; i++) {
848
+ const w1 = contentWords[i];
849
+ const w2 = contentWords[i + 1];
850
+ // Wait, they must be adjacent in the sentence!
851
+ if (Math.abs(w1.absoluteIndex - w2.absoluteIndex) !== 1)
852
+ continue;
853
+ const pos1 = w1.lexicalClass;
854
+ const pos2 = w2.lexicalClass;
855
+ const isCompound = (pos2.startsWith('N') && (pos1.startsWith('N') || pos1.startsWith('J')));
856
+ if (!isCompound)
857
+ continue;
858
+ const leftStressed = isLeftStressedPair(w1.word, w2.word);
859
+ if (leftStressed) {
860
+ setPrimaryStress(w1, 2);
861
+ setPrimaryStress(w2, 1);
862
+ }
863
+ else {
864
+ setPrimaryStress(w1, 1);
865
+ setPrimaryStress(w2, 2);
866
+ }
867
+ }
868
+ }
869
+ }
870
+ }
871
+ /** Locate the syllable with the highest stress and set it to `value`. */
872
+ function setPrimaryStress(word, value) {
873
+ let maxIdx = -1;
874
+ let maxVal = -1;
875
+ for (let i = 0; i < word.syllables.length; i++) {
876
+ if (word.syllables[i].stress > maxVal) {
877
+ maxVal = word.syllables[i].stress;
878
+ maxIdx = i;
879
+ }
880
+ }
881
+ if (maxIdx >= 0) {
882
+ word.syllables[maxIdx].stress = value;
883
+ }
884
+ }
885
+ // ─── NUCLEAR STRESS RULE ──────────────────────────────────────────
886
+ /**
887
+ * Recursively assign higher stress to content words from right to left.
888
+ * Only the rightmost content word receives a boost (+1 above lexical primary).
889
+ * All other content words keep their lexical stress.
890
+ * This preserves lexical stress for meter detection while still indicating
891
+ * the nuclear accent for phonological phrasing.
892
+ */
893
+ export function applyNuclearStress(ius) {
894
+ for (const iu of ius) {
895
+ for (const pp of iu.phonologicalPhrases) {
896
+ const words = collectPPTokens(pp).sort((a, b) => a.index - b.index);
897
+ // Find the rightmost content word and boost its primary by 1 level.
898
+ for (let i = words.length - 1; i >= 0; i--) {
899
+ if (words[i].isContent) {
900
+ const word = words[i];
901
+ let maxIdx = -1;
902
+ let maxVal = -1;
903
+ for (let j = 0; j < word.syllables.length; j++) {
904
+ if (word.syllables[j].stress > maxVal) {
905
+ maxVal = word.syllables[j].stress;
906
+ maxIdx = j;
907
+ }
908
+ }
909
+ if (maxIdx >= 0) {
910
+ // Boost the rightmost content word's primary by 1.
911
+ word.syllables[maxIdx].stress = word.syllables[maxIdx].stress + 1;
912
+ }
913
+ break; // Only the rightmost content word gets boosted.
914
+ }
915
+ }
916
+ }
917
+ }
918
+ }
919
+ // ─── RELATIVE STRESS ASSIGNMENT (4‑LEVEL) ─────────────────────────
920
+ /**
921
+ * Convert numeric per‑syllable stress to McAleese’s symbolic levels
922
+ * (w, n, m, s) and resolve adjacent identical stresses using dependency
923
+ * information.
924
+ */
925
+ export function assignRelativeStresses(words, ius) {
926
+ // First pass: numeric → symbolic (0→w, 1→n, 2→m, 3+→s)
927
+ // Use lexicalStress (pre-nuclear) so nuclear stress doesn't corrupt meter detection.
928
+ for (const word of words) {
929
+ for (const syl of word.syllables) {
930
+ const val = syl.lexicalStress ?? syl.stress;
931
+ if (val === 0) {
932
+ // Zero-Provision (`x`) for a maximally-reduced clitic: a stressless
933
+ // syllable of a function word reads *below* a stressless content
934
+ // syllable (the/a/of/and… vs. the weak syllable of a content word).
935
+ // EXCEPTION: an aphaeresis clipping ('neath/o'er/'gainst…) is the
936
+ // *lexically-stressed* syllable of its base word surviving the clip — an
937
+ // overt syllable carrying real stress, merely reduced in context. `x`
938
+ // means extrametrical (Hayes' zero-provision), which it is NOT; so it
939
+ // floors at `w` (overt weak), promotable like any weak syllable.
940
+ const bare = word.word.toLowerCase().replace(/['’]/g, '');
941
+ // Function VERBS (copula/aux/aspectual: be/is/keeps/began…) and
942
+ // function ADVERBS (deictic/scalar: just/now/then/here/there…) floor
943
+ // at 'w', not 'x': both classes carry full, unreducible vowels —
944
+ // 'x' is for schwa-able clitics (the/a/of/and). At 'w' they remain
945
+ // Attridge-promotable, recovering e.g. the dactylic opening beat of
946
+ // "JUST for a riband to STICK in his coat" (Browning).
947
+ if (word.isContent || APHAERESIS_CLITICS.has(bare)
948
+ || FUNCTION_VERBS.has(bare) || FUNCTION_ADVERBS.has(bare)) {
949
+ syl.relativeStress = 'w';
950
+ }
951
+ else {
952
+ syl.relativeStress = 'x';
953
+ }
954
+ }
955
+ else if (val === 1) {
956
+ syl.relativeStress = 'n';
957
+ }
958
+ else if (val === 2) {
959
+ syl.relativeStress = 'm';
960
+ }
961
+ else {
962
+ syl.relativeStress = 's';
963
+ }
964
+ // Monosyllabic function clitic → floor at 'w' (overt-weak, promotable),
965
+ // never 'n'. A CMU-primary monosyllabic preposition/determiner/possessive/
966
+ // wh-word/coordinator is reduced in running speech; flooring it at 'n' is
967
+ // what produced the flat function-word runs ("So on my", "where strange").
968
+ // (Pure clitics the/a/of already read 'x' via the val===0 branch.)
969
+ if (syl.relativeStress === 'n' && isMonosyllabicClitic(word)) {
970
+ syl.relativeStress = 'w';
971
+ }
972
+ // Downgrade extrametrical syllables by one level. We do NOT push a weak
973
+ // syllable to 'x' here: 'x' (zero-provision) is reserved for maximally-
974
+ // reduced *clitics*, whereas a weak *content* syllable (e.g. the feminine
975
+ // ending "li·cense") stays 'w' per the maintainer's tier semantics.
976
+ if (syl.extrametrical === 'morphological') {
977
+ if (syl.relativeStress === 'n')
978
+ syl.relativeStress = 'w';
979
+ else if (syl.relativeStress === 'm')
980
+ syl.relativeStress = 'n';
981
+ else if (syl.relativeStress === 's')
982
+ syl.relativeStress = 'm';
983
+ }
984
+ }
985
+ }
986
+ // Apply nuclear stress boosts to relative stress.
987
+ // `syl.stress` may be higher than `syl.lexicalStress` after applyNuclearStress
988
+ // boosted the rightmost content word. Each level of increase promotes the
989
+ // relative stress by one tier: w→n, n→m, m→s.
990
+ for (const word of words) {
991
+ for (const syl of word.syllables) {
992
+ const base = syl.lexicalStress ?? 0;
993
+ const boost = syl.stress - base;
994
+ if (boost > 0) {
995
+ let current = syl.relativeStress ?? 'w';
996
+ for (let i = 0; i < boost; i++) {
997
+ if (current === 'x')
998
+ current = 'w';
999
+ else if (current === 'w')
1000
+ current = 'n';
1001
+ else if (current === 'n')
1002
+ current = 'm';
1003
+ else if (current === 'm')
1004
+ current = 's';
1005
+ }
1006
+ syl.relativeStress = current;
1007
+ }
1008
+ }
1009
+ }
1010
+ // Second pass: resolve adjacent identical stresses within each phonological phrase
1011
+ for (const iu of ius) {
1012
+ for (const pp of iu.phonologicalPhrases) {
1013
+ const ppWords = collectPPTokens(pp);
1014
+ resolveAdjacentClashes(ppWords);
1015
+ }
1016
+ }
1017
+ // Third pass: resolve clashes across prosodic boundaries (PP and IU).
1018
+ // McAleese: when two adjacent syllables at a prosodic boundary have equal stress
1019
+ // and one is a function word, demote the function word (beginnings-free principle).
1020
+ resolveCrossBoundaryClashes(words, ius);
1021
+ // Compound forestress (linear surface order): a left-stressed compound's
1022
+ // prominence sits on its LEFT element (WASTE·shore, SEA·shore, GHOST·town).
1023
+ // The phrasal compound/nuclear rules run in hierarchy order, which a mis-
1024
+ // grouped parse can split (e.g. "a cavernous waste shore" separating
1025
+ // waste/shore), so we re-assert forestress here on true surface adjacency,
1026
+ // after the clash passes, so it survives the rightmost-content nuclear boost.
1027
+ resolveCompoundForestress(words);
1028
+ resolveCollocationForestress(words);
1029
+ resolveHyphenCompounds(words);
1030
+ // Fourth pass: resolve clashes on the LINEAR SURFACE order. A stress clash is
1031
+ // a property of *contiguous pronounced* syllables (Hayes' "two contiguous
1032
+ // syllables"), i.e. surface order — but the phrasal passes above run in
1033
+ // hierarchy order, which a mis-grouped parse can scramble (e.g. "a cavernous
1034
+ // waste shore" leaving "waste"/"shore" non-adjacent in the tree though
1035
+ // contiguous in speech). Catch any residual cardinal s–s clash here.
1036
+ resolveLinearClashes(words);
1037
+ }
1038
+ /** Ascending rank of the 5 relative-stress tiers, for level arithmetic. */
1039
+ const STRESS_RANK = { x: 0, w: 1, n: 2, m: 3, s: 4 };
1040
+ const STRESS_LEVELS = ['x', 'w', 'n', 'm', 's'];
1041
+ /**
1042
+ * Re-assert left-stress on forestressed compounds over the LINEAR surface
1043
+ * sequence (e.g. WASTE·shore, SEA·shore, GHOST·town, STORM·cloud). For each
1044
+ * pair of truly-adjacent content words (by absoluteIndex) that the Compound
1045
+ * Stress Rule marks left-stressed, the left element's peak is raised to the
1046
+ * pair's maximum prominence and the right element's peak is demoted one rung
1047
+ * below it — never raising the subordinate. Runs on surface order so it works
1048
+ * even when the parse mis-groups the two into different phrases.
1049
+ */
1050
+ function resolveCompoundForestress(words) {
1051
+ const content = words.filter(w => w.isContent && !isPunctuation(w.lexicalClass));
1052
+ for (let i = 0; i < content.length - 1; i++) {
1053
+ const w1 = content[i];
1054
+ const w2 = content[i + 1];
1055
+ if (Math.abs(w1.absoluteIndex - w2.absoluteIndex) !== 1)
1056
+ continue; // truly adjacent
1057
+ const pos1 = w1.lexicalClass, pos2 = w2.lexicalClass;
1058
+ if (!(pos2.startsWith('N') && (pos1.startsWith('N') || pos1.startsWith('J'))))
1059
+ continue;
1060
+ if (!isLeftStressedPair(w1.word, w2.word))
1061
+ continue;
1062
+ const s1 = wordPeak(w1);
1063
+ const s2 = wordPeak(w2);
1064
+ if (!s1 || !s2)
1065
+ continue;
1066
+ const r1 = STRESS_RANK[s1.relativeStress ?? 'w'];
1067
+ const r2 = STRESS_RANK[s2.relativeStress ?? 'w'];
1068
+ const hi = Math.max(r1, r2);
1069
+ s1.relativeStress = STRESS_LEVELS[hi]; // head ≥ both
1070
+ s2.relativeStress = STRESS_LEVELS[Math.min(r2, Math.max(0, hi - 1))]; // demote-only
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Forestress lexicalised collocations (GOOD old, END-all) over the LINEAR
1075
+ * surface sequence. Unlike `resolveCompoundForestress` this iterates ALL words
1076
+ * (not just content), because a collocation's second element may be a function
1077
+ * word ("end ALL" — "all" is a determiner): raise the left element's peak to the
1078
+ * pair maximum and demote the right one rung (demote-only, never raises the
1079
+ * subordinate).
1080
+ */
1081
+ function resolveCollocationForestress(words) {
1082
+ const seq = words
1083
+ .filter(w => !isPunctuation(w.lexicalClass) && w.syllables.length > 0)
1084
+ .sort((a, b) => a.absoluteIndex - b.absoluteIndex);
1085
+ for (let i = 0; i < seq.length - 1; i++) {
1086
+ const w1 = seq[i];
1087
+ const w2 = seq[i + 1];
1088
+ if (w2.absoluteIndex - w1.absoluteIndex !== 1)
1089
+ continue; // truly adjacent
1090
+ if (!isLeftStressedCollocation(w1, w2))
1091
+ continue;
1092
+ const s1 = wordPeak(w1);
1093
+ const s2 = wordPeak(w2);
1094
+ if (!s1 || !s2)
1095
+ continue;
1096
+ const r1 = STRESS_RANK[s1.relativeStress ?? 'w'];
1097
+ const r2 = STRESS_RANK[s2.relativeStress ?? 'w'];
1098
+ const hi = Math.max(r1, r2);
1099
+ s1.relativeStress = STRESS_LEVELS[hi]; // left element ≥ both
1100
+ s2.relativeStress = STRESS_LEVELS[Math.min(r2, Math.max(0, hi - 1))]; // demote-only
1101
+ }
1102
+ }
1103
+ /**
1104
+ * Resolve the dual-strong clash at a hyphen seam inside a compound word
1105
+ * ("torch-flames", "blood-red"). The parser keeps a hyphenated compound as a
1106
+ * single token, so the word-level compound and clash passes never see its two
1107
+ * halves — left alone, both keep primary stress (s·s). For a hyphenated content
1108
+ * word whose hyphen parts align 1:1 with its syllables, an adjacent s·s seam is
1109
+ * resolved with the same logic as a two-word compound: forestress the left if it
1110
+ * is a known forestress modifier, otherwise retract the left (the nuclear /
1111
+ * right-stress default, e.g. torch-FLAMES).
1112
+ */
1113
+ function resolveHyphenCompounds(words) {
1114
+ for (const w of words) {
1115
+ if (!w.isContent || !w.word.includes('-'))
1116
+ continue;
1117
+ const parts = w.word.split('-').filter(p => p.length > 0);
1118
+ if (parts.length < 2 || parts.length !== w.syllables.length)
1119
+ continue;
1120
+ for (let i = 0; i < w.syllables.length - 1; i++) {
1121
+ const a = w.syllables[i];
1122
+ const b = w.syllables[i + 1];
1123
+ // An equal-strong seam (s·s or m·m) is the unresolved compound clash.
1124
+ const equalStrong = a.relativeStress === b.relativeStress
1125
+ && (a.relativeStress === 's' || a.relativeStress === 'm');
1126
+ if (equalStrong) {
1127
+ if (isLeftStressedPair(parts[i], parts[i + 1]))
1128
+ demoteOneLevel(b); // BLOOD-red
1129
+ else
1130
+ demoteOneLevel(a); // torch-FLAMES
1131
+ }
1132
+ }
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Resolve cardinal stress clashes on the linear surface sequence: two
1137
+ * *contiguous* syllables both at the strongest level ('s') with no weaker
1138
+ * syllable between them. Per McAleese/Hayes, retract the LEFT stress one level
1139
+ * (s→m), with within-word-peak protection so a polysyllable's own peak is never
1140
+ * demoted for an adjacent monosyllable (the monosyllable yields instead).
1141
+ *
1142
+ * Deliberately limited to s–s (the cardinal clash the methodology resolves
1143
+ * unconditionally): m–m and lower are often metrically meaningful (spondaic /
1144
+ * emphatic substitutions) and are left for the meter layer to weigh.
1145
+ */
1146
+ function resolveLinearClashes(words) {
1147
+ const flat = [];
1148
+ for (const w of words)
1149
+ for (const s of w.syllables)
1150
+ flat.push({ word: w, syl: s });
1151
+ for (let i = 0; i < flat.length - 1; i++) {
1152
+ const a = flat[i];
1153
+ const b = flat[i + 1];
1154
+ if (a.syl.relativeStress !== 's' || b.syl.relativeStress !== 's')
1155
+ continue;
1156
+ if (a.word === b.word)
1157
+ continue; // intra-word clashes → silent beat downstream
1158
+ const aPeak = a.word.syllables.length > 1 && a.syl === wordPeak(a.word);
1159
+ const bPeak = b.word.syllables.length > 1 && b.syl === wordPeak(b.word);
1160
+ // Protect a polysyllable's peak: if only the left is a peak and the right is
1161
+ // a lone monosyllable, retract the monosyllable instead.
1162
+ if (aPeak && !bPeak && b.word.syllables.length === 1) {
1163
+ demoteOneLevel(b.syl);
1164
+ }
1165
+ else {
1166
+ demoteOneLevel(a.syl); // Hayes: retract the left stress
1167
+ }
1168
+ }
1169
+ }
1170
+ /**
1171
+ * Scan across the linear sequence of syllables and adjust any adjacent
1172
+ * identical relative stress levels using syntactic governance.
1173
+ */
1174
+ function resolveAdjacentClashes(words) {
1175
+ // "Endings strict": when a phrase ends in a run of two or more bare function
1176
+ // words (e.g. "…fast as you MIGHT"), the metrical beat gravitates to one of
1177
+ // them; the others are upbeat. Demote the others so a leftward governance
1178
+ // clash can't promote a medial off-beat ("you") over the phrase-final beat.
1179
+ // Phrases ending in a content word are untouched.
1180
+ {
1181
+ let runStart = words.length;
1182
+ while (runStart > 0 && !words[runStart - 1].isContent)
1183
+ runStart--;
1184
+ if (words.length - runStart >= 2) {
1185
+ // The beat is normally the run's last word, UNLESS that is a clause-final
1186
+ // oblique pronoun (me/him/them…), which is canonically unstressed — then
1187
+ // the beat falls on the preceding member ("and beHIND me", not "behind ME").
1188
+ let beatIdx = words.length - 1;
1189
+ if (OBLIQUE_PRONOUNS.has(words[beatIdx].word.toLowerCase()) && beatIdx > runStart) {
1190
+ beatIdx--;
1191
+ }
1192
+ for (let wi = runStart; wi < words.length; wi++) {
1193
+ if (wi === beatIdx)
1194
+ continue;
1195
+ const w = words[wi];
1196
+ const peak = wordPeak(w);
1197
+ for (const s of w.syllables) {
1198
+ // Protect a polysyllabic word's own lexical peak: never flatten a real
1199
+ // internal stress (be·HIND) to 'w' just because the word is functional.
1200
+ if (w.syllables.length > 1 && s === peak && (s.lexicalStress ?? s.stress) >= 1)
1201
+ continue;
1202
+ s.relativeStress = 'w';
1203
+ }
1204
+ }
1205
+ }
1206
+ }
1207
+ // Flatten all syllables with reference to their owning word.
1208
+ const flat = [];
1209
+ for (const w of words) {
1210
+ for (const s of w.syllables) {
1211
+ flat.push({ word: w, syl: s });
1212
+ }
1213
+ }
1214
+ for (let i = 0; i < flat.length - 1; i++) {
1215
+ const a = flat[i];
1216
+ const b = flat[i + 1];
1217
+ if (a.syl.relativeStress !== b.syl.relativeStress)
1218
+ continue;
1219
+ // Within-word strictness (Kiparsky): a polysyllabic word's own stress peak
1220
+ // must not be demoted below its word-mates by a clash with an adjacent
1221
+ // monosyllable. Protect the peak; demote the monosyllable instead.
1222
+ const aPeak = a.word.syllables.length > 1 && a.syl === wordPeak(a.word);
1223
+ const bPeak = b.word.syllables.length > 1 && b.syl === wordPeak(b.word);
1224
+ if (aPeak && b.word.syllables.length === 1) {
1225
+ adjustAdjacent(a.syl, b.syl, governorDependentDirection);
1226
+ continue;
1227
+ }
1228
+ if (bPeak && a.word.syllables.length === 1) {
1229
+ adjustAdjacent(b.syl, a.syl, governorDependentDirection);
1230
+ continue;
1231
+ }
1232
+ // Otherwise use the syntactic governor relationship.
1233
+ const governor = getGovernor(a.word, b.word);
1234
+ if (governor === a.word) {
1235
+ // a governs b → a stronger, b weaker
1236
+ adjustAdjacent(a.syl, b.syl, governorDependentDirection);
1237
+ }
1238
+ else if (governor === b.word) {
1239
+ // b governs a → b stronger, a weaker
1240
+ adjustAdjacent(b.syl, a.syl, governorDependentDirection);
1241
+ }
1242
+ // If no relationship, leave untouched.
1243
+ }
1244
+ }
1245
+ /** The syllable bearing a word's lexical stress peak (used for within-word protection). */
1246
+ function wordPeak(word) {
1247
+ let best;
1248
+ let bestVal = -Infinity;
1249
+ for (const s of word.syllables) {
1250
+ const v = s.lexicalStress ?? s.stress;
1251
+ if (v > bestVal) {
1252
+ bestVal = v;
1253
+ best = s;
1254
+ }
1255
+ }
1256
+ return best;
1257
+ }
1258
+ /** Return the governor word if one directly governs the other, else null. */
1259
+ function getGovernor(w1, w2) {
1260
+ const dep1 = w1.dependency;
1261
+ const dep2 = w2.dependency;
1262
+ if (!dep1 || !dep2)
1263
+ return null;
1264
+ // Check if w2 is a dependent of w1.
1265
+ if (dep2.governor === w1)
1266
+ return w1;
1267
+ // Check if w1 is a dependent of w2.
1268
+ if (dep1.governor === w2)
1269
+ return w2;
1270
+ return null;
1271
+ }
1272
+ /** Adjustment direction: governor stronger (promote), dependent weaker (demote). */
1273
+ function governorDependentDirection(gov, dep) {
1274
+ const govStress = gov.relativeStress;
1275
+ const depStress = dep.relativeStress;
1276
+ // Promote governor (if possible)
1277
+ if (govStress === 'n')
1278
+ gov.relativeStress = 'm';
1279
+ else if (govStress === 'm')
1280
+ gov.relativeStress = 's';
1281
+ // 'w' or 's' stay the same (can't promote 's', can't easily promote 'w' to 'n' without risking equal)
1282
+ // Demote dependent (if possible)
1283
+ if (depStress === 's')
1284
+ dep.relativeStress = 'm';
1285
+ else if (depStress === 'm')
1286
+ dep.relativeStress = 'n';
1287
+ else if (depStress === 'n')
1288
+ dep.relativeStress = 'w';
1289
+ else if (depStress === 'w')
1290
+ dep.relativeStress = 'x';
1291
+ }
1292
+ /** Simple adjustment for two adjacent syllables. */
1293
+ function adjustAdjacent(stronger, weaker, direction) {
1294
+ direction(stronger, weaker);
1295
+ }
1296
+ /** Demote a syllable's relative stress by one level: s→m, m→n, n→w, w→x, x stays x. */
1297
+ function demoteOneLevel(syl) {
1298
+ const cur = syl.relativeStress;
1299
+ if (cur === 's')
1300
+ syl.relativeStress = 'm';
1301
+ else if (cur === 'm')
1302
+ syl.relativeStress = 'n';
1303
+ else if (cur === 'n')
1304
+ syl.relativeStress = 'w';
1305
+ else if (cur === 'w')
1306
+ syl.relativeStress = 'x';
1307
+ }
1308
+ /**
1309
+ * Resolve stress clashes across prosodic boundaries (PP and IU).
1310
+ * When adjacent syllables at a boundary have equal stress:
1311
+ * - If one word is function and the other content, demote the function word
1312
+ * (per "beginnings free": the start of a new unit can be weakened)
1313
+ * - If both are same type, use dependency relationship
1314
+ * - If no relationship exists, leave untouched
1315
+ */
1316
+ function resolveCrossBoundaryClashes(words, ius) {
1317
+ // Build flat array with prosodic position tracking
1318
+ const flat = [];
1319
+ for (let iuIdx = 0; iuIdx < ius.length; iuIdx++) {
1320
+ const iu = ius[iuIdx];
1321
+ for (let ppIdx = 0; ppIdx < iu.phonologicalPhrases.length; ppIdx++) {
1322
+ const pp = iu.phonologicalPhrases[ppIdx];
1323
+ const ppWords = collectPPTokens(pp);
1324
+ for (const w of ppWords) {
1325
+ for (const s of w.syllables) {
1326
+ flat.push({ word: w, syl: s, ppKey: `${iuIdx}:${ppIdx}` });
1327
+ }
1328
+ }
1329
+ }
1330
+ }
1331
+ for (let i = 0; i < flat.length - 1; i++) {
1332
+ const a = flat[i];
1333
+ const b = flat[i + 1];
1334
+ if (a.syl.relativeStress !== b.syl.relativeStress)
1335
+ continue;
1336
+ // Only adjust if they span a prosodic boundary
1337
+ if (a.ppKey === b.ppKey)
1338
+ continue;
1339
+ const aContent = a.word.isContent;
1340
+ const bContent = b.word.isContent;
1341
+ if (aContent && !bContent) {
1342
+ demoteOneLevel(b.syl);
1343
+ }
1344
+ else if (!aContent && bContent) {
1345
+ demoteOneLevel(a.syl);
1346
+ }
1347
+ else {
1348
+ // Both same content/function type — try dependency relationship
1349
+ const governor = getGovernor(a.word, b.word);
1350
+ if (governor === a.word) {
1351
+ adjustAdjacent(a.syl, b.syl, governorDependentDirection);
1352
+ }
1353
+ else if (governor === b.word) {
1354
+ adjustAdjacent(b.syl, a.syl, governorDependentDirection);
1355
+ }
1356
+ }
1357
+ }
1358
+ }
1359
+ /** Check whether a POS tag belongs to a content word category. */
1360
+ function isContentWord(tag, word) {
1361
+ if (CONTENT_POS.has(tag)) {
1362
+ if (word) {
1363
+ const lower = word.toLowerCase();
1364
+ if (FUNCTION_ADVERBS.has(lower))
1365
+ return false;
1366
+ if (FUNCTION_VERBS.has(lower))
1367
+ return false;
1368
+ }
1369
+ return true;
1370
+ }
1371
+ return false;
1372
+ }