Skip to content

feat(reader): TTS prosody v2a Phase C — Android Markdown narration segments - #647

Merged
github-actions[bot] merged 5 commits into
devfrom
feature/tts-v2a-android-markdown-segments
Aug 26, 2026
Merged

github-actions[bot] merged 5 commits into
devfrom
feature/tts-v2a-android-markdown-segments

Conversation

@libravault-pipeline-bot

@libravault-pipeline-bot libravault-pipeline-bot Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Closes #636.

What this adds

Part of #499's v2a phased breakdown. Mirrors iOS Phase A (#634, PR #640): same NarrationSegment shape, kept in sync across platforms, though Android's extraction stays line-oriented regex (matching MarkdownTtsTextExtractor's existing style) rather than an AST walk.

  • NarrationSegment.kt (core/tts) — the shared (text, kind, pauseBefore) type, plus joinToNarrationText() (fallback flattening for engines with no segment awareness, mirroring iOS's plainText).
  • MarkdownTtsTextExtractor.extractNarrationSegments — new function alongside (not replacing) stripMarkdownSyntax, reusing the same regexes to classify bold/italic → EMPHASIS, block quotes → QUOTE, headings → HEADING, list items → SENTENCE pause, paragraph breaks → PARAGRAPH pause, thematic breaks → SCENE_BREAK pause on the segment that follows (and the break line itself is dropped, same as stripMarkdownSyntax). Consecutive same-kind lines with no blank line between them (a soft-wrapped paragraph, a multi-line block quote) merge into one segment so pauseBefore == NONE segments never need an implicit separator.
  • TtsEngine.speak(segments: List<NarrationSegment>) — new default-implemented overload that flattens to plain text and calls speak(text). Pocket/Cloud engines get this for free, no regression, no new capability yet.
  • AndroidTtsEngine — the one real override. Converts segments into a List<PlaybackItem> (Speech | Silence), translating pauseBefore into a TextToSpeech.playSilentUtterance duration (150/500/900ms for Sentence/Paragraph/SceneBreak) spliced in ahead of each segment. This required generalizing the internal playback model from "one utterance chunk at a time via QUEUE_FLUSH + manual onDone-driven chaining" to enqueueing the whole remaining sequence upfront via QUEUE_ADD — a silence item has no "next chunk" to chain from other than Android's own queue. speak(text) now funnels through the same queue (as all-Speech, no silences), so pause/resume/stop/setSpeechRate only reason about one shape.

Scope note on the issue's own text

The issue says TextToSpeech.queueSilence(...). The real, documented Android API for this is TextToSpeech.playSilentUtterance(durationInMs, queueMode, utteranceId) (added API 21; this repo's minSdk is 31). Used the real method name — flagging the discrepancy here rather than silently "fixing" the issue text without comment.

Not done here (not asked for by this issue's own scope)

This issue's "What's needed" list (data model, extractor, TtsEngine overload, AndroidTtsEngine rendering) does not include wiring ReaderChapter/ReaderViewModel to actually call speak(segments) for the Markdown reader's mini-bar — unlike iOS Phase A's issue (#634), which explicitly listed AppState wiring as a numbered step. Read that omission as deliberate: ReaderChapter is a shared cross-format type also touched by the explicitly-separate Phase D (Android EPUB, #637), so wiring it now risks rework once that phase also wants segments. Flagging this explicitly rather than silently deciding to either add or skip that wiring on my own judgment — happy to do it here if a human disagrees and wants it in scope now.

Explicitly out of scope here (per issue)

Testing

  • New unit tests: MarkdownTtsTextExtractorTest (segment classification/merging/pauses), AndroidTtsEngineTest (buildPlaybackItems — the one piece of the rendering path reachable without a real android.speech.tts.TextToSpeech, same constraint as this file's existing splitIntoUtterances tests).
  • Fixed 4 pre-existing fakeTtsEngine.speak(any()) mockk calls in ReaderViewModelTest that became ambiguous once speak was overloaded — pinned to any<String>().
  • Full ./gradlew testDebugUnitTest --continue passes locally, including after rebasing onto dev's latest commit (fix(player): stop MediaController listener race from swallowing real playback failures (#642) #649, unrelated feature:player fix).

…erload

Kotlin counterpart of iOS's NarrationSegment (#634/#640), kept in sync in
shape. TtsEngine gets a default speak(segments) that flattens to plain
text and calls speak(text) — engines that aren't taught to render
segments yet (Pocket/Cloud) get this for free. Part of #636 (TTS v2a
Phase C: Android Markdown narration segments).
Adds extractNarrationSegments alongside (not replacing) stripMarkdownSyntax,
reusing the same regexes to classify bold/italic (Emphasis), block quotes
(Quote), headings (Heading), list items (Sentence pause), paragraph breaks
(Paragraph pause), and thematic breaks (SceneBreak pause on the segment
that follows) instead of discarding the classification.

Also fixes ReaderViewModelTest's `speak(any())` mockk calls, which became
ambiguous now that TtsEngine.speak is overloaded — pinned to any<String>().

Part of #636.
… chain

New speak(segments) override splices TextToSpeech.playSilentUtterance in
ahead of each segment per its pauseBefore hint, interleaved with the
segment's own (possibly split) text chunks. This required generalizing
the internal playback model from "one utterance chunk at a time" to a
List<PlaybackItem> (Speech | Silence) queue that's enqueued upfront via
QUEUE_ADD and replayed from the current index on resume/rate-change,
replacing the old QUEUE_FLUSH + manual onDone-driven chaining — a single
silence item has no "next chunk" to chain from other than the queue
itself, so the old one-at-a-time model doesn't generalize.

speak(text) now funnels through the same PlaybackItem queue (as
all-Speech, no silences), so pause/resume/stop/setSpeechRate only need to
reason about one shape.

Part of #636.
@github-actions
github-actions Bot marked this pull request as ready for review August 26, 2026 04:28
@github-actions github-actions Bot added the risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge label Aug 26, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-qa PR open, awaiting qa-agent verification label Aug 26, 2026
@claude

claude Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

QA verification — PR #647 vs issue #636

Acceptance criteria (issue #636 "What's needed")

  1. Shared NarrationSegment type (Kotlin counterpart of iOS's) — PASS. core/tts/.../NarrationSegment.kt matches the spec'd shape (text, kind: Kind{Plain,Emphasis,Quote,Heading}, pauseBefore: PauseHint{None,Sentence,Paragraph,SceneBreak}).
  2. stripMarkdownSyntax's classification kept instead of thrown away — PASS. MarkdownTtsTextExtractor.extractNarrationSegments (sibling function, as the issue explicitly allowed) reuses the same regexes and now classifies bold/italic→Emphasis, >→Quote, headings→Heading, list items→Sentence pause, blank line→Paragraph pause, thematic break→SceneBreak pause on the following segment.
  3. TtsEngine.speak(segments: List<NarrationSegment>) overload — PASS. Default-implemented, flattens via joinToNarrationText() and calls speak(text); Pocket/Cloud get it for free.
  4. AndroidTtsEngine renders segments via a documented pause primitive interleaved with speech — PASS, with a noted, well-justified deviation: the issue says TextToSpeech.queueSilence(...), which is not a real Android API; the PR uses the real one, TextToSpeech.playSilentUtterance(...), and calls this out explicitly in the PR description rather than silently reinterpreting the issue text. Chaining model was generalized from QUEUE_FLUSH+manual onDone chaining to an upfront QUEUE_ADD sequence, as required.

Explicitly-out-of-scope items (Android EPUB #637, iOS #634/635, Pocket rendering #638) are untouched — confirmed via the diff (only core/tts and feature/reader/.../markdown touched). The deliberate omission of ReaderViewModel/ReaderChapter wiring is reasonable and flagged by the PR itself; issue #636's own checklist doesn't ask for it (unlike iOS's #634).

Test suite run (real, foreground, this checkout)

  • ./gradlew testDebugUnitTest --continue (root): BUILD SUCCESSFUL in 10m 4s, 440 tasks. Note: the bare root invocation did not print/exercise :core:tts:testDebugUnitTest in its console output at all (a known task-name quirk this repo's own jvm-tests.yml comment documents for flavored modules — core:tts isn't flavored, so this is a separate anomaly worth someone looking at, not something I could root-cause in this pass). Because of that, I did not trust it as coverage for the core:tts changes and instead ran that module directly:
    • ./gradlew :core:tts:testDebugUnitTest --rerun --continue → BUILD SUCCESSFUL, AndroidTtsEngineTest: 20/20 passed, 0 failures (verified via the raw TEST-*.xml, not just the "BUILD SUCCESSFUL" line).
    • feature/reader's suite (from the root run): MarkdownTtsTextExtractorTest 24/24 passed, ReaderViewModelTest 73/73 passed (again read from the XML, not inferred).

Test quality (checking these exercise real code, not a mock past the broken part)

  • extractNarrationSegments and buildPlaybackItems tests call the real production functions directly with exact-value assertEquals on the returned NarrationSegment/PlaybackItem lists — no mocking involved, and they'd fail (fail to compile, even) on the pre-PR code since the functions are new. Confirmed this is real signal, not a relaxed-mock trivial-pass.
  • ReaderViewModelTest's 4 changed lines are exactly what the PR description claims (speak(any()) → speak(any<String>()) to disambiguate the new overload) — diffed against origin/dev to confirm no other behavioral change snuck in there.

Gap found — missing coverage (AGENTS.md violation)

NarrationSegment.kt:69 — List<NarrationSegment>.joinToNarrationText() has zero unit tests anywhere in the repo. This is non-trivial new logic (distinct handling for all four PauseHint values, plus an empty-builder edge case for the first segment) shipped in this PR, and it's not a side effect — it's the actual fallback rendering path TtsEngine.speak(segments)'s default implementation uses for every engine that doesn't override it (Pocket, Cloud — i.e., most of them). It's pure JVM logic with no Android dependency, so there's no cost-of-testing excuse (this repo's own AGENTS.md "Choosing a test type" table puts this squarely in the free/instant "Pure JVM" tier). AGENTS.md's "Required: always ship unit tests" section calls out exactly this case: "New behaviour — branch coverage for each new code path (success / failure / boundary)."

Not a blocker I'm raising: AndroidTtsEngine's actual enqueueFrom/onDone queue-chaining rewrite (the QUEUE_ADD generalization) has no direct test of its own, but this is a pre-existing architectural constraint (no real android.speech.tts.TextToSpeech on the JVM, per this same test file's own top-of-file comment) that predates this PR for the old chaining model too — not a new gap this PR introduced, and not practically fixable at the JVM-test level.

AGENTS.md conventions

  • Branch naming, commit hygiene, no hardcoded versions: all fine.
  • Coverage: fails the "ship tests for non-trivial new behaviour" bar on joinToNarrationText specifically (see above).

Verdict

One concrete, cheap-to-fix gap (a missing pure-JVM unit test for joinToNarrationText) is enough to fail this per this repo's own stated test policy, even though everything else — the acceptance criteria, the new segment/queue logic that IS tested, and the full test run — checks out.

QA verdict: FAIL

@github-actions github-actions Bot removed the status:needs-qa PR open, awaiting qa-agent verification label Aug 26, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:in-progress Dev agent is actively implementing label Aug 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor
QA failed its first round — routing back to the dev agent for one automated retry.

QA follow-up on PR #647 (issue #636): the pure-JVM fallback flattening
path TtsEngine.speak(segments)'s default implementation uses for every
engine without segment-aware rendering had zero test coverage. Covers
all four PauseHint branches, the first-segment empty-builder edge
case, and a mixed multi-segment join.
@github-actions

Copy link
Copy Markdown
Contributor

Fix for QA gap (round 2)

Addressed the one gap QA found: List<NarrationSegment>.joinToNarrationText() had zero unit test coverage.

  • Added core/tts/src/test/kotlin/xyz/libravault/core/tts/NarrationSegmentTest.kt — 10 pure-JVM unit tests covering all four PauseHint branches (NONE/SENTENCE/PARAGRAPH/SCENE_BREAK), the first-segment empty-builder edge case for each pause type, and a mixed multi-segment join to confirm ordering.
  • Verified via raw TEST-*.xml (not just "BUILD SUCCESSFUL"): NarrationSegmentTest 10/10 passed. Re-ran the full :core:tts:testDebugUnitTest module afterward — all 13 test classes pass, 0 failures/errors across the module.
  • dev moved by one commit since this branch was cut (43ed26b, a docs-only human-merge-sweep log append) — no overlap with this change, no rebase needed.

No other changes — scope stayed limited to the QA-reported gap.

@github-actions github-actions Bot removed the status:in-progress Dev agent is actively implementing label Aug 26, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-qa PR open, awaiting qa-agent verification label Aug 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

⏭️ iOS Simulator Build & Unit Tests - skipped
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

@claude

claude Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

QA verification — PR #647 vs. issue #636

Acceptance criteria (issue #636 "What's needed")

  1. Shared NarrationSegment type (Kotlin counterpart of iOS's, same shape) — PASS. core/tts/.../NarrationSegment.kt matches (text, kind: Kind, pauseBefore: PauseHint) with Kind {PLAIN, EMPHASIS, QUOTE, HEADING} and PauseHint {NONE, SENTENCE, PARAGRAPH, SCENE_BREAK}.
  2. stripMarkdownSyntax sibling emitting List<NarrationSegment>, reusing the same regex classification — PASS. MarkdownTtsTextExtractor.extractNarrationSegments reuses the existing heading/blockquote/list/thematic-break/emphasis regexes instead of discarding the match, added alongside (not replacing) stripMarkdownSyntax.
  3. TtsEngine.speak(segments: List<NarrationSegment>) overload — PASS. Default-implemented, flattens via joinToNarrationText() and calls speak(text). Confirmed Pocket/Cloud engines only override speak(text: String), so they pick up the default with no behavior change.
  4. AndroidTtsEngine renders segments via a documented silence primitive interleaved with speech — PASS, with a scope note the PR itself calls out: the issue says TextToSpeech.queueSilence(...), which does not exist on the real API; the PR uses TextToSpeech.playSilentUtterance(durationMs, queueMode, utteranceId) instead. I independently confirmed this is the correct real method (compilation against the real Android SDK stubs succeeded, which would fail if the method name were wrong) — this is a legitimate correction, not scope drift. The QUEUE_FLUSH-plus-manual-chaining model was generalized to a QUEUE_ADD-based List<PlaybackItem> queue, per the issue's own note about speakNext's chaining model needing to change.

Scope note (not a criterion, but worth confirming isn't silent scope-cutting): ReaderViewModel/ReaderChapter wiring to actually call speak(segments) from the mini-bar is not done here. I checked issue #636's own "What's needed" list — it only lists the 4 items above and does not mention view-model wiring (unlike iOS's #634, which explicitly listed AppState wiring). Confirmed via grep that speak(segments)/extractNarrationSegments have no production callers yet, only test callers — this matches what the PR description says outright, it isn't a hidden gap.

Tests run

./gradlew testDebugUnitTest --continue (full suite, foreground, ~10m12s): BUILD SUCCESSFUL, 440 actionable tasks, 0 failures.

Confirmed fresh (not stale-cached) execution of the relevant suites via test-result XML timestamps matching the run:

  • core:tts NarrationSegmentTest: 10/10 passed
  • core:tts AndroidTtsEngineTest: 20/20 passed (includes the new buildPlaybackItems segment/pause-translation cases)
  • feature:reader MarkdownTtsTextExtractorTest: 24/24 passed (includes the new extractNarrationSegments cases)
  • feature:reader ReaderViewModelTest: passed — the 4 speak(any()) → speak(any<String>()) mockk pins needed once speak was overloaded are the only change, no behavior change.

Test-quality check (this repo's known failure mode — tests mocking past the broken part): All the new/changed tests call the pure functions (extractNarrationSegments, buildPlaybackItems, joinToNarrationText) directly and assert exact equality against real output — no mocks involved, so a broken implementation cannot pass them. Spot-checked several (e.g. the blank-segment-keeps-its-pause case, the merge-consecutive-same-kind-lines case, the thematic-break-drops-itself-but-passes-the-pause-forward case) by tracing the implementation by hand; the assertions are precise enough that a regression in the logic would fail them.

One pre-existing, honestly-documented limitation carried forward unchanged by this PR: AndroidTtsEngineTest cannot construct a real android.speech.tts.TextToSpeech, so speak(segments)'s actual queuing/onDone chaining is untested end-to-end here — only the pure buildPlaybackItems translation is. This is the same constraint the pre-existing speak(text) path already had (undisturbed by this PR, not a new gap it introduces).

Regressions / related areas: Diffed AndroidTtsEngine.kt against the pre-PR parent commit — the QUEUE_FLUSH+onDone-chaining → QUEUE_ADD+batch-enqueue refactor is internally consistent (generation-guarded stale-callback rejection preserved, pause/resume/setSpeechRate all correctly route through the new enqueueFrom(currentItemIndex)). No other TtsEngine implementation needed changes. Full suite passing covers cross-module regressions.

AGENTS.md conventions: Tests present for all non-trivial new code paths, JUnit 5 + backtick names followed, no hardcoded versions, commits are Conventional-Commits-formatted and reasonably scoped (the ReaderViewModelTest mockk-ambiguity fix is bundled with the commit that caused it, which is the interface-overload's direct fallout, not a separate concern).

QA verdict: PASS

@github-actions github-actions Bot removed the status:needs-qa PR open, awaiting qa-agent verification label Aug 26, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-review QA passed, awaiting principal-review-agent label Aug 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Principal review — verdict: human-merge

Risk label: risk:high is current and correct. Re-ran classify_pr_risk.py origin/dev HEAD myself rather than trusting the label: diff is 602 changed lines, over the 400-line auto-merge threshold — pure diff-size trigger, no sensitive_paths match (confirmed by hand against the changed-file list too). No commits landed after the label was last set, so no re-classification was needed, but I did it anyway as a sanity check. This alone forces human-merge regardless of review findings, per policy.

No CONFIRMED findings. Routing to a human purely for the risk:high diff-size gate, not because anything here needs to change — posting as a plain comment rather than --request-changes accordingly.

Verification performed (ground truth, not just reading the diff/description):

  • Read the full diff for all 8 changed files, not a summary.
  • Ran ./gradlew :core:tts:testDebugUnitTest :feature:reader:testDebugUnitTest --continue locally against this branch → BUILD SUCCESSFUL. Independently cross-checked against this PR's own CI: the Unit & Integration Tests (JVM) check on the latest commit (efdf14f) passed in 10m1s — the PR's "tests pass" claim is corroborated two ways, not just taken on faith.
  • Grepped for extractNarrationSegments / speak(segments / NarrationSegment usage outside core/tts and feature/reader's own new code — confirmed it's genuinely unwired into ReaderViewModel/the mini-bar, matching the PR description's explicit claim that this is intentionally out of scope for this issue. No user-visible behavior change to Markdown Read Aloud ships from this PR.
  • Hand-traced MarkdownTtsTextExtractor.extractNarrationSegments's pendingPause/block-merge state machine against the 7 new extractor tests plus a few cases not explicitly covered (list item immediately after a blank line — correctly keeps PARAGRAPH rather than downgrading to SENTENCE, since the pendingPause == NONE guard on the list-item branch skips the override; consecutive quote lines with inline bold — correctly stay one merged QUOTE segment since isQuote outranks hasEmphasis in the kind when). No defect found.
  • Hand-traced AndroidTtsEngine's playback-queue rewrite (single QUEUE_FLUSH + onDone-chained chunk → upfront QUEUE_ADD of the whole PlaybackItem queue) for the generation-guard/index-tracking correctness across speak/pause/resume/setSpeechRate/stop. No correctness bug found — the generation bump ordering relative to engine.stop() in pause()/setSpeechRate() correctly invalidates stale callbacks the same way the pre-existing single-chunk model did.

One thing worth a closer look before merging, not a defect: this refactor changes the already-live speak(text) path (every existing Read Aloud call funnels through the new speakItems/enqueueFrom queue now, not just the new-and-still-unwired speak(segments) overload). AndroidTtsEngineTest's own pre-existing header comment establishes that speak()/resume()/pause() can't be exercised against a real TextToSpeech on the JVM — that constraint predates this PR, but more of the class's real logic now lives behind it (index-based onDone completion tracking, "re-enqueue everything from currentItemIndex" on resume/rate-change). Given risk:high already means a human is looking at this, I'd suggest an emulator/device smoke test of Read Aloud pause → resume and rate-change mid-chapter before merging, since nothing short of that can currently catch a regression here.

Policy checks: no new networking dependency/call; no .github/agent-policy.yml sensitive_paths touched; AGENTS.md test conventions followed (backtick-named tests, colocated with the code under test, non-trivial changes covered — including a same-PR QA follow-up commit adding coverage for joinToNarrationText()); no status:blocked on the PR or its linked issue (#636).

@github-actions github-actions Bot added status:needs-human-merge Principal review done, requires human merge decision and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 26, 2026
@github-actions
github-actions Bot merged commit f5e61dd into dev Aug 26, 2026
20 checks passed
@github-actions
github-actions Bot deleted the feature/tts-v2a-android-markdown-segments branch August 26, 2026 08:52
github-actions Bot added a commit that referenced this pull request Aug 26, 2026
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge status:needs-human-merge Principal review done, requires human merge decision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TTS v2a Phase C: Android Markdown narration segments

0 participants