<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Harsh Verma</title>
<link>https://insightsurge-dev.web.app/blog.html</link>
<atom:link href="https://insightsurge-dev.web.app/blog.xml" rel="self" type="application/rss+xml"/>
<description>R, Shiny and R-package engineering for GxP pharma, and the R Engineering Playbook.</description>
<image>
<url>https://insightsurge-dev.web.app/images/social/default.png</url>
<title>Harsh Verma</title>
<link>https://insightsurge-dev.web.app/blog.html</link>
</image>
<generator>quarto-1.8.27</generator>
<lastBuildDate>Wed, 11 Nov 2026 18:30:00 GMT</lastBuildDate>
<item>
  <title>mascot is on CRAN: live, mood-driven mascots for Shiny and Quarto</title>
  <link>https://insightsurge-dev.web.app/posts/introducing-mascot/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="mascot-0.1.0-is-on-cran" class="level2">
<h2 class="anchored" data-anchor-id="mascot-0.1.0-is-on-cran">mascot 0.1.0 is on CRAN</h2>
<p>The <code>mascot</code> package is now on CRAN: a small animated character for Shiny apps and Quarto pages that tells your users what the app is doing. It is more than a face:</p>
<ul>
<li><strong>Moods and status text:</strong> five moods on every character, with a status line always shown beside the face, so a mood never carries meaning alone.</li>
<li><strong>Speech bubbles:</strong> short messages that close after a few seconds, or stay until the visitor closes them.</li>
<li><strong>Click actions and popup menus:</strong> a click can run an action or open a menu, and your Shiny server reads what was chosen.</li>
<li><strong>Floating or inline:</strong> pin a mascot to a corner of the page and let visitors minimise it, or place it in the layout.</li>
<li><strong>Four characters, your colours:</strong> 34 ready-made palettes, your own brand colours, and light and dark mode.</li>
<li><strong>Reduced motion:</strong> the browser’s <code>prefers-reduced-motion</code> setting is honoured.</li>
<li><strong>Shiny and Quarto:</strong> live mood changes from server code in Shiny, and the same characters in rendered Quarto pages.</li>
</ul>
<p>Install the released version directly from CRAN:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;">install.packages</span>(<span class="st" style="color: #20794D;">"mascot"</span>)</span></code></pre></div></div>
<p>Here is Tessa, the default mascot, reacting to actions in a small Shiny review workflow:</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/readme-demo.svg" class="lightbox" data-gallery="quarto-lightbox-gallery-1" title="A short animation: Tessa sits beside a small Shiny form. She is idle, then thinking while the rows are checked, worried when two dates need a look, and happy when they are fixed, with her status text beside her each time and the matching update_mascot() call below."><img src="https://insightsurge-dev.web.app/posts/introducing-mascot/readme-demo.svg" class="img-fluid figure-img" alt="A short animation: Tessa sits beside a small Shiny form. She is idle, then thinking while the rows are checked, worried when two dates need a look, and happy when they are fixed, with her status text beside her each time and the matching update_mascot() call below."></a></p>
<figcaption>A short animation: Tessa sits beside a small Shiny form. She is idle, then thinking while the rows are checked, worried when two dates need a look, and happy when they are fixed, with her status text beside her each time and the matching update_mascot() call below.</figcaption>
</figure>
</div>
<p>It is meant for apps where a user needs to see at a glance that something has changed.</p>
</section>
<section id="the-usual-approach-spinners-toasts-and-red-text" class="level2">
<h2 class="anchored" data-anchor-id="the-usual-approach-spinners-toasts-and-red-text">The usual approach: spinners, toasts, and red text</h2>
<p>Most Shiny applications reach for three conventional tools when communicating status:</p>
<ol type="1">
<li><strong>Spinners:</strong> A spinner signals that R is busy, but it communicates only binary activity: it cannot explain what is happening or whether a step completed normally. When computation finishes, the spinner vanishes without leaving confirmation.</li>
<li><strong>Toast notifications:</strong> Pop-up messages disappear on a timer (<code>shiny::showNotification()</code> closes after 5 seconds by default). If a user looks away, the notification expires unread.</li>
<li><strong>Red text alerts:</strong> Warning text conveys urgency, but it sits wherever the layout put it and says nothing when an operation succeeds. Colour alone also excludes people who do not see it the same way: the Web Content Accessibility Guidelines say colour must not be the only way to convey information.</li>
</ol>
<p>None of these tools provides a stable visual companion that conveys progress, snags, and completion within a consistent layout.</p>
</section>
<section id="the-r-way-mascots-with-moods-and-status" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-mascots-with-moods-and-status">The R way: mascots with moods and status</h2>
<p>The <code>mascot</code> package introduces a dedicated UI element paired with server-side updates. You place a character in your UI with <code>mascot()</code> and update its mood, status message, speech bubble or click menu from the server with <code>update_mascot()</code>.</p>
<p>Here is the smallest working Shiny application:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">library</span>(shiny)</span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">library</span>(mascot)</span>
<span id="cb2-3"></span>
<span id="cb2-4">ui <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">fluidPage</span>(</span>
<span id="cb2-5">  <span class="fu" style="color: #4758AB;">mascot</span>(</span>
<span id="cb2-6">    <span class="st" style="color: #20794D;">"helper"</span>,</span>
<span id="cb2-7">    <span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"idle"</span>,</span>
<span id="cb2-8">    <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"Ready to greet you"</span>,</span>
<span id="cb2-9">    <span class="at" style="color: #657422;">placement =</span> <span class="st" style="color: #20794D;">"inline"</span></span>
<span id="cb2-10">  ),</span>
<span id="cb2-11">  <span class="fu" style="color: #4758AB;">actionButton</span>(<span class="st" style="color: #20794D;">"greet"</span>, <span class="st" style="color: #20794D;">"Say hello"</span>)</span>
<span id="cb2-12">)</span>
<span id="cb2-13"></span>
<span id="cb2-14">server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb2-15">  <span class="fu" style="color: #4758AB;">observeEvent</span>(input<span class="sc" style="color: #5E5E5E;">$</span>greet, {</span>
<span id="cb2-16">    <span class="fu" style="color: #4758AB;">update_mascot</span>(<span class="st" style="color: #20794D;">"helper"</span>, <span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"happy"</span>, <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"Hello!"</span>)</span>
<span id="cb2-17">  })</span>
<span id="cb2-18">}</span>
<span id="cb2-19"></span>
<span id="cb2-20"><span class="fu" style="color: #4758AB;">shinyApp</span>(ui, server)</span></code></pre></div></div>
<section id="bubbles-menus-and-corners" class="level3">
<h3 class="anchored" data-anchor-id="bubbles-menus-and-corners">Bubbles, menus and corners</h3>
<p>A mascot can also talk and take clicks. This one sits in the bottom-right corner, can be minimised, shows a message until it is closed, and opens a menu when clicked. The server reads the chosen item from <code>input$helper_menu</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">ui <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">fluidPage</span>(</span>
<span id="cb3-2">  <span class="fu" style="color: #4758AB;">mascot</span>(</span>
<span id="cb3-3">    <span class="st" style="color: #20794D;">"helper"</span>,</span>
<span id="cb3-4">    <span class="at" style="color: #657422;">bubble =</span> <span class="fu" style="color: #4758AB;">mascot_bubble</span>(<span class="st" style="color: #20794D;">"Need a hand with the form?"</span>, <span class="at" style="color: #657422;">duration =</span> <span class="cn" style="color: #8f5902;">Inf</span>),</span>
<span id="cb3-5">    <span class="at" style="color: #657422;">placement =</span> <span class="fu" style="color: #4758AB;">mascot_placement</span>(<span class="st" style="color: #20794D;">"bottom-right"</span>, <span class="at" style="color: #657422;">minimise =</span> <span class="cn" style="color: #8f5902;">TRUE</span>),</span>
<span id="cb3-6">    <span class="at" style="color: #657422;">click =</span> <span class="fu" style="color: #4758AB;">mascot_popup_menu</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="at" style="color: #657422;">about =</span> <span class="st" style="color: #20794D;">"About this form"</span>, <span class="at" style="color: #657422;">reset =</span> <span class="st" style="color: #20794D;">"Start again"</span>))</span>
<span id="cb3-7">  )</span>
<span id="cb3-8">)</span>
<span id="cb3-9"></span>
<span id="cb3-10">server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb3-11">  <span class="fu" style="color: #4758AB;">observeEvent</span>(input<span class="sc" style="color: #5E5E5E;">$</span>helper_menu, {</span>
<span id="cb3-12">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (input<span class="sc" style="color: #5E5E5E;">$</span>helper_menu <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"reset"</span>) {</span>
<span id="cb3-13">      <span class="fu" style="color: #4758AB;">update_mascot</span>(<span class="st" style="color: #20794D;">"helper"</span>, <span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"idle"</span>, <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"Ready when you are"</span>)</span>
<span id="cb3-14">    }</span>
<span id="cb3-15">  })</span>
<span id="cb3-16">}</span></code></pre></div></div>
</section>
<section id="the-date-check-from-the-animation" class="level3">
<h3 class="anchored" data-anchor-id="the-date-check-from-the-animation">The date check from the animation</h3>
<p>The animation above is a small review form: paste visit dates, press <em>Check</em>, and Tessa reports what the check found. The app keeps the check and the mascot apart. A plain function counts the dates that need a look, and a second one turns that count into a mood and a status line:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">mascot_state <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(check) {</span>
<span id="cb4-2">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (check<span class="sc" style="color: #5E5E5E;">$</span>n_rows <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb4-3">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"idle"</span>, <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"Paste some dates to check"</span>))</span>
<span id="cb4-4">  }</span>
<span id="cb4-5">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (check<span class="sc" style="color: #5E5E5E;">$</span>n_bad <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb4-6">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"happy"</span>, <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"All checks passed"</span>))</span>
<span id="cb4-7">  }</span>
<span id="cb4-8">  status <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (check<span class="sc" style="color: #5E5E5E;">$</span>n_bad <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">1</span>L) {</span>
<span id="cb4-9">    <span class="st" style="color: #20794D;">"One date needs a look"</span></span>
<span id="cb4-10">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb4-11">    <span class="fu" style="color: #4758AB;">paste</span>(check<span class="sc" style="color: #5E5E5E;">$</span>n_bad, <span class="st" style="color: #20794D;">"dates need a look"</span>)</span>
<span id="cb4-12">  }</span>
<span id="cb4-13">  <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"worried"</span>, <span class="at" style="color: #657422;">status =</span> status)</span>
<span id="cb4-14">}</span></code></pre></div></div>
<p>The server then hands that state to the mascot. Because the state comes from a plain function, you can test it without a browser, and the status line is wording you can review:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;">observeEvent</span>(<span class="fu" style="color: #4758AB;">result</span>(), {</span>
<span id="cb5-2">  state <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">mascot_state</span>(<span class="fu" style="color: #4758AB;">result</span>())</span>
<span id="cb5-3">  mascot<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">update_mascot</span>(<span class="st" style="color: #20794D;">"reviewer"</span>, <span class="at" style="color: #657422;">mood =</span> state<span class="sc" style="color: #5E5E5E;">$</span>mood, <span class="at" style="color: #657422;">status =</span> state<span class="sc" style="color: #5E5E5E;">$</span>status)</span>
<span id="cb5-4">})</span></code></pre></div></div>
<p>The companion script at the end of this post holds the whole app and a <code>shiny::testServer()</code> check of it. If you give <code>update_mascot()</code> an argument it cannot use, it warns and leaves the mascot unchanged, so a test can use <code>expect_no_warning()</code> to catch that. It does not reject a mood name it has never heard of, so keep the moods your app uses in one place, as above.</p>
</section>
<section id="characters-5-moods-status-text" class="level3">
<h3 class="anchored" data-anchor-id="characters-5-moods-status-text">4 characters, 5 moods, status text</h3>
<p>All characters share five standard moods: <code>"idle"</code> (at rest), <code>"thinking"</code> (working on something), <code>"happy"</code> (something went well), <code>"worried"</code> (something needs attention) and <code>"celebrating"</code> (a big success). <code>mascot_moods()</code> lists them with their descriptions:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;">library</span>(mascot)</span>
<span id="cb6-2"></span>
<span id="cb6-3">moods <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">mascot_moods</span>()</span>
<span id="cb6-4">moods[, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"name"</span>, <span class="st" style="color: #20794D;">"description"</span>)]</span></code></pre></div></div>
<p>Here is every character in every mood, each with the status line it shows by default. This is not a screenshot: the chunk below ran when this page was rendered, and the mascots are drawn in your browser. It is also how you put mascots in a Quarto page, so it shows the capability and the Quarto integration at once.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;">library</span>(mascot)</span>
<span id="cb7-2"><span class="fu" style="color: #4758AB;">library</span>(htmltools)</span>
<span id="cb7-3"></span>
<span id="cb7-4">characters <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">mascot_characters</span>()</span>
<span id="cb7-5">moods <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">mascot_moods</span>()<span class="sc" style="color: #5E5E5E;">$</span>name</span>
<span id="cb7-6"></span>
<span id="cb7-7">cell <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(id, mood) {</span>
<span id="cb7-8">  <span class="fu" style="color: #4758AB;">mascot</span>(<span class="fu" style="color: #4758AB;">paste</span>(id, mood, <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">"-"</span>), <span class="at" style="color: #657422;">character =</span> id, <span class="at" style="color: #657422;">mood =</span> mood, <span class="at" style="color: #657422;">size =</span> <span class="dv" style="color: #AD0000;">100</span>, <span class="at" style="color: #657422;">placement =</span> <span class="st" style="color: #20794D;">"inline"</span>)</span>
<span id="cb7-9">}</span>
<span id="cb7-10">label <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(text) <span class="fu" style="color: #4758AB;">div</span>(<span class="at" style="color: #657422;">class =</span> <span class="st" style="color: #20794D;">"mascot-matrix-label"</span>, text)</span>
<span id="cb7-11"></span>
<span id="cb7-12">rows <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">lapply</span>(<span class="fu" style="color: #4758AB;">seq_len</span>(<span class="fu" style="color: #4758AB;">nrow</span>(characters)), <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(i) {</span>
<span id="cb7-13">  <span class="fu" style="color: #4758AB;">c</span>(<span class="fu" style="color: #4758AB;">list</span>(<span class="fu" style="color: #4758AB;">label</span>(characters<span class="sc" style="color: #5E5E5E;">$</span>name[i])), <span class="fu" style="color: #4758AB;">lapply</span>(moods, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(m) <span class="fu" style="color: #4758AB;">cell</span>(characters<span class="sc" style="color: #5E5E5E;">$</span>id[i], m)))</span>
<span id="cb7-14">})</span>
<span id="cb7-15"></span>
<span id="cb7-16"><span class="fu" style="color: #4758AB;">div</span>(</span>
<span id="cb7-17">  <span class="at" style="color: #657422;">class =</span> <span class="st" style="color: #20794D;">"mascot-matrix"</span>,</span>
<span id="cb7-18">  <span class="fu" style="color: #4758AB;">label</span>(<span class="st" style="color: #20794D;">""</span>), <span class="fu" style="color: #4758AB;">lapply</span>(moods, label),</span>
<span id="cb7-19">  <span class="fu" style="color: #4758AB;">unlist</span>(rows, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb7-20">)</span></code></pre></div></div>
<div class="cell-output-display">

</div>
</div>
<p>The mascots breathe and blink, and follow this page’s light and dark mode. In a Quarto document the mood and status text are fixed when the page is rendered, so there are no live server updates; changing the mood while someone watches needs Shiny. Today, embedding a mascot in Quarto takes an R code chunk like the one above. A dedicated Quarto shortcode is planned for version 0.2.0, so authors can insert characters directly in Markdown.</p>
<p>The rows are the four built-in characters:</p>
<ul>
<li><strong>Tessa (Hexonians, stable):</strong> The default character, a slim teal hexagon with a silver ring and a chest badge whose icon shows her mood. Her status lines sound like a sturdy workbench (“Working out how the parts fit”, “Finished, and built to last”), which suits tutorials and documentation.</li>
<li><strong>Sela (Hexonians, stable):</strong> A lilac hexagon with violet hair, flanked by time blocks that overlap during a clash and slide apart once it is sorted (“Direct schedule clash detected”). Suits schedules and bookings.</li>
<li><strong>Knurl (Visorfolk, experimental):</strong> A single-wheeled repair robot with a clamp arm and a screen visor. It keeps to clipped readouts (“Queue idle”, “Task repaired”), which suits queues and batch jobs.</li>
<li><strong>Neer (Elementals, experimental):</strong> A water character in blue tones with a shell, calm and observant. Her status lines are quiet (“Checking the inputs”, “Some fields need attention”), which suits form checks.</li>
</ul>
<p>The design enforces a core rule: <strong>status text is always displayed beside the character</strong>. The mascot wiggles briefly on mood changes to draw the user’s eye, but the visible text ensures the exact meaning is unambiguous.</p>
<p>For visitors who prefer reduced motion (<code>prefers-reduced-motion</code>), <code>mascot</code> honours that browser setting automatically: the wiggle animation is omitted, and the character transitions directly to its new expression. You can also turn off movement programmatically using <code>motion = FALSE</code> or configure motion timings with <code>mascot_motion_settings()</code>.</p>
</section>
</section>
<section id="try-it-before-you-use-it-the-studio" class="level2">
<h2 class="anchored" data-anchor-id="try-it-before-you-use-it-the-studio">Try it before you use it: the studio</h2>
<p>Before writing application code, you can explore every character, mood, and argument in the interactive mascot studio. The studio is experimental and relies on optional packages <code>bslib</code> (0.7.0 or later) and <code>knitr</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb8-1">mascot<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mascot_studio</span>()</span></code></pre></div></div>
<p>The studio runs locally on your computer without internet access. You can select any character, tweak parameters—such as placement, sizes, speech bubbles, and gestures—and see the character react live. Beneath the preview, the studio displays the exact R code required to reproduce what you see.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/images/mascot-studio.jpg" class="lightbox" data-gallery="quarto-lightbox-gallery-2" title="The mascot studio in a browser: Tessa in a preview pane with a speech bubble and her status line, and the R code for her current settings underneath."><img src="https://insightsurge-dev.web.app/posts/introducing-mascot/images/mascot-studio.jpg" class="img-fluid figure-img" alt="The mascot studio in a browser: Tessa in a preview pane with a speech bubble and her status line, and the R code for her current settings underneath."></a></p>
<figcaption>The mascot studio in a browser: Tessa in a preview pane with a speech bubble and her status line, and the R code for her current settings underneath.</figcaption>
</figure>
</div>
<p>To explore theming and check accessibility, run:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb9-1">mascot<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mascot_studio</span>(<span class="at" style="color: #657422;">view =</span> <span class="st" style="color: #20794D;">"theme"</span>)</span></code></pre></div></div>
<p>This view lets you test named palettes, custom brand hex codes, or <code>bslib</code> theme colours. Its <strong>Check</strong> tab shows every mood in light and dark mode and warns about low contrast.</p>
</section>
<section id="built-for-regulated-work" class="level2">
<h2 class="anchored" data-anchor-id="built-for-regulated-work">Built for regulated work</h2>
<p><code>mascot</code> is built for GxP work. These are the design choices that matter there:</p>
<ul>
<li><strong>Offline by design:</strong> every script and style ships inside the package, so drawing a mascot needs no internet access.</li>
<li><strong>Deterministic drawing:</strong> a frame is worked out from the character and its state only. The engine never reads the clock to draw and never calls <code>Math.random()</code>, so the same inputs give the same drawing. Blinking follows a seeded rule rather than chance.</li>
<li><strong>Light and dark mode:</strong> a mascot follows your <code>bslib</code> colour toggle or Quarto’s theme mode.</li>
<li><strong>Accessible semantics:</strong> a mascot without a click is a picture for screen readers, and keyboard focus skips it. Give it a click action (<code>mascot_action()</code>) or a menu (<code>mascot_popup_menu()</code>) and it becomes a button: Enter or Space activates it and screen readers announce its label.</li>
</ul>
<p>In regulated workflows, use <code>mascot</code> <strong>beside your application’s field errors and audit tables, never instead of them</strong>. A friendly character provides situational awareness, but it does not replace formal form validation, explicit discrepancy logs, or verified data exports.</p>
</section>
<section id="what-is-experimental" class="level2">
<h2 class="anchored" data-anchor-id="what-is-experimental">What is experimental</h2>
<p>Tessa and Sela are the stable characters in 0.1.0. Knurl, Neer, <code>mascot_studio()</code>, free dragging (<code>drag = "free"</code>), custom CSS variable styling and automatic mapping of <code>bslib</code> theme colours are experimental, so their arguments and results may change.</p>
<p>You can already describe your own character in a JSON file and check it with <code>mascot_check_character()</code>. That is experimental too, and saving and registering characters comes in a later release. The package site has the format guide.</p>
</section>
<section id="where-next" class="level2">
<h2 class="anchored" data-anchor-id="where-next">Where next</h2>
<p>With version 0.1.0 on CRAN, you can start adding live characters to your internal Shiny applications and Quarto dashboards. Version 0.2.0 is planned to add the Quarto shortcode.</p>
<ul>
<li>Read the <a href="https://insightsurge.github.io/mascot/">mascot package documentation</a> for articles, the function reference and styling guides.</li>
<li>Report a problem or suggest a feature on the <a href="https://github.com/insightsurge/mascot/issues">issue tracker</a>.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/scripts/review-demo.R">View <code>review-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/introducing-mascot/scripts/review-demo.R" download="review-demo.R">Download</a></p>
<p>The date-check app from the animation: a function that checks visit dates, the function that turns the result into a mood and a status line, the Shiny app, and a <code>shiny::testServer()</code> check of the server logic. Requires <code>{shiny}</code> and <code>{mascot}</code>. Its functions have tests that check the flagged rows and the moods, and that catch an unusable <code>update_mascot()</code> argument.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>review-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="co" style="color: #5E5E5E;"># A small Shiny form whose mascot reports what a date check found: the app</span></span>
<span id="cb10-2"><span class="co" style="color: #5E5E5E;"># from the post's animation. Defines a pure helper that checks visit dates,</span></span>
<span id="cb10-3"><span class="co" style="color: #5E5E5E;"># a mapping from its result to a mascot mood and status line, the app itself,</span></span>
<span id="cb10-4"><span class="co" style="color: #5E5E5E;"># and a headless check of the server logic with shiny::testServer().</span></span>
<span id="cb10-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb10-6"><span class="co" style="color: #5E5E5E;">#   Rscript review-demo.R           # runs the headless check</span></span>
<span id="cb10-7"><span class="co" style="color: #5E5E5E;">#   shiny::runApp(review_app())     # opens the app (after sourcing this file)</span></span>
<span id="cb10-8"></span>
<span id="cb10-9"><span class="co" style="color: #5E5E5E;">#' Check visit dates typed one per line</span></span>
<span id="cb10-10"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-11"><span class="co" style="color: #5E5E5E;">#' A date needs a look when it cannot be read as `YYYY-MM-DD` or lies after</span></span>
<span id="cb10-12"><span class="co" style="color: #5E5E5E;">#' `today`.</span></span>
<span id="cb10-13"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-14"><span class="co" style="color: #5E5E5E;">#' @param lines Character vector, one visit date per element.</span></span>
<span id="cb10-15"><span class="co" style="color: #5E5E5E;">#' @param today The latest date accepted. Pass it explicitly in tests.</span></span>
<span id="cb10-16"><span class="co" style="color: #5E5E5E;">#' @return A list with `n_rows` (non-empty lines), `bad` (the lines that need</span></span>
<span id="cb10-17"><span class="co" style="color: #5E5E5E;">#'   a look) and `n_bad`.</span></span>
<span id="cb10-18"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-19">check_dates <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(lines, <span class="at" style="color: #657422;">today =</span> <span class="fu" style="color: #4758AB;">Sys.Date</span>()) {</span>
<span id="cb10-20">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.character</span>(lines)) {</span>
<span id="cb10-21">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`lines` must be a character vector."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb10-22">  }</span>
<span id="cb10-23">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">trimws</span>(lines)</span>
<span id="cb10-24">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> lines[<span class="fu" style="color: #4758AB;">nzchar</span>(lines)]</span>
<span id="cb10-25">  parsed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as.Date</span>(lines, <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"%Y-%m-%d"</span>, <span class="at" style="color: #657422;">optional =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb10-26">  needs_look <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">is.na</span>(parsed) <span class="sc" style="color: #5E5E5E;">|</span> parsed <span class="sc" style="color: #5E5E5E;">&gt;</span> today</span>
<span id="cb10-27">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb10-28">    <span class="at" style="color: #657422;">n_rows =</span> <span class="fu" style="color: #4758AB;">length</span>(lines),</span>
<span id="cb10-29">    <span class="at" style="color: #657422;">bad =</span> lines[needs_look],</span>
<span id="cb10-30">    <span class="at" style="color: #657422;">n_bad =</span> <span class="fu" style="color: #4758AB;">sum</span>(needs_look)</span>
<span id="cb10-31">  )</span>
<span id="cb10-32">}</span>
<span id="cb10-33"></span>
<span id="cb10-34"><span class="co" style="color: #5E5E5E;">#' Turn a date check into a mood and a status line</span></span>
<span id="cb10-35"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-36"><span class="co" style="color: #5E5E5E;">#' The status text says the same thing as the face, so the face never carries</span></span>
<span id="cb10-37"><span class="co" style="color: #5E5E5E;">#' the meaning alone.</span></span>
<span id="cb10-38"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-39"><span class="co" style="color: #5E5E5E;">#' @param check The list returned by `check_dates()`.</span></span>
<span id="cb10-40"><span class="co" style="color: #5E5E5E;">#' @return A list with `mood` and `status`, ready for `update_mascot()`.</span></span>
<span id="cb10-41"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-42">mascot_state <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(check) {</span>
<span id="cb10-43">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (check<span class="sc" style="color: #5E5E5E;">$</span>n_rows <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb10-44">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"idle"</span>, <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"Paste some dates to check"</span>))</span>
<span id="cb10-45">  }</span>
<span id="cb10-46">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (check<span class="sc" style="color: #5E5E5E;">$</span>n_bad <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb10-47">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"happy"</span>, <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"All checks passed"</span>))</span>
<span id="cb10-48">  }</span>
<span id="cb10-49">  status <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (check<span class="sc" style="color: #5E5E5E;">$</span>n_bad <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">1</span>L) {</span>
<span id="cb10-50">    <span class="st" style="color: #20794D;">"One date needs a look"</span></span>
<span id="cb10-51">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb10-52">    <span class="fu" style="color: #4758AB;">paste</span>(check<span class="sc" style="color: #5E5E5E;">$</span>n_bad, <span class="st" style="color: #20794D;">"dates need a look"</span>)</span>
<span id="cb10-53">  }</span>
<span id="cb10-54">  <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"worried"</span>, <span class="at" style="color: #657422;">status =</span> status)</span>
<span id="cb10-55">}</span>
<span id="cb10-56"></span>
<span id="cb10-57">review_ui <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb10-58">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">fluidPage</span>(</span>
<span id="cb10-59">    mascot<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mascot</span>(</span>
<span id="cb10-60">      <span class="st" style="color: #20794D;">"reviewer"</span>,</span>
<span id="cb10-61">      <span class="at" style="color: #657422;">mood =</span> <span class="st" style="color: #20794D;">"idle"</span>,</span>
<span id="cb10-62">      <span class="at" style="color: #657422;">status =</span> <span class="st" style="color: #20794D;">"Paste some dates to check"</span>,</span>
<span id="cb10-63">      <span class="at" style="color: #657422;">placement =</span> <span class="st" style="color: #20794D;">"inline"</span></span>
<span id="cb10-64">    ),</span>
<span id="cb10-65">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">textAreaInput</span>(<span class="st" style="color: #20794D;">"dates"</span>, <span class="st" style="color: #20794D;">"Visit dates (YYYY-MM-DD)"</span>, <span class="at" style="color: #657422;">rows =</span> <span class="dv" style="color: #AD0000;">6</span>),</span>
<span id="cb10-66">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">actionButton</span>(<span class="st" style="color: #20794D;">"check"</span>, <span class="st" style="color: #20794D;">"Check"</span>),</span>
<span id="cb10-67">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">verbatimTextOutput</span>(<span class="st" style="color: #20794D;">"flagged"</span>)</span>
<span id="cb10-68">  )</span>
<span id="cb10-69">}</span>
<span id="cb10-70"></span>
<span id="cb10-71">review_server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">today =</span> <span class="fu" style="color: #4758AB;">Sys.Date</span>()) {</span>
<span id="cb10-72">  <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb10-73">    result <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">eventReactive</span>(input<span class="sc" style="color: #5E5E5E;">$</span>check, {</span>
<span id="cb10-74">      <span class="fu" style="color: #4758AB;">check_dates</span>(<span class="fu" style="color: #4758AB;">strsplit</span>(input<span class="sc" style="color: #5E5E5E;">$</span>dates, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)[[<span class="dv" style="color: #AD0000;">1</span>]], <span class="at" style="color: #657422;">today =</span> today)</span>
<span id="cb10-75">    })</span>
<span id="cb10-76"></span>
<span id="cb10-77">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">observeEvent</span>(<span class="fu" style="color: #4758AB;">result</span>(), {</span>
<span id="cb10-78">      state <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">mascot_state</span>(<span class="fu" style="color: #4758AB;">result</span>())</span>
<span id="cb10-79">      mascot<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">update_mascot</span>(</span>
<span id="cb10-80">        <span class="st" style="color: #20794D;">"reviewer"</span>,</span>
<span id="cb10-81">        <span class="at" style="color: #657422;">mood =</span> state<span class="sc" style="color: #5E5E5E;">$</span>mood,</span>
<span id="cb10-82">        <span class="at" style="color: #657422;">status =</span> state<span class="sc" style="color: #5E5E5E;">$</span>status</span>
<span id="cb10-83">      )</span>
<span id="cb10-84">    })</span>
<span id="cb10-85"></span>
<span id="cb10-86">    output<span class="sc" style="color: #5E5E5E;">$</span>flagged <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">renderText</span>({</span>
<span id="cb10-87">      <span class="fu" style="color: #4758AB;">paste</span>(<span class="fu" style="color: #4758AB;">result</span>()<span class="sc" style="color: #5E5E5E;">$</span>bad, <span class="at" style="color: #657422;">collapse =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb10-88">    })</span>
<span id="cb10-89">  }</span>
<span id="cb10-90">}</span>
<span id="cb10-91"></span>
<span id="cb10-92">review_app <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">today =</span> <span class="fu" style="color: #4758AB;">Sys.Date</span>()) {</span>
<span id="cb10-93">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">shinyApp</span>(<span class="fu" style="color: #4758AB;">review_ui</span>(), <span class="fu" style="color: #4758AB;">review_server</span>(today))</span>
<span id="cb10-94">}</span>
<span id="cb10-95"></span>
<span id="cb10-96"><span class="co" style="color: #5E5E5E;">#' Run headless checks on the server logic with testServer</span></span>
<span id="cb10-97"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-98"><span class="co" style="color: #5E5E5E;">#' Sets the input as a user would, then checks the flagged rows and that</span></span>
<span id="cb10-99"><span class="co" style="color: #5E5E5E;">#' `update_mascot()` runs without a warning (it warns, and leaves the mascot</span></span>
<span id="cb10-100"><span class="co" style="color: #5E5E5E;">#' unchanged, when it is given an argument it cannot use).</span></span>
<span id="cb10-101"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-102"><span class="co" style="color: #5E5E5E;">#' @return `TRUE`, invisibly, if every check passes.</span></span>
<span id="cb10-103"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-104">run_review_checks <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb10-105">  today <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as.Date</span>(<span class="st" style="color: #20794D;">"2026-11-12"</span>)</span>
<span id="cb10-106">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">testServer</span>(<span class="fu" style="color: #4758AB;">review_server</span>(today), {</span>
<span id="cb10-107">    session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">dates =</span> <span class="st" style="color: #20794D;">"2026-03-02</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">2026-13-45</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">2027-01-05"</span>, <span class="at" style="color: #657422;">check =</span> <span class="dv" style="color: #AD0000;">1</span>)</span>
<span id="cb10-108">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(output<span class="sc" style="color: #5E5E5E;">$</span>flagged, <span class="st" style="color: #20794D;">"2026-13-45</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">2027-01-05"</span>))</span>
<span id="cb10-109"></span>
<span id="cb10-110">    session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">dates =</span> <span class="st" style="color: #20794D;">"2026-03-02</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">2026-03-09"</span>, <span class="at" style="color: #657422;">check =</span> <span class="dv" style="color: #AD0000;">2</span>)</span>
<span id="cb10-111">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(output<span class="sc" style="color: #5E5E5E;">$</span>flagged, <span class="st" style="color: #20794D;">""</span>))</span>
<span id="cb10-112">  })</span>
<span id="cb10-113">  <span class="fu" style="color: #4758AB;">invisible</span>(<span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb10-114">}</span>
<span id="cb10-115"></span>
<span id="cb10-116"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb10-117">  <span class="fu" style="color: #4758AB;">run_review_checks</span>()</span>
<span id="cb10-118">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"review-demo.R: checks passed</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb10-119">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<ul>
<li><strong>CRAN package repository:</strong> <a href="https://CRAN.R-project.org/package=mascot">mascot on CRAN</a></li>
<li><strong>Package documentation site:</strong> <a href="https://insightsurge.github.io/mascot/">mascot documentation</a></li>
<li><strong>Source code and issue tracker:</strong> <a href="https://github.com/insightsurge/mascot">mascot on GitHub</a></li>
<li><strong>Shiny package:</strong> <a href="https://CRAN.R-project.org/package=shiny">shiny on CRAN</a></li>
<li><strong>Web Content Accessibility Guidelines, Use of Color:</strong> <a href="https://www.w3.org/WAI/WCAG21/Understanding/use-of-color.html">Understanding Success Criterion 1.4.1</a></li>
<li><strong>bslib package:</strong> <a href="https://CRAN.R-project.org/package=bslib">bslib on CRAN</a></li>
<li><strong>knitr package:</strong> <a href="https://CRAN.R-project.org/package=knitr">knitr on CRAN</a></li>
</ul>



</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor site-related">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/shiny-testserver/index.html" class="site-link-row" title="Test Shiny modules and server logic headless with shiny::testServer(), verify reactive state and return values, and separate pure logic for testthat."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Testing Shiny server logic with testServer()</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/index.html" class="site-link-row" title="Drive Shiny applications end to end with shinytest2 and headless Chrome, testing real browser rendering, user input sequences, and reactive outputs."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">End-to-end Shiny tests with shinytest2</span></a></li>
</ul>
</div>
</section>


 ]]></description>
  <category>mascot</category>
  <category>R packages</category>
  <category>Shiny</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/introducing-mascot/</guid>
  <pubDate>Wed, 11 Nov 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Dependencies: DESCRIPTION and NAMESPACE</title>
  <link>https://insightsurge-dev.web.app/posts/package-dependencies-namespace/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem-library-in-package-code" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-library-in-package-code">The problem: <code>library()</code> in package code</h2>
<p>In an analysis script, a line such as <code>library(dplyr)</code> or <code>library(tools)</code> does two jobs simultaneously: it declares that the script expects a package to be installed, and it attaches that package’s exported functions directly onto the search path so you can call <code>filter()</code> or <code>file_ext()</code> unqualified.</p>
<p>When developers convert an analysis script into an R package, they often keep those <code>library()</code> calls at the top of files in <code>R/</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="co" style="color: #5E5E5E;"># R/ext.R</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">library</span>(tools)</span>
<span id="cb1-3"></span>
<span id="cb1-4">get_ext <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb1-5">  <span class="fu" style="color: #4758AB;">file_ext</span>(path)</span>
<span id="cb1-6">}</span></code></pre></div></div>
<p>During interactive package development, this pattern appears to work. When you run <code>pkgload::load_all()</code>, the development helper sources the files in <code>R/</code> into an interactive environment, which attaches <code>{tools}</code> to your current session search path. <code>get_ext("trial_data.csv")</code> returns <code>"csv"</code> without error.</p>
<p>Once the package is installed via <code>R CMD INSTALL</code>, however, top-level code in <code>R/</code> behaves differently. Top-level statements run during package installation to prepare the namespace image. When a user later loads your package with <code>library(mypkg)</code> in a fresh session, those top-level lines do not re-run. The <code>{tools}</code> namespace is never attached to the user’s search path. Calling <code>get_ext("trial_data.csv")</code> immediately fails:</p>
<pre class="text"><code>Error in file_ext(path) : could not find function "file_ext"</code></pre>
<p>Placing <code>library()</code> inside a function body creates a different failure mode:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">get_ext <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb3-2">  <span class="fu" style="color: #4758AB;">library</span>(tools)</span>
<span id="cb3-3">  <span class="fu" style="color: #4758AB;">file_ext</span>(path)</span>
<span id="cb3-4">}</span></code></pre></div></div>
<p>Inside a function, <code>library()</code> mutates the search path of whoever called it. Attaching a package as a side effect of calling a calculation or utility function can silently mask functions in the user’s workspace. <code>R CMD check</code> flags this practice explicitly with a WARNING:</p>
<pre class="text"><code>* checking dependencies in R code ... WARNING
'library' or 'require' call not declared from: ‘tools’
'library' or 'require' call to ‘tools’ in package code.
  Please use :: or requireNamespace() instead.
  See section 'Suggested packages' in the 'Writing R Extensions' manual.</code></pre>
<p>In our check run on R 4.6.1 (with <code>{tools}</code> declared in <code>Imports</code>), a top-level <code>library(tools)</code> escaped that <code>'library' or 'require'</code> WARNING, but <code>R CMD check</code> still caught the breakdown with two NOTEs: <code>Namespace in Imports field not imported from: 'tools'</code> and <code>get_ext: no visible global function definition for 'file_ext'</code>.</p>
<p>A package cannot rely on script-style attachment. It must separate what must be installed from how individual functions are referenced.</p>
</section>
<section id="the-web-repo-way-manifest-declarations-and-explicit-imports" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-manifest-declarations-and-explicit-imports">The web-repo way: manifest declarations and explicit imports</h2>
<p>Developers working in Node (<code>package.json</code>) or Python (<code>pyproject.toml</code>) will recognize this division immediately:</p>
<ul>
<li><strong>Runtime dependencies:</strong> Node lists production packages in <code>dependencies</code>; Python lists required distributions in <code>dependencies</code> under <code>[project]</code>.</li>
<li><strong>Development tools:</strong> Node uses <code>devDependencies</code> for local test and build tools.</li>
<li><strong>Optional dependencies:</strong> npm’s <code>optionalDependencies</code> lets installation continue if one is unavailable. Python’s <code>[project.optional-dependencies]</code> defines extras a consumer can request, such as <code>mypkg[report]</code>.</li>
<li><strong>Local imports:</strong> Source files import names they use, for example <code>import { readFile } from "node:fs/promises"</code> and <code>from os.path import splitext</code>. Those names are bound in that module, unlike R’s package-wide <code>NAMESPACE</code> imports.</li>
</ul>
<p>R adopts the same conceptual division, but implements it with two distinct files:</p>
<ol type="1">
<li><code>DESCRIPTION</code> acts as the package manifest. It tells package managers (<code>install.packages()</code>, <code>pak</code>) what external packages must be installed on the machine.</li>
<li><code>NAMESPACE</code> controls symbol visibility. It informs R’s namespace mechanism which external functions your package code borrows, and which internal functions your package exports to consumers.</li>
</ol>
<p>The critical difference to keep in mind is that in R, <code>NAMESPACE</code> imports are <strong>package-wide</strong>, not file-scoped. A symbol imported in <code>NAMESPACE</code> is accessible to every function across all files in <code>R/</code>. Furthermore, listing a package under <code>Imports:</code> in <code>DESCRIPTION</code> does not actually import any functions into your code; it ensures installation and namespace availability, leaving the import mechanism to <code>NAMESPACE</code> or <code>::</code>.</p>
</section>
<section id="the-r-way-description-fields-and-namespace-resolution" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-description-fields-and-namespace-resolution">The R way: DESCRIPTION fields and NAMESPACE resolution</h2>
<section id="description-choosing-the-correct-dependency-field" class="level3">
<h3 class="anchored" data-anchor-id="description-choosing-the-correct-dependency-field">DESCRIPTION: choosing the correct dependency field</h3>
<p>Section 1.1.3 of <em>Writing R Extensions</em> defines the four main dependency fields in <code>DESCRIPTION</code>:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>Field</th>
<th>When to use it</th>
<th>Installed by default?</th>
<th>Attached to search path?</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong><code>Imports</code></strong></td>
<td>Required packages whose functions you call via <code>pkg::fun()</code> or <code>@importFrom</code>.</td>
<td>Yes (by <code>install.packages()</code>)</td>
<td>No</td>
</tr>
<tr class="even">
<td><strong><code>Suggests</code></strong></td>
<td>Packages used only in unit tests, vignettes, documentation examples, or optional helper functions.</td>
<td>No</td>
<td>No</td>
</tr>
<tr class="odd">
<td><strong><code>Depends</code></strong></td>
<td>Minimum R version requirements (<code>R (&gt;= 4.1)</code>), or rare meta-packages designed to expose another package’s entire API.</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr class="even">
<td><strong><code>LinkingTo</code></strong></td>
<td>Packages providing C/C++ header files at compilation time (such as <code>{cpp11}</code> or <code>{Rcpp}</code>).</td>
<td>Yes</td>
<td>No</td>
</tr>
</tbody>
</table>
</div>
<p>Don’t list a package in both <code>Depends</code> and <code>Imports</code>. <code>LinkingTo</code> is separate: a package such as <code>{Rcpp}</code> often appears in both <code>Imports</code> and <code>LinkingTo</code>.</p>
<section id="why-depends-is-rarely-appropriate-for-packages" class="level4">
<h4 class="anchored" data-anchor-id="why-depends-is-rarely-appropriate-for-packages">Why <code>Depends</code> is rarely appropriate for packages</h4>
<p>In early versions of R, <code>Depends</code> was the standard method for declaring dependencies. However, because <code>Depends</code> attaches the listed packages to the search path whenever your package is attached, it pollutes the user’s workspace with symbols they did not request. As Hadley Wickham and Jenny Bryan emphasize in <em>R Packages</em> (2e), you should list packages in <code>Imports</code>, not <code>Depends</code>. <em>Writing R Extensions</em> (§1.1.3) similarly notes: “Field ‘Depends’ should nowadays be used rarely”.</p>
<p>Reserve <code>Depends</code> almost exclusively for declaring the minimum R version required by your code:</p>
<pre class="text"><code>Depends:
    R (&gt;= 4.1)</code></pre>
</section>
<section id="specifying-minimum-versions" class="level4">
<h4 class="anchored" data-anchor-id="specifying-minimum-versions">Specifying minimum versions</h4>
<p>If your code relies on a feature introduced in a recent release of a dependency, pin the minimum version in parentheses: <code>cli (&gt;= 3.6.0)</code>.</p>
<pre class="text"><code>Depends:
    R (&gt;= 4.1)
Imports:
    cli (&gt;= 3.6.0),
    rlang
Suggests:
    knitr,
    testthat (&gt;= 3.0.0)</code></pre>
<p>In our tests on R 4.6.1, <code>pkgload::load_all()</code> and <code>R CMD check</code> both halt if an installed dependency fails to satisfy a declared minimum version requirement, reporting that an unsuitable version is present.</p>
</section>
<section id="automating-declarations-with-usethis" class="level4">
<h4 class="anchored" data-anchor-id="automating-declarations-with-usethis">Automating declarations with <code>{usethis}</code></h4>
<p>Rather than editing <code>DESCRIPTION</code> manually, use <code>usethis::use_package()</code> to modify fields safely:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"cli"</span>, <span class="at" style="color: #657422;">min_version =</span> <span class="st" style="color: #20794D;">"3.6.0"</span>)</span>
<span id="cb7-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"knitr"</span>, <span class="at" style="color: #657422;">type =</span> <span class="st" style="color: #20794D;">"Suggests"</span>)</span>
<span id="cb7-3">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"R"</span>, <span class="at" style="color: #657422;">type =</span> <span class="st" style="color: #20794D;">"Depends"</span>, <span class="at" style="color: #657422;">min_version =</span> <span class="st" style="color: #20794D;">"4.1"</span>)</span></code></pre></div></div>
<p>When you add a dependency, <code>{usethis}</code> updates the correct field and reminds you how to call its functions:</p>
<pre class="text"><code>✔ Adding cli to 'Imports' field in DESCRIPTION.
☐ Refer to functions with `cli::fun()`.
✔ Adding knitr to 'Suggests' field in DESCRIPTION.
☐ Use `requireNamespace("knitr", quietly = TRUE)` to test if knitr is installed.
☐ Then directly refer to functions with `knitr::fun()`.</code></pre>
<p>If you specify <code>min_version = TRUE</code>, <code>{usethis}</code> reads the version currently installed in your library and sets that as the lower bound. If you request <code>type = "Depends"</code> for a package, <code>{usethis}</code> warns:</p>
<pre class="text"><code>! Are you sure you want 'Depends'? 'Imports' is almost always the better choice.</code></pre>
<p>If a package is already in <code>Suggests</code>, calling <code>use_package("pkg", type = "Imports")</code> promotes it. However, <code>{usethis}</code> will not demote an entry from <code>Imports</code> to <code>Suggests</code>, nor does it provide a helper function to remove dependencies; when you drop a dependency, delete the entry from <code>DESCRIPTION</code> by hand.</p>
</section>
</section>
<section id="namespace-calling-external-functions" class="level3">
<h3 class="anchored" data-anchor-id="namespace-calling-external-functions">NAMESPACE: calling external functions</h3>
<p>Once an external package is declared in <code>DESCRIPTION</code>, you have three ways to call its functions from <code>R/</code>:</p>
<section id="the-default-pkgfun" class="level4">
<h4 class="anchored" data-anchor-id="the-default-pkgfun">1. The default: <code>pkg::fun()</code></h4>
<p>The recommended default in modern R package engineering is to call external functions explicitly with the double-colon operator: <code>cli::cli_inform()</code>.</p>
<p>Calling <code>pkg::fun()</code> offers three distinct benefits: - <strong>Provenance:</strong> Anyone reading the code knows exactly where the function originates without searching through <code>NAMESPACE</code> or roxygen comments. - <strong>Conflict prevention:</strong> It eliminates name collisions between packages. - <strong>On-demand loading:</strong> When your package is loaded, packages referenced only via <code>::</code> are loaded on first use rather than immediately at package load time. (By contrast, <code>pkgload::load_all()</code> loads all packages listed in <code>Imports</code> up front during development).</p>
</section>
<section id="selective-imports-importfrom" class="level4">
<h4 class="anchored" data-anchor-id="selective-imports-importfrom">2. Selective imports: <code>@importFrom</code></h4>
<p>Infix operators are awkward to call with <code>::</code>: <code>rlang::`%||%`(x, y)</code> works but is harder to read than <code>x %||% y</code>. For functions called repeatedly in a tight loop, an import can also avoid repeated namespace lookups.</p>
<p>To import specific functions into your package’s namespace, add the <code>@importFrom</code> roxygen tag above the calling function:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="co" style="color: #5E5E5E;"># R/summary.R</span></span>
<span id="cb10-2"></span>
<span id="cb10-3"><span class="co" style="color: #5E5E5E;">#' Format a summary label</span></span>
<span id="cb10-4"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-5"><span class="co" style="color: #5E5E5E;">#' @param x A vector of values.</span></span>
<span id="cb10-6"><span class="co" style="color: #5E5E5E;">#' @param label An optional display label.</span></span>
<span id="cb10-7"><span class="co" style="color: #5E5E5E;">#' @return Invisible NULL; emits an informative message.</span></span>
<span id="cb10-8"><span class="co" style="color: #5E5E5E;">#' @importFrom rlang %||%</span></span>
<span id="cb10-9"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-10">summary_label <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x, <span class="at" style="color: #657422;">label =</span> <span class="cn" style="color: #8f5902;">NULL</span>) {</span>
<span id="cb10-11">  label <span class="ot" style="color: #003B4F;">&lt;-</span> label <span class="sc" style="color: #5E5E5E;">%||%</span> <span class="st" style="color: #20794D;">"Summary"</span></span>
<span id="cb10-12">  cli<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">cli_inform</span>(<span class="st" style="color: #20794D;">"{label}: {length(x)} value{?s}"</span>)</span>
<span id="cb10-13">}</span></code></pre></div></div>
<p>When you run <code>devtools::document()</code>, <code>{roxygen2}</code> writes the corresponding directive to <code>NAMESPACE</code>. In <code>{roxygen2}</code> 8.1.0, multiple <code>@importFrom</code> directives for the same external package are collapsed into a single multi-line statement:</p>
<pre class="text"><code>export(summary_label)
importFrom(rlang,"%||%")</code></pre>
<p>To keep import tags in one place, first create package-level documentation with <code>usethis::use_package_doc()</code> if your package has none. Then <code>usethis::use_import_from("rlang", "%||%")</code> places the tag in <code>R/&lt;pkg&gt;-package.R</code> and updates <code>NAMESPACE</code>.</p>
</section>
<section id="why-to-avoid-full-package-imports-import" class="level4">
<h4 class="anchored" data-anchor-id="why-to-avoid-full-package-imports-import">3. Why to avoid full package imports: <code>@import</code></h4>
<p>The <code>@import pkg</code> tag instructs <code>{roxygen2}</code> to write <code>import(pkg)</code> into <code>NAMESPACE</code>, pulling all exported symbols from that package into your package’s namespace.</p>
<p>While this saves typing, it creates subtle bugs when two imported packages export overlapping names. For example, if a package uses both <code>@import dplyr</code> and <code>@import stats</code>, loading the package prints a collision warning:</p>
<pre class="text"><code>replacing previous import ‘dplyr::filter’ by ‘stats::filter’ when loading ‘mypkg’</code></pre>
<p>Inside this package, an unqualified <code>filter()</code> resolves to <code>stats::filter()</code>. Code that expected <code>dplyr::filter()</code> may then error or produce the wrong result. For this reason, <em>R Packages</em> (2e) recommends <code>pkg::fun()</code> or <code>@importFrom</code> for most code. Stick to <code>pkg::fun()</code> as your default, supplemented by targeted <code>@importFrom</code> tags.</p>
</section>
</section>
<section id="optional-packages-the-suggests-guard" class="level3">
<h3 class="anchored" data-anchor-id="optional-packages-the-suggests-guard">Optional packages: the Suggests guard</h3>
<p>Packages listed in <code>Suggests</code> are not installed by default when someone installs your package. If an optional calculation, report formatter, or export function requires a suggested package, you must verify its presence before invoking it.</p>
<p>R provides two distinct patterns for guarding optional dependencies.</p>
<section id="pattern-1-asserting-presence-with-rlangcheck_installed" class="level4">
<h4 class="anchored" data-anchor-id="pattern-1-asserting-presence-with-rlangcheck_installed">Pattern 1: Asserting presence with <code>rlang::check_installed()</code></h4>
<p>When a function cannot proceed without the optional package, use <code>rlang::check_installed()</code>. It accepts a human-readable <code>reason</code> explaining why the package is needed:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">markdown_table <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data) {</span>
<span id="cb13-2">  rlang<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">check_installed</span>(<span class="st" style="color: #20794D;">"knitr"</span>, <span class="at" style="color: #657422;">reason =</span> <span class="st" style="color: #20794D;">"to format the table as Markdown"</span>)</span>
<span id="cb13-3">  knitr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">kable</span>(data, <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"pipe"</span>)</span>
<span id="cb13-4">}</span>
<span id="cb13-5"></span>
<span id="cb13-6"><span class="fu" style="color: #4758AB;">markdown_table</span>(<span class="fu" style="color: #4758AB;">head</span>(mtcars[, <span class="dv" style="color: #AD0000;">1</span><span class="sc" style="color: #5E5E5E;">:</span><span class="dv" style="color: #AD0000;">3</span>], <span class="dv" style="color: #AD0000;">3</span>))</span></code></pre></div></div>
<p>If the package is missing, <code>rlang::check_installed()</code> behaves according to session interactivity: - In an <strong>interactive</strong> session, it prompts the user with an option to install the missing package via <code>pak</code> or <code>install.packages()</code>. - In a <strong>non-interactive</strong> session (such as a batch calculation, CI runner, or automated reporting pipeline), it aborts evaluation immediately with an error of class <code>rlib_error_package_not_found</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="fu" style="color: #4758AB;">tryCatch</span>(</span>
<span id="cb14-2">  rlang<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">check_installed</span>(<span class="st" style="color: #20794D;">"notarealpkg"</span>, <span class="at" style="color: #657422;">reason =</span> <span class="st" style="color: #20794D;">"to format the table as Markdown"</span>),</span>
<span id="cb14-3">  <span class="at" style="color: #657422;">error =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(e) <span class="fu" style="color: #4758AB;">class</span>(e)</span>
<span id="cb14-4">)</span></code></pre></div></div>
<p>The error condition contains a <code>$pkg</code> element naming the missing dependency, and attributes the error to the calling function rather than the internal check. You can also specify minimum version constraints directly in the guard: <code>rlang::check_installed("knitr (&gt;= 1.40.0)")</code>.</p>
</section>
<section id="pattern-2-graceful-degradation-with-requirenamespace" class="level4">
<h4 class="anchored" data-anchor-id="pattern-2-graceful-degradation-with-requirenamespace">Pattern 2: Graceful degradation with <code>requireNamespace()</code></h4>
<p>If your function can fall back to a base R method or alternative representation when the suggested package is unavailable, use <code>requireNamespace(..., quietly = TRUE)</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">as_table <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data) {</span>
<span id="cb15-2">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">requireNamespace</span>(<span class="st" style="color: #20794D;">"knitr"</span>, <span class="at" style="color: #657422;">quietly =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)) {</span>
<span id="cb15-3">    knitr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">kable</span>(data, <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"pipe"</span>)</span>
<span id="cb15-4">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb15-5">    data</span>
<span id="cb15-6">  }</span>
<span id="cb15-7">}</span>
<span id="cb15-8"></span>
<span id="cb15-9"><span class="fu" style="color: #4758AB;">as_table</span>(<span class="fu" style="color: #4758AB;">head</span>(mtcars[, <span class="dv" style="color: #AD0000;">1</span><span class="sc" style="color: #5E5E5E;">:</span><span class="dv" style="color: #AD0000;">2</span>], <span class="dv" style="color: #AD0000;">2</span>))</span></code></pre></div></div>
<p>The argument <code>quietly = TRUE</code> is essential. If omitted, R prints a diagnostic message to standard error whenever the package is absent:</p>
<pre class="text"><code>Loading required namespace: notarealpkg
Failed with error:  ‘there is no package called ‘notarealpkg’’</code></pre>
<p>Do not use <code>require()</code> for conditioning in package code. Unlike <code>requireNamespace()</code>, <code>require()</code> attempts to attach the package to the user’s search path, emitting warnings on failure and polluting the session on success. The check WARNING above points to the same fix: use <code>::</code> or <code>requireNamespace()</code> (see <em>Writing R Extensions</em>, §1.1.3.1).</p>
</section>
</section>
<section id="handling-suggested-packages-in-test-suites" class="level3">
<h3 class="anchored" data-anchor-id="handling-suggested-packages-in-test-suites">Handling suggested packages in test suites</h3>
<p>Developer machines and CI runners usually install <code>Suggests</code> packages, so tests that use <code>{testthat}</code> itself need no guard. <em>Writing R Extensions</em> still asks for suggested packages to be used conditionally.</p>
<p>When a test exercises an optional integration or a heavy package that may not be present in every testing environment, guard the test block with <code>testthat::skip_if_not_installed()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb17-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"markdown formatting renders valid pipe table"</span>, {</span>
<span id="cb17-2">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">skip_if_not_installed</span>(<span class="st" style="color: #20794D;">"knitr"</span>, <span class="at" style="color: #657422;">minimum_version =</span> <span class="st" style="color: #20794D;">"1.40.0"</span>)</span>
<span id="cb17-3">  tbl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">markdown_table</span>(<span class="fu" style="color: #4758AB;">head</span>(mtcars, <span class="dv" style="color: #AD0000;">2</span>))</span>
<span id="cb17-4">  <span class="fu" style="color: #4758AB;">expect_s3_class</span>(tbl, <span class="st" style="color: #20794D;">"knitr_kable"</span>)</span>
<span id="cb17-5">})</span></code></pre></div></div>
<p>This prevents the test suite from generating false check failures when running on environments configured without optional dependencies.</p>
</section>
</section>
<section id="the-pharma-angle-dependency-assessment-and-verification-boundaries" class="level2">
<h2 class="anchored" data-anchor-id="the-pharma-angle-dependency-assessment-and-verification-boundaries">The pharma angle: dependency assessment and verification boundaries</h2>
<p>In regulated clinical reporting (GxP), every package declared in your manifest carries an evaluation footprint. As explored in <a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html">Runtime dependency vetting</a> and <a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html">Validation-ready R packages</a>, organisations must justify the integrity and stability of the software tools used to produce submission tables, figures, and listings.</p>
<p>An <code>Imports</code> entry makes a dependency available wherever your package is installed. Record direct and transitive dependencies, then assess their role in the actual workflow. The R Validation Hub distinguishes packages used directly from supporting imports and recommends focusing accuracy verification on the former; an <code>Imports</code> entry alone does not require separate accuracy qualification of its entire dependency tree. A package in <code>Suggests</code> still needs consideration if a production workflow uses it. Choose <code>Imports</code> when core functionality needs the package and <code>Suggests</code> when the feature is optional, rather than treating the field as a validation decision.</p>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/scripts/dependencies-demo.R">View <code>dependencies-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/scripts/dependencies-demo.R" download="dependencies-demo.R">Download</a></p>
<p>Writes a <code>DESCRIPTION</code> file in a temporary folder using <code>{desc}</code>, extracts and classifies dependencies into a structured table, flags common declaration mistakes, and demonstrates an <code>rlang::check_installed()</code> guard.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>dependencies-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><span class="co" style="color: #5E5E5E;"># Dependencies, read from DESCRIPTION: writes a small DESCRIPTION into a temp</span></span>
<span id="cb18-2"><span class="co" style="color: #5E5E5E;"># folder, lists its dependencies with their minimum versions, flags two</span></span>
<span id="cb18-3"><span class="co" style="color: #5E5E5E;"># common mistakes, and shows a guard for a package that is only suggested.</span></span>
<span id="cb18-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb18-5"><span class="co" style="color: #5E5E5E;">#   Rscript dependencies-demo.R</span></span>
<span id="cb18-6"></span>
<span id="cb18-7"><span class="co" style="color: #5E5E5E;"># Writes a DESCRIPTION with three dependency fields and returns its folder.</span></span>
<span id="cb18-8">write_demo_description <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">path =</span> <span class="fu" style="color: #4758AB;">tempfile</span>(<span class="st" style="color: #20794D;">"demopkg"</span>)) {</span>
<span id="cb18-9">  <span class="fu" style="color: #4758AB;">dir.create</span>(path, <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb18-10">  d <span class="ot" style="color: #003B4F;">&lt;-</span> desc<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">desc</span>(</span>
<span id="cb18-11">    <span class="at" style="color: #657422;">text =</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb18-12">      <span class="st" style="color: #20794D;">"Package: demopkg"</span>,</span>
<span id="cb18-13">      <span class="st" style="color: #20794D;">"Title: Demo Package"</span>,</span>
<span id="cb18-14">      <span class="st" style="color: #20794D;">"Version: 0.1.0"</span>,</span>
<span id="cb18-15">      <span class="st" style="color: #20794D;">"Description: Shows how a package declares its dependencies."</span>,</span>
<span id="cb18-16">      <span class="st" style="color: #20794D;">"License: MIT + file LICENSE"</span></span>
<span id="cb18-17">    )</span>
<span id="cb18-18">  )</span>
<span id="cb18-19">  d<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_dep</span>(<span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"Depends"</span>, <span class="st" style="color: #20794D;">"&gt;= 4.1"</span>)</span>
<span id="cb18-20">  d<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_dep</span>(<span class="st" style="color: #20794D;">"cli"</span>, <span class="st" style="color: #20794D;">"Imports"</span>, <span class="st" style="color: #20794D;">"&gt;= 3.6.0"</span>)</span>
<span id="cb18-21">  d<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_dep</span>(<span class="st" style="color: #20794D;">"rlang"</span>, <span class="st" style="color: #20794D;">"Imports"</span>)</span>
<span id="cb18-22">  d<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_dep</span>(<span class="st" style="color: #20794D;">"testthat"</span>, <span class="st" style="color: #20794D;">"Suggests"</span>, <span class="st" style="color: #20794D;">"&gt;= 3.0.0"</span>)</span>
<span id="cb18-23">  d<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_dep</span>(<span class="st" style="color: #20794D;">"knitr"</span>, <span class="st" style="color: #20794D;">"Suggests"</span>)</span>
<span id="cb18-24">  d<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">write</span>(<span class="at" style="color: #657422;">file =</span> <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"DESCRIPTION"</span>))</span>
<span id="cb18-25">  path</span>
<span id="cb18-26">}</span>
<span id="cb18-27"></span>
<span id="cb18-28"><span class="co" style="color: #5E5E5E;"># One row per dependency: its field, whether default installation needs it</span></span>
<span id="cb18-29"><span class="co" style="color: #5E5E5E;"># (Depends, Imports, LinkingTo), and the minimum version, if any.</span></span>
<span id="cb18-30">dependency_table <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb18-31">  deps <span class="ot" style="color: #003B4F;">&lt;-</span> desc<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">desc_get_deps</span>(path)</span>
<span id="cb18-32">  <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb18-33">    <span class="at" style="color: #657422;">package =</span> deps<span class="sc" style="color: #5E5E5E;">$</span>package,</span>
<span id="cb18-34">    <span class="at" style="color: #657422;">field =</span> deps<span class="sc" style="color: #5E5E5E;">$</span>type,</span>
<span id="cb18-35">    <span class="at" style="color: #657422;">required =</span> deps<span class="sc" style="color: #5E5E5E;">$</span>type <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"Depends"</span>, <span class="st" style="color: #20794D;">"Imports"</span>, <span class="st" style="color: #20794D;">"LinkingTo"</span>),</span>
<span id="cb18-36">    <span class="at" style="color: #657422;">min_version =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb18-37">      deps<span class="sc" style="color: #5E5E5E;">$</span>version <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"*"</span>,</span>
<span id="cb18-38">      <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb18-39">      <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"^&gt;=</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*"</span>, <span class="st" style="color: #20794D;">""</span>, deps<span class="sc" style="color: #5E5E5E;">$</span>version)</span>
<span id="cb18-40">    )</span>
<span id="cb18-41">  )</span>
<span id="cb18-42">}</span>
<span id="cb18-43"></span>
<span id="cb18-44"><span class="co" style="color: #5E5E5E;"># Two rules from Writing R Extensions: a package belongs in only one field,</span></span>
<span id="cb18-45"><span class="co" style="color: #5E5E5E;"># and Depends is for R itself and (rarely) packages users need attached.</span></span>
<span id="cb18-46">dependency_problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb18-47">  deps <span class="ot" style="color: #003B4F;">&lt;-</span> desc<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">desc_get_deps</span>(path)</span>
<span id="cb18-48">  counts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">table</span>(deps<span class="sc" style="color: #5E5E5E;">$</span>package)</span>
<span id="cb18-49">  <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb18-50">    <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"%s is listed in more than one field"</span>, <span class="fu" style="color: #4758AB;">names</span>(counts)[counts <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">1</span>]),</span>
<span id="cb18-51">    <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb18-52">      <span class="st" style="color: #20794D;">"%s is in Depends: prefer Imports"</span>,</span>
<span id="cb18-53">      <span class="fu" style="color: #4758AB;">setdiff</span>(deps<span class="sc" style="color: #5E5E5E;">$</span>package[deps<span class="sc" style="color: #5E5E5E;">$</span>type <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Depends"</span>], <span class="st" style="color: #20794D;">"R"</span>)</span>
<span id="cb18-54">    )</span>
<span id="cb18-55">  )</span>
<span id="cb18-56">}</span>
<span id="cb18-57"></span>
<span id="cb18-58"><span class="co" style="color: #5E5E5E;"># The guard for a suggested package: stops with a classed error that says</span></span>
<span id="cb18-59"><span class="co" style="color: #5E5E5E;"># what the package is needed for. Call it at the top of the function that</span></span>
<span id="cb18-60"><span class="co" style="color: #5E5E5E;"># uses the package, then call that package's functions with pkg::fun().</span></span>
<span id="cb18-61">check_suggested <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(pkg, reason, <span class="at" style="color: #657422;">call =</span> rlang<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">caller_env</span>()) {</span>
<span id="cb18-62">  rlang<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">check_installed</span>(pkg, <span class="at" style="color: #657422;">reason =</span> reason, <span class="at" style="color: #657422;">call =</span> call)</span>
<span id="cb18-63">}</span>
<span id="cb18-64"></span>
<span id="cb18-65"><span class="co" style="color: #5E5E5E;"># An example user: writes a Markdown table with knitr (a suggested package).</span></span>
<span id="cb18-66">markdown_table <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data) {</span>
<span id="cb18-67">  rlang<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">check_installed</span>(<span class="st" style="color: #20794D;">"knitr"</span>, <span class="at" style="color: #657422;">reason =</span> <span class="st" style="color: #20794D;">"to format the table as Markdown"</span>)</span>
<span id="cb18-68">  knitr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">kable</span>(data, <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"pipe"</span>)</span>
<span id="cb18-69">}</span>
<span id="cb18-70"></span>
<span id="cb18-71"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb18-72"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb18-73">  path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">write_demo_description</span>()</span>
<span id="cb18-74">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">readLines</span>(<span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"DESCRIPTION"</span>)), <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-75">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">dependency_table</span>(path))</span>
<span id="cb18-76"></span>
<span id="cb18-77">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"A package in two fields, and one in Depends:"</span>)</span>
<span id="cb18-78">  desc<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">desc_set_dep</span>(<span class="st" style="color: #20794D;">"rlang"</span>, <span class="st" style="color: #20794D;">"Suggests"</span>, <span class="at" style="color: #657422;">file =</span> path)</span>
<span id="cb18-79">  desc<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">desc_set_dep</span>(<span class="st" style="color: #20794D;">"dplyr"</span>, <span class="st" style="color: #20794D;">"Depends"</span>, <span class="at" style="color: #657422;">file =</span> path)</span>
<span id="cb18-80">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">dependency_problems</span>(path))</span>
<span id="cb18-81"></span>
<span id="cb18-82">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"A suggested package that is installed:"</span>)</span>
<span id="cb18-83">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">markdown_table</span>(<span class="fu" style="color: #4758AB;">head</span>(mtcars[, <span class="dv" style="color: #AD0000;">1</span><span class="sc" style="color: #5E5E5E;">:</span><span class="dv" style="color: #AD0000;">3</span>], <span class="dv" style="color: #AD0000;">3</span>)))</span>
<span id="cb18-84"></span>
<span id="cb18-85">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"A suggested package that is not installed:"</span>)</span>
<span id="cb18-86">  <span class="fu" style="color: #4758AB;">tryCatch</span>(</span>
<span id="cb18-87">    <span class="fu" style="color: #4758AB;">check_suggested</span>(<span class="st" style="color: #20794D;">"notarealpkg"</span>, <span class="st" style="color: #20794D;">"to run this example"</span>),</span>
<span id="cb18-88">    <span class="at" style="color: #657422;">error =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(e) {</span>
<span id="cb18-89">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">conditionMessage</span>(e), <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-90">    }</span>
<span id="cb18-91">  )</span>
<span id="cb18-92">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards &amp; R manuals</strong></p>
<ul>
<li><strong>R Validation Hub, risk-based package assessment white paper (§6.1):</strong> <a href="https://pharmar.org/white-paper/">pharmar.org/white-paper</a></li>
<li><strong>Writing R Extensions (§1.1.3 Package Dependencies):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Package-Dependencies">cran.r-project.org/doc/manuals/r-release/R-exts.html#Package-Dependencies</a></li>
<li><strong>Writing R Extensions (§1.1.3.1 Suggested packages):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Suggested-packages">cran.r-project.org/doc/manuals/r-release/R-exts.html#Suggested-packages</a></li>
<li><strong>Writing R Extensions (§1.5.1 Specifying imports and exports):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Specifying-imports-and-exports">cran.r-project.org/doc/manuals/r-release/R-exts.html#Specifying-imports-and-exports</a></li>
</ul>
<p><strong>R package development guides</strong></p>
<ul>
<li><strong>R Packages (2e), Dependencies: Mindset and Background:</strong> <a href="https://r-pkgs.org/dependencies-mindset-background.html">r-pkgs.org/dependencies-mindset-background.html</a></li>
<li><strong>R Packages (2e), Dependencies: In Practice:</strong> <a href="https://r-pkgs.org/dependencies-in-practice.html">r-pkgs.org/dependencies-in-practice.html</a></li>
<li><strong>roxygen2, Managing imports and exports:</strong> <a href="https://roxygen2.r-lib.org/articles/namespace.html">roxygen2.r-lib.org/articles/namespace.html</a></li>
<li><strong>roxygen2 NEWS (8.1.0 importFrom directive formatting):</strong> <a href="https://roxygen2.r-lib.org/news/index.html">roxygen2.r-lib.org/news/index.html</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>cli:</strong> <a href="https://cli.r-lib.org/">cli.r-lib.org</a> · <a href="https://cran.r-project.org/package=cli">CRAN page</a></li>
<li><strong>cpp11:</strong> <a href="https://cran.r-project.org/package=cpp11">CRAN page</a></li>
<li><strong>desc:</strong> <a href="https://desc.r-lib.org/">desc.r-lib.org</a> · <a href="https://cran.r-project.org/package=desc">CRAN page</a></li>
<li><strong>devtools:</strong> <a href="https://cran.r-project.org/package=devtools">CRAN page</a></li>
<li><strong>dplyr:</strong> <a href="https://cran.r-project.org/package=dplyr">CRAN page</a></li>
<li><strong>knitr:</strong> <a href="https://yihui.org/knitr/">yihui.org/knitr</a> · <a href="https://cran.r-project.org/package=knitr">CRAN page</a></li>
<li><strong>pak:</strong> <a href="https://cran.r-project.org/package=pak">CRAN page</a></li>
<li><strong>pkgload:</strong> <a href="https://pkgload.r-lib.org/">pkgload.r-lib.org</a> · <a href="https://cran.r-project.org/package=pkgload">CRAN page</a></li>
<li><strong>rcmdcheck:</strong> <a href="https://rcmdcheck.r-lib.org/">rcmdcheck.r-lib.org</a> · <a href="https://cran.r-project.org/package=rcmdcheck">CRAN page</a></li>
<li><strong>Rcpp:</strong> <a href="https://cran.r-project.org/package=Rcpp">CRAN page</a></li>
<li><strong>rlang:</strong> <a href="https://rlang.r-lib.org/">rlang.r-lib.org</a> · <a href="https://cran.r-project.org/package=rlang">CRAN page</a></li>
<li><strong>roxygen2:</strong> <a href="https://roxygen2.r-lib.org/">roxygen2.r-lib.org</a> · <a href="https://cran.r-project.org/package=roxygen2">CRAN page</a></li>
<li><strong>stats:</strong> <a href="https://search.r-project.org/R/refmans/stats/html/00Index.html">R reference</a></li>
<li><strong>testthat:</strong> <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a> · <a href="https://cran.r-project.org/package=testthat">CRAN page</a></li>
<li><strong>tools:</strong> <a href="https://search.r-project.org/R/refmans/tools/html/00Index.html">R reference</a></li>
<li><strong>usethis:</strong> <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a> · <a href="https://cran.r-project.org/package=usethis">CRAN page</a></li>
<li><strong>withr:</strong> <a href="https://withr.r-lib.org/">withr.r-lib.org</a> · <a href="https://cran.r-project.org/package=withr">CRAN page</a></li>
</ul>
<p><strong>Comparative packaging standards</strong></p>
<ul>
<li><strong>Node.js, File system promises API:</strong> <a href="https://nodejs.org/api/fs.html#promises-api">nodejs.org/api/fs.html</a></li>
<li><strong>npm package.json specification:</strong> <a href="https://docs.npmjs.com/cli/v11/configuring-npm/package-json">docs.npmjs.com/cli/v11/configuring-npm/package-json</a></li>
<li><strong>Python language reference, imports:</strong> <a href="https://docs.python.org/3/reference/import.html">docs.python.org/3/reference/import.html</a></li>
<li><strong>Python Packaging User Guide (pyproject.toml):</strong> <a href="https://packaging.python.org/en/latest/guides/writing-pyproject-toml/">packaging.python.org/en/latest/guides/writing-pyproject-toml</a></li>
</ul>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/package-dev.html" class="site-series-nav__series">R package development series · part 3 of 4</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 2</span><span class="site-related-card__title">The package development loop and R CMD check</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/roxygen2-documentation/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 4</span><span class="site-related-card__title">Documenting functions with roxygen2</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html" class="site-link-row" title="Manage dependencies through lockfiles, runtime pinning, and package vetting for reproducible R environments."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Dependency updates, runtime pinning &amp; package vetting</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/index.html" class="site-link-row" title="The mascot package is now on CRAN: add mood-driven characters to Shiny apps and Quarto pages, with visible status text, speech bubbles, click menus and reduced-motion support."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">mascot is on CRAN: live, mood-driven mascots for Shiny and Quarto</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R packages</category>
  <category>R</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/package-dependencies-namespace/</guid>
  <pubDate>Mon, 28 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Documenting functions with roxygen2</title>
  <link>https://insightsurge-dev.web.app/posts/roxygen2-documentation/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem-documentation-that-drifts" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-documentation-that-drifts">The problem: documentation that drifts</h2>
<p>In analysis scripts and informal collections of helper functions, documentation is rarely more than a comment header or a separate specification document. As analysis requirements evolve, arguments are added, default values change, and return structures are refactored. That separate document, stored in a shared directory or wiki, rarely keeps pace.</p>
<p>When a team moves those functions into an R package, the consequence becomes immediate: typing <code>?format_n_pct</code> in the console prints <code>No documentation for ‘format_n_pct’ in specified packages and libraries</code>. R stores package help pages as <code>.Rd</code> files in <code>man/</code>. For a documented function, a generated page commonly contains <code>\name</code>, <code>\alias</code>, <code>\title</code>, <code>\description</code>, <code>\usage</code>, <code>\arguments</code>, <code>\value</code>, and <code>\examples</code>. These sections are not all mandatory; <code>R CMD check</code> separately checks exported functions for missing documentation and compares documented arguments with the function usage:</p>
<pre class="text"><code>\name{format_n_pct}
\alias{format_n_pct}
\title{Format a count and percentage}
\usage{
format_n_pct(n, denom, digits = 1)
}
\arguments{
\item{n}{Numeric vector of counts.}
\item{denom}{Denominator: a single positive finite number.}
\item{digits}{Non-negative whole number of decimal places.}
}
\value{
A character vector the same length as \code{n}.
}
\description{
Formats counts and percentages for summary tables.
}</code></pre>
<p>Hand-written Rd files create a dual-maintenance problem: A change to a function’s arguments requires the corresponding usage and argument documentation to stay aligned. A change to what the package exports also requires the <code>NAMESPACE</code> directives to stay aligned. <code>R CMD check</code> reports undocumented arguments, and an unexported function cannot be called by users with the <code>pkg::fun()</code> syntax.</p>
<p>In regulated work, stale help pages make review harder. The <code>{riskmetric}</code> assessments assess whether exported values have help entries and whether function documentation contains example or usage fields (see <a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html">validation-ready R packages</a>). Those presence checks do not show that the examples run or that the help text matches the implementation.</p>
</section>
<section id="the-web-repo-way-generated-from-source" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-generated-from-source">The web-repo way: generated from source</h2>
<p>One way to reduce documentation drift is to keep documentation beside the code it describes.</p>
<p>In JavaScript and TypeScript repositories, developers place JSDoc comments (<code>/** ... */</code>) directly above function definitions. Tags such as <code>@param</code>, <code>@returns</code>, and <code>@example</code> declare metadata that tools like TypeDoc compile into reference documentation. In Python, PEP 257 standardises docstrings embedded directly inside function bodies. Tools such as Sphinx’s <code>autodoc</code> extract these docstrings to build API documentation sites. Python’s <code>doctest</code> module goes further: it parses interactive sessions in docstrings and executes them, verifying that code runs and matches recorded output.</p>
<p>Both workflows keep human-written documentation close to the code and can generate reference pages from it. Verification is a separate step: Python’s <code>doctest</code> can execute examples and compare output, while TypeDoc turns comments into reference documentation.</p>
<p>In R, <code>{roxygen2}</code> implements this workflow. You write structured comment blocks directly above function definitions in <code>R/</code>, and <code>devtools::document()</code> compiles them into <code>man/*.Rd</code> files and <code>NAMESPACE</code> export directives. One distinction from Python’s <code>doctest</code> is that <code>R CMD check</code> executes examples and halts on unhandled errors, but it does not compare console print output to expected text unless the package ships a reference file, <code>tests/Examples/&lt;pkg&gt;-Ex.Rout.save</code> (<em>Writing R Extensions</em>, §1.3.1).</p>
</section>
<section id="the-r-way-roxygen2-blocks-and-the-compilation-loop" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-roxygen2-blocks-and-the-compilation-loop">The R way: roxygen2 blocks and the compilation loop</h2>
<section id="anatomy-of-a-roxygen-block" class="level3">
<h3 class="anchored" data-anchor-id="anatomy-of-a-roxygen-block">Anatomy of a roxygen block</h3>
<p>A roxygen block sits immediately before a function definition. Each line begins with the comment prefix <code>#'</code>. The block uses specific tags to populate the corresponding sections of the generated Rd file:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">check_digits <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(digits) {</span>
<span id="cb2-2">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.numeric</span>(digits) <span class="sc" style="color: #5E5E5E;">||</span> <span class="fu" style="color: #4758AB;">length</span>(digits) <span class="sc" style="color: #5E5E5E;">!=</span> <span class="dv" style="color: #AD0000;">1</span>L <span class="sc" style="color: #5E5E5E;">||</span></span>
<span id="cb2-3">      <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.finite</span>(digits) <span class="sc" style="color: #5E5E5E;">||</span> digits <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">||</span> digits <span class="sc" style="color: #5E5E5E;">!=</span> <span class="fu" style="color: #4758AB;">floor</span>(digits)) {</span>
<span id="cb2-4">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`digits` must be a single non-negative whole number."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb2-5">  }</span>
<span id="cb2-6">  <span class="fu" style="color: #4758AB;">invisible</span>(<span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb2-7">}</span>
<span id="cb2-8"></span>
<span id="cb2-9"><span class="co" style="color: #5E5E5E;">#' Format a count and percentage</span></span>
<span id="cb2-10"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb2-11"><span class="co" style="color: #5E5E5E;">#' Formats `n` out of `denom` as `"n (pct%)"`, the way counts appear</span></span>
<span id="cb2-12"><span class="co" style="color: #5E5E5E;">#' in a summary table.</span></span>
<span id="cb2-13"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb2-14"><span class="co" style="color: #5E5E5E;">#' @param n Numeric vector of counts.</span></span>
<span id="cb2-15"><span class="co" style="color: #5E5E5E;">#' @param denom Denominator: a single positive finite number.</span></span>
<span id="cb2-16"><span class="co" style="color: #5E5E5E;">#' @param digits Non-negative whole number of decimal places.</span></span>
<span id="cb2-17"><span class="co" style="color: #5E5E5E;">#' @returns A character vector the same length as `n`.</span></span>
<span id="cb2-18"><span class="co" style="color: #5E5E5E;">#' @family formatting helpers</span></span>
<span id="cb2-19"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb2-20"><span class="co" style="color: #5E5E5E;">#' @examples</span></span>
<span id="cb2-21"><span class="co" style="color: #5E5E5E;">#' format_n_pct(c(12, 30), denom = 86)</span></span>
<span id="cb2-22"><span class="co" style="color: #5E5E5E;">#' format_n_pct(5, denom = 86, digits = 0)</span></span>
<span id="cb2-23">format_n_pct <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(n, denom, <span class="at" style="color: #657422;">digits =</span> <span class="dv" style="color: #AD0000;">1</span>) {</span>
<span id="cb2-24">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.numeric</span>(denom) <span class="sc" style="color: #5E5E5E;">||</span> <span class="fu" style="color: #4758AB;">length</span>(denom) <span class="sc" style="color: #5E5E5E;">!=</span> <span class="dv" style="color: #AD0000;">1</span>L <span class="sc" style="color: #5E5E5E;">||</span></span>
<span id="cb2-25">      <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.finite</span>(denom) <span class="sc" style="color: #5E5E5E;">||</span> denom <span class="sc" style="color: #5E5E5E;">&lt;=</span> <span class="dv" style="color: #AD0000;">0</span>) {</span>
<span id="cb2-26">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`denom` must be a single positive finite number."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb2-27">  }</span>
<span id="cb2-28">  <span class="fu" style="color: #4758AB;">check_digits</span>(digits)</span>
<span id="cb2-29">  pct <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">formatC</span>(<span class="dv" style="color: #AD0000;">100</span> <span class="sc" style="color: #5E5E5E;">*</span> n <span class="sc" style="color: #5E5E5E;">/</span> denom, <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"f"</span>, <span class="at" style="color: #657422;">digits =</span> digits)</span>
<span id="cb2-30">  <span class="fu" style="color: #4758AB;">paste0</span>(n, <span class="st" style="color: #20794D;">" ("</span>, pct, <span class="st" style="color: #20794D;">"%)"</span>)</span>
<span id="cb2-31">}</span>
<span id="cb2-32"></span>
<span id="cb2-33"><span class="fu" style="color: #4758AB;">format_n_pct</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">12</span>, <span class="dv" style="color: #AD0000;">30</span>), <span class="at" style="color: #657422;">denom =</span> <span class="dv" style="color: #AD0000;">86</span>)</span></code></pre></div></div>
<p>The roxygen parser maps this structure to Rd elements:</p>
<ul>
<li><strong>Title:</strong> The first sentence or paragraph becomes <code>\title{...}</code>.</li>
<li><strong>Description:</strong> The second paragraph becomes <code>\description{...}</code>. If you omit the second paragraph, roxygen2 reuses the title as the description.</li>
<li><strong><code>@param name Description</code>:</strong> Defines an argument in the <code>\arguments{}</code> section. Roxygen2 inspects <code>formals(fun)</code> to generate the <code>\usage{}</code> line automatically, including default arguments.</li>
<li><strong><code>@returns</code> (or <code>@return</code>):</strong> Documents the return object type and structure in <code>\value{...}</code>. <em>R Packages (2e)</em> uses <code>@returns</code>.</li>
<li><strong><code>@export</code>:</strong> Directs roxygen2 to write <code>export(format_n_pct)</code> to <code>NAMESPACE</code>. Functions without <code>@export</code> remain internal to the package.</li>
<li><strong><code>@examples</code>:</strong> Contains executable R code demonstrating typical usage.</li>
</ul>
</section>
<section id="what-document-writes" class="level3">
<h3 class="anchored" data-anchor-id="what-document-writes">What <code>document()</code> writes</h3>
<p>To compile roxygen comments into package documentation, run <code>devtools::document()</code>, which delegates to <code>roxygen2::roxygenise()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">devtools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">document</span>()</span></code></pre></div></div>
<p>This command parses all files in <code>R/</code> and updates two build artifacts:</p>
<ol type="1">
<li><strong><code>man/format_n_pct.Rd</code>:</strong> The generated manual file:</li>
</ol>
<pre class="text"><code>% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/format.R
\name{format_n_pct}
\alias{format_n_pct}
\title{Format a count and percentage}
\usage{
format_n_pct(n, denom, digits = 1)
}
\arguments{
\item{n}{Numeric vector of counts.}

\item{denom}{Denominator: a single positive finite number.}

\item{digits}{Non-negative whole number of decimal places.}
}
\value{
A character vector the same length as \code{n}.
}
\description{
Formats \code{n} out of \code{denom} as \code{"n (pct\%)"}, the way counts appear
in a summary table.
}
\examples{
format_n_pct(c(12, 30), denom = 86)
format_n_pct(5, denom = 86, digits = 0)
}
\seealso{
Other formatting helpers:
\code{\link[=format_mean_sd]{format_mean_sd()}}
}
\concept{formatting helpers}</code></pre>
<ol start="2" type="1">
<li><strong><code>NAMESPACE</code>:</strong> Adds the export entry:</li>
</ol>
<pre class="text"><code># Generated by roxygen2: do not edit by hand

export(format_mean_sd)
export(format_n_pct)</code></pre>
<p>Both files begin with an explicit header: <code>% Generated by roxygen2: do not edit by hand</code> or <code># Generated by roxygen2: do not edit by hand</code>. Any manual modifications made directly to these files will be overwritten on the next call to <code>devtools::document()</code>.</p>
<p>If you have pre-existing manual documentation files that lack the roxygen header, roxygen2 will not overwrite them. It displays a message such as <code>Skipping NAMESPACE: It already exists and was not generated by roxygen2</code>, ensuring hand-crafted configuration is protected until you choose to opt in.</p>
</section>
<section id="markdown-in-roxygen-blocks" class="level3">
<h3 class="anchored" data-anchor-id="markdown-in-roxygen-blocks">Markdown in roxygen blocks</h3>
<p>In early versions of roxygen2, text formatting required raw Rd commands (<code>\code{...}</code>, <code>\emph{...}</code>, <code>\link{...}</code>). Modern roxygen2 supports standard Markdown formatting:</p>
<ul>
<li>Inline code: <code>`formatC()`</code> becomes <code>\code{formatC()}</code>.</li>
<li>Function links: <code>[formatC()]</code> generates <code>\code{\link[=formatC]{formatC()}}</code>.</li>
<li>Text emphasis: <code>**bold**</code> becomes <code>\strong{bold}</code> and <code>*italic*</code> becomes <code>\emph{italic}</code>.</li>
<li>Lists and sections: Markdown bullet lists and headings (<code>## Details</code>) translate directly to Rd.</li>
</ul>
<p>Markdown processing is <strong>disabled by default</strong> in the core <code>roxygen2::roxygenise()</code> engine. When you initialise a package with <code>usethis::create_package()</code>, usethis enables it by inserting this line in <code>DESCRIPTION</code>:</p>
<pre class="text"><code>Roxygen: list(markdown = TRUE)</code></pre>
<p>In roxygen2 8.x, configuration fields can also be specified using the <code>Config/roxygen2/</code> prefix. The vignette <code>vignette("rd-formatting")</code> documents the equivalent field:</p>
<pre class="text"><code>Config/roxygen2/markdown: TRUE</code></pre>
<p>If neither field is present in <code>DESCRIPTION</code>, backticks and Markdown links are left as literal characters in the <code>.Rd</code> output.</p>
</section>
<section id="tags-that-reduce-repetition" class="level3">
<h3 class="anchored" data-anchor-id="tags-that-reduce-repetition">Tags that reduce repetition</h3>
<p>Roxygen provides several tags designed to eliminate duplicated documentation across related functions:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="co" style="color: #5E5E5E;">#' Format a mean and standard deviation</span></span>
<span id="cb8-2"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb8-3"><span class="co" style="color: #5E5E5E;">#' Formats sample mean and standard deviation as `"mean (sd)"`.</span></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb8-5"><span class="co" style="color: #5E5E5E;">#' @param x Numeric vector of observations.</span></span>
<span id="cb8-6"><span class="co" style="color: #5E5E5E;">#' @inheritParams format_n_pct</span></span>
<span id="cb8-7"><span class="co" style="color: #5E5E5E;">#' @returns A character string of the form `"mean (sd)"`.</span></span>
<span id="cb8-8"><span class="co" style="color: #5E5E5E;">#' @family formatting helpers</span></span>
<span id="cb8-9"><span class="co" style="color: #5E5E5E;">#' @seealso [formatC()] for the underlying number formatting.</span></span>
<span id="cb8-10"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb8-11"><span class="co" style="color: #5E5E5E;">#' @examplesIf interactive()</span></span>
<span id="cb8-12"><span class="co" style="color: #5E5E5E;">#' format_mean_sd(c(64, 71, 80))</span></span>
<span id="cb8-13">format_mean_sd <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x, <span class="at" style="color: #657422;">digits =</span> <span class="dv" style="color: #AD0000;">1</span>) {</span>
<span id="cb8-14">  <span class="fu" style="color: #4758AB;">check_digits</span>(digits)</span>
<span id="cb8-15">  m <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">formatC</span>(<span class="fu" style="color: #4758AB;">mean</span>(x, <span class="at" style="color: #657422;">na.rm =</span> <span class="cn" style="color: #8f5902;">TRUE</span>), <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"f"</span>, <span class="at" style="color: #657422;">digits =</span> digits)</span>
<span id="cb8-16">  s <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">formatC</span>(stats<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">sd</span>(x, <span class="at" style="color: #657422;">na.rm =</span> <span class="cn" style="color: #8f5902;">TRUE</span>), <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"f"</span>, <span class="at" style="color: #657422;">digits =</span> digits)</span>
<span id="cb8-17">  <span class="fu" style="color: #4758AB;">paste0</span>(m, <span class="st" style="color: #20794D;">" ("</span>, s, <span class="st" style="color: #20794D;">")"</span>)</span>
<span id="cb8-18">}</span>
<span id="cb8-19"></span>
<span id="cb8-20"><span class="fu" style="color: #4758AB;">format_mean_sd</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">64</span>, <span class="dv" style="color: #AD0000;">71</span>, <span class="dv" style="color: #AD0000;">80</span>))</span></code></pre></div></div>
<ul>
<li><strong><code>@inheritParams source_fun</code>:</strong> Copies parameter descriptions from <code>source_fun</code> for any argument present in both functions (here, <code>digits</code>). Because the text is copied verbatim, write the source parameter description generically so it fits all inheriting functions.</li>
<li><strong><code>@family family_name</code>:</strong> Groups related functions together. Roxygen2 adds an entry to the <code>\seealso{}</code> section of each family member linking to all other family members (under <code>Other family_name:</code>), and adds a <code>\concept{family_name}</code> index entry.</li>
<li><strong><code>@seealso [target()]</code>:</strong> Links to a related function. For a function in another package, write <code>[pkg::fun()]</code> when package inference is ambiguous.</li>
<li><strong><code>@noRd</code>:</strong> Tells roxygen2 not to generate an <code>.Rd</code> file. Use <code>@noRd</code> on internal helper functions (such as <code>check_digits()</code>) so developers have structured comments without cluttering the package’s public help index. Internal helpers should not have <code>@export</code>.</li>
</ul>
</section>
<section id="examples-are-executable-documentation" class="level3">
<h3 class="anchored" data-anchor-id="examples-are-executable-documentation">Examples are executable documentation</h3>
<p>Examples demonstrate API usage and are run during <code>R CMD check</code> when their conditions allow it. An unhandled error in an executed example makes the check fail. A condition such as <code>@examplesIf interactive()</code> skips its body during a noninteractive check; ordinary examples do not assert their printed result unless the package supplies a reference output file. Use tests for assertions about return values.</p>
<p>If an example throws an unhandled error during check execution, <code>R CMD check</code> fails with <code>ERROR</code>:</p>
<pre class="text"><code>* checking examples ... ERROR
Running examples in ‘tflformat-Ex.R’ failed
The error most likely occurred in:

&gt; format_n_pct(5, denom = 86, digits = -1)
Error: `digits` must be a single non-negative whole number.
Execution halted</code></pre>
<p>To maintain informative examples while keeping package checks clean, follow these guidelines:</p>
<ol type="1">
<li><strong>Demonstrate expected errors with <code>try()</code>:</strong> When showing users how input validation works, wrap the call in <code>try()</code>:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="co" style="color: #5E5E5E;"># Demonstrates error handling without stopping check execution</span></span>
<span id="cb10-2"><span class="fu" style="color: #4758AB;">try</span>(<span class="fu" style="color: #4758AB;">format_n_pct</span>(<span class="dv" style="color: #AD0000;">5</span>, <span class="at" style="color: #657422;">denom =</span> <span class="dv" style="color: #AD0000;">86</span>, <span class="at" style="color: #657422;">digits =</span> <span class="sc" style="color: #5E5E5E;">-</span><span class="dv" style="color: #AD0000;">1</span>))</span></code></pre></div></div>
<ol start="2" type="1">
<li><strong>Conditional execution with <code>@examplesIf</code>:</strong> If an example requires interactive execution, an internet connection, or an environment variable (such as a database URL), guard it with <code>@examplesIf</code>:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="co" style="color: #5E5E5E;">#' @examplesIf interactive()</span></span>
<span id="cb11-2"><span class="co" style="color: #5E5E5E;">#' format_mean_sd(c(64, 71, 80))</span></span></code></pre></div></div>
<p>In roxygen2 8.1.0, this wraps the example in the Rd file as:</p>
<pre class="text"><code>\dontshow{if (interactive()) withAutoprint(\{ # examplesIf}
format_mean_sd(c(64, 71, 80))
\dontshow{\}) # examplesIf}</code></pre>
<p>This formatting call is gated only to illustrate the tag; it has no interactive dependency. In a real package, give such a call an ordinary <code>@examples</code> tag so it runs during checks.</p>
<ol start="3" type="1">
<li><strong>Avoid <code>\donttest{}</code> as a hiding place:</strong> A common misconception is that wrapping slow or fragile code in <code>\donttest{}</code> prevents check failures. While base <code>R CMD check</code> skips <code>\donttest{}</code> by default, <code>R CMD check --as-cran</code> executes all <code>\donttest{}</code> examples. Because <code>devtools::check()</code> passes <code>--as-cran</code> by default (<code>cran = TRUE</code>), <code>\donttest{}</code> blocks are run during your standard development check.</li>
<li><strong>Reserve <code>\dontrun{}</code> for non-runnable code:</strong> <code>\dontrun{}</code> comments out example code during extraction. Reserve it strictly for code that cannot run in an automated environment, such as examples requiring interactive file selectors or external hardware tokens.</li>
</ol>
</section>
</section>
<section id="pitfalls-and-roxygen2-8.x-gotchas" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-and-roxygen2-8.x-gotchas">Pitfalls and roxygen2 8.x gotchas</h2>
<section id="missing-param-tags-are-not-flagged-by-roxygen2" class="level3">
<h3 class="anchored" data-anchor-id="missing-param-tags-are-not-flagged-by-roxygen2">1. Missing <code>@param</code> tags are not flagged by roxygen2</h3>
<p>If you add a new argument to a function signature but forget to write a corresponding <code>@param</code> tag, <code>roxygen2::roxygenise()</code> completes silently without reporting any problem. It generates the <code>.Rd</code> file with the missing parameter omitted from <code>\arguments{}</code>.</p>
<p>The failure only appears later, when running <code>R CMD check</code>:</p>
<pre class="text"><code>* checking Rd \usage sections ... WARNING
Undocumented arguments in Rd file 'format_n_pct.Rd'
  ‘denom’
Functions with \usage entries need to have the corresponding
\arguments.</code></pre>
<p>To catch undocumented arguments early in development without running a full package check, call <code>tools::checkDocFiles()</code> directly:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb14-1">tools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">checkDocFiles</span>(<span class="at" style="color: #657422;">dir =</span> <span class="st" style="color: #20794D;">"."</span>)</span></code></pre></div></div>
</section>
<section id="devtoolscheck-may-skip-documenting" class="level3">
<h3 class="anchored" data-anchor-id="devtoolscheck-may-skip-documenting">2. <code>devtools::check()</code> may skip documenting</h3>
<p>With roxygen2 8.x, new packages record <code>Config/roxygen2/version</code> instead of <code>RoxygenNote</code>, and devtools 2.5.2 then skips its automatic <code>document()</code> step without saying so. Run <code>devtools::document()</code> before <code>devtools::check()</code>, or use <code>check(document = TRUE)</code>; the <a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html">previous post</a> shows the details.</p>
<p>You can also check whether documentation is stale with <code>roxygen2::needs_roxygenize()</code>, which compares the modification times of <code>.Rd</code> files with the source files they were generated from.</p>
</section>
<section id="combining-export-with-nord-produces-undocumented-objects" class="level3">
<h3 class="anchored" data-anchor-id="combining-export-with-nord-produces-undocumented-objects">3. Combining <code>@export</code> with <code>@noRd</code> produces undocumented objects</h3>
<p>If you tag a helper function with <code>@export</code> and <code>@noRd</code>, roxygen2 adds the function to <code>NAMESPACE</code> but writes no <code>.Rd</code> file. In <code>R CMD check</code>, this triggers a WARNING:</p>
<pre class="text"><code>* checking for missing documentation entries ... WARNING
Undocumented code objects:
  ‘helper_fn’
All user-level objects in a package should have documentation entries.</code></pre>
<p>If a function is exported, it must have reference documentation. If a function is an internal implementation detail, use <code>@noRd</code> and omit <code>@export</code>.</p>
</section>
<section id="first-run-link-resolution-messages" class="level3">
<h3 class="anchored" data-anchor-id="first-run-link-resolution-messages">4. First-run link resolution messages</h3>
<p>When you add a Markdown link in <code>@seealso</code> to another function in the same package (such as <code>[format_mean_sd()]</code>), the first run of <code>devtools::document()</code> on a clean package may display an informational message:</p>
<pre class="text"><code>✖ format.R:27: @seealso Could not resolve link to topic "format_mean_sd".
ℹ If this is an in-package link, this is normal. Once "format_mean_sd" is documented, this warning goes away.</code></pre>
<p>This is expected behavior. On the initial pass, roxygen2 evaluates links before the destination <code>.Rd</code> file exists on disk. On the second pass, once the destination topic has been indexed, roxygen2 resolves the cross-reference without messages.</p>
</section>
<section id="keeping-generated-files-synchronized" class="level3">
<h3 class="anchored" data-anchor-id="keeping-generated-files-synchronized">5. Keeping generated files synchronized</h3>
<p>Documentation drift occurs when developers modify code in <code>R/</code> but forget to run <code>devtools::document()</code> before committing changes. The <code>roxygenize</code> hook from <code>{precommit}</code> (described in <a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html">hooks, formatting, and linting</a>) runs <code>roxygen2::roxygenise()</code> before a commit. If it changes <code>.Rd</code> or <code>NAMESPACE</code> files, the hook fails that attempt; review and stage the generated changes, then retry the commit.</p>
</section>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/roxygen2-documentation/scripts/roxygen-demo.R">View <code>roxygen-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/roxygen2-documentation/scripts/roxygen-demo.R" download="roxygen-demo.R">Download</a></p>
<p>Creates a temporary R package with documented formatting helpers, runs <code>roxygen2::roxygenise()</code>, inspects generated <code>.Rd</code> files and <code>NAMESPACE</code> exports, tests conditional example extraction, and demonstrates how missing parameter tags are caught by <code>tools::checkDocFiles()</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>roxygen-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1"><span class="co" style="color: #5E5E5E;"># Demonstrate function documentation with roxygen2 in a minimal package.</span></span>
<span id="cb17-2"><span class="co" style="color: #5E5E5E;"># Run from the project root:</span></span>
<span id="cb17-3"><span class="co" style="color: #5E5E5E;">#   Rscript posts/roxygen2-documentation/scripts/roxygen-demo.R</span></span>
<span id="cb17-4"></span>
<span id="cb17-5">demo_source <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb17-6">  <span class="st" style="color: #20794D;">"#' Format a count and percentage"</span>,</span>
<span id="cb17-7">  <span class="st" style="color: #20794D;">"#'"</span>,</span>
<span id="cb17-8">  <span class="st" style="color: #20794D;">"#' Formats `n` out of `denom` as `</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">n (pct%)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">`, the way counts appear"</span>,</span>
<span id="cb17-9">  <span class="st" style="color: #20794D;">"#' in a summary table."</span>,</span>
<span id="cb17-10">  <span class="st" style="color: #20794D;">"#'"</span>,</span>
<span id="cb17-11">  <span class="st" style="color: #20794D;">"#' @param n Numeric vector of counts."</span>,</span>
<span id="cb17-12">  <span class="st" style="color: #20794D;">"#' @param denom Denominator: a single positive finite number."</span>,</span>
<span id="cb17-13">  <span class="st" style="color: #20794D;">"#' @param digits Non-negative whole number of decimal places."</span>,</span>
<span id="cb17-14">  <span class="st" style="color: #20794D;">"#' @returns A character vector the same length as `n`."</span>,</span>
<span id="cb17-15">  <span class="st" style="color: #20794D;">"#' @family formatting helpers"</span>,</span>
<span id="cb17-16">  <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb17-17">  <span class="st" style="color: #20794D;">"#' @examples"</span>,</span>
<span id="cb17-18">  <span class="st" style="color: #20794D;">"#' format_n_pct(c(12, 30), denom = 86)"</span>,</span>
<span id="cb17-19">  <span class="st" style="color: #20794D;">"#' format_n_pct(5, denom = 86, digits = 0)"</span>,</span>
<span id="cb17-20">  <span class="st" style="color: #20794D;">"format_n_pct &lt;- function(n, denom, digits = 1) {"</span>,</span>
<span id="cb17-21">  <span class="st" style="color: #20794D;">"  if (!is.numeric(denom) || length(denom) != 1L ||"</span>,</span>
<span id="cb17-22">  <span class="st" style="color: #20794D;">"      !is.finite(denom) || denom &lt;= 0) {"</span>,</span>
<span id="cb17-23">  <span class="st" style="color: #20794D;">"    stop(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">`denom` must be a single positive finite number.</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, call. = FALSE)"</span>,</span>
<span id="cb17-24">  <span class="st" style="color: #20794D;">"  }"</span>,</span>
<span id="cb17-25">  <span class="st" style="color: #20794D;">"  check_digits(digits)"</span>,</span>
<span id="cb17-26">  <span class="st" style="color: #20794D;">"  pct &lt;- formatC(100 * n / denom, format = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">f</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, digits = digits)"</span>,</span>
<span id="cb17-27">  <span class="st" style="color: #20794D;">"  paste0(n, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;"> (</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, pct, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">%)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb17-28">  <span class="st" style="color: #20794D;">"}"</span>,</span>
<span id="cb17-29">  <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb17-30">  <span class="st" style="color: #20794D;">"#' Format a mean and standard deviation"</span>,</span>
<span id="cb17-31">  <span class="st" style="color: #20794D;">"#'"</span>,</span>
<span id="cb17-32">  <span class="st" style="color: #20794D;">"#' @param x Numeric vector."</span>,</span>
<span id="cb17-33">  <span class="st" style="color: #20794D;">"#' @inheritParams format_n_pct"</span>,</span>
<span id="cb17-34">  <span class="st" style="color: #20794D;">"#' @returns A character string of the form `</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">mean (sd)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">`."</span>,</span>
<span id="cb17-35">  <span class="st" style="color: #20794D;">"#' @family formatting helpers"</span>,</span>
<span id="cb17-36">  <span class="st" style="color: #20794D;">"#' @seealso [formatC()] for the underlying number formatting."</span>,</span>
<span id="cb17-37">  <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb17-38">  <span class="st" style="color: #20794D;">"#' @examplesIf interactive()"</span>,</span>
<span id="cb17-39">  <span class="st" style="color: #20794D;">"#' format_mean_sd(c(64, 71, 80))"</span>,</span>
<span id="cb17-40">  <span class="st" style="color: #20794D;">"format_mean_sd &lt;- function(x, digits = 1) {"</span>,</span>
<span id="cb17-41">  <span class="st" style="color: #20794D;">"  check_digits(digits)"</span>,</span>
<span id="cb17-42">  <span class="st" style="color: #20794D;">"  m &lt;- formatC(mean(x, na.rm = TRUE), format = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">f</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, digits = digits)"</span>,</span>
<span id="cb17-43">  <span class="st" style="color: #20794D;">"  s &lt;- formatC(stats::sd(x, na.rm = TRUE), format = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">f</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, digits = digits)"</span>,</span>
<span id="cb17-44">  <span class="st" style="color: #20794D;">"  paste0(m, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;"> (</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, s, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb17-45">  <span class="st" style="color: #20794D;">"}"</span>,</span>
<span id="cb17-46">  <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb17-47">  <span class="st" style="color: #20794D;">"#' Validate digits argument"</span>,</span>
<span id="cb17-48">  <span class="st" style="color: #20794D;">"#' @noRd"</span>,</span>
<span id="cb17-49">  <span class="st" style="color: #20794D;">"check_digits &lt;- function(digits) {"</span>,</span>
<span id="cb17-50">  <span class="st" style="color: #20794D;">"  if (!is.numeric(digits) || length(digits) != 1L ||"</span>,</span>
<span id="cb17-51">  <span class="st" style="color: #20794D;">"      !is.finite(digits) || digits &lt; 0 || digits != floor(digits)) {"</span>,</span>
<span id="cb17-52">  <span class="st" style="color: #20794D;">"    stop(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">`digits` must be a single non-negative whole number.</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, call. = FALSE)"</span>,</span>
<span id="cb17-53">  <span class="st" style="color: #20794D;">"  }"</span>,</span>
<span id="cb17-54">  <span class="st" style="color: #20794D;">"  invisible(TRUE)"</span>,</span>
<span id="cb17-55">  <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb17-56">)</span>
<span id="cb17-57"></span>
<span id="cb17-58">make_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">path =</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"tflformat"</span>)) {</span>
<span id="cb17-59">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(path, <span class="at" style="color: #657422;">rstudio =</span> <span class="cn" style="color: #8f5902;">FALSE</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb17-60">  <span class="fu" style="color: #4758AB;">writeLines</span>(demo_source, <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"format.R"</span>))</span>
<span id="cb17-61">  path</span>
<span id="cb17-62">}</span>
<span id="cb17-63"></span>
<span id="cb17-64">document_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb17-65">  roxygen2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">roxygenise</span>(path)</span>
<span id="cb17-66">  <span class="fu" style="color: #4758AB;">invisible</span>(<span class="fu" style="color: #4758AB;">list.files</span>(<span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"man"</span>), <span class="at" style="color: #657422;">full.names =</span> <span class="cn" style="color: #8f5902;">FALSE</span>))</span>
<span id="cb17-67">}</span>
<span id="cb17-68"></span>
<span id="cb17-69">rd_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path, topic) {</span>
<span id="cb17-70">  <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"man"</span>, <span class="fu" style="color: #4758AB;">paste0</span>(topic, <span class="st" style="color: #20794D;">".Rd"</span>))</span>
<span id="cb17-71">}</span>
<span id="cb17-72"></span>
<span id="cb17-73">rd_arguments <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(file) {</span>
<span id="cb17-74">  parsed <span class="ot" style="color: #003B4F;">&lt;-</span> tools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">parse_Rd</span>(file)</span>
<span id="cb17-75">  args_tag <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">Filter</span>(<span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) <span class="fu" style="color: #4758AB;">attr</span>(x, <span class="st" style="color: #20794D;">"Rd_tag"</span>) <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">arguments"</span>, parsed)</span>
<span id="cb17-76">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(args_tag) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb17-77">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">character</span>())</span>
<span id="cb17-78">  }</span>
<span id="cb17-79">  items <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">Filter</span>(<span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) <span class="fu" style="color: #4758AB;">attr</span>(x, <span class="st" style="color: #20794D;">"Rd_tag"</span>) <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">item"</span>, args_tag[[<span class="dv" style="color: #AD0000;">1</span>]])</span>
<span id="cb17-80">  <span class="fu" style="color: #4758AB;">vapply</span>(items, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(it) <span class="fu" style="color: #4758AB;">as.character</span>(it[[<span class="dv" style="color: #AD0000;">1</span>]]), <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">1</span>))</span>
<span id="cb17-81">}</span>
<span id="cb17-82"></span>
<span id="cb17-83">namespace_exports <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb17-84">  <span class="fu" style="color: #4758AB;">parseNamespaceFile</span>(<span class="fu" style="color: #4758AB;">basename</span>(path), <span class="fu" style="color: #4758AB;">dirname</span>(path))<span class="sc" style="color: #5E5E5E;">$</span>exports</span>
<span id="cb17-85">}</span>
<span id="cb17-86"></span>
<span id="cb17-87">example_code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(file) {</span>
<span id="cb17-88">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">capture.output</span>(tools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">Rd2ex</span>(file))</span>
<span id="cb17-89">  lines[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"^###"</span>, lines) <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="fu" style="color: #4758AB;">nzchar</span>(<span class="fu" style="color: #4758AB;">trimws</span>(lines))]</span>
<span id="cb17-90">}</span>
<span id="cb17-91"></span>
<span id="cb17-92">undocumented_arguments <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb17-93">  tools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">checkDocFiles</span>(<span class="at" style="color: #657422;">dir =</span> path)</span>
<span id="cb17-94">}</span>
<span id="cb17-95"></span>
<span id="cb17-96">drop_param <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path, param) {</span>
<span id="cb17-97">  format_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"format.R"</span>)</span>
<span id="cb17-98">  code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readLines</span>(format_file, <span class="at" style="color: #657422;">warn =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb17-99">  pattern <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">paste0</span>(<span class="st" style="color: #20794D;">"#'</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s+@param</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s+"</span>, param, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">b"</span>)</span>
<span id="cb17-100">  <span class="fu" style="color: #4758AB;">writeLines</span>(code[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">grepl</span>(pattern, code)], format_file)</span>
<span id="cb17-101">}</span>
<span id="cb17-102"></span>
<span id="cb17-103">run_demo <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb17-104">  demo_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"tflformatdemo"</span>)</span>
<span id="cb17-105">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">dir.exists</span>(demo_dir)) {</span>
<span id="cb17-106">    <span class="fu" style="color: #4758AB;">unlink</span>(demo_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb17-107">  }</span>
<span id="cb17-108">  <span class="fu" style="color: #4758AB;">on.exit</span>(<span class="fu" style="color: #4758AB;">unlink</span>(demo_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>), <span class="at" style="color: #657422;">add =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb17-109"></span>
<span id="cb17-110">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"1. Creating demo package..."</span>)</span>
<span id="cb17-111">  <span class="fu" style="color: #4758AB;">make_demo_package</span>(demo_dir)</span>
<span id="cb17-112"></span>
<span id="cb17-113">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"2. Running roxygen2::roxygenise()..."</span>)</span>
<span id="cb17-114">  <span class="fu" style="color: #4758AB;">document_package</span>(demo_dir)</span>
<span id="cb17-115"></span>
<span id="cb17-116">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"3. Generated Rd files in man/:"</span>)</span>
<span id="cb17-117">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">list.files</span>(<span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"man"</span>)))</span>
<span id="cb17-118"></span>
<span id="cb17-119">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"4. NAMESPACE exports:"</span>)</span>
<span id="cb17-120">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">namespace_exports</span>(demo_dir))</span>
<span id="cb17-121"></span>
<span id="cb17-122">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"5. Arguments documented in format_mean_sd.Rd:"</span>)</span>
<span id="cb17-123">  rd_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">rd_file</span>(demo_dir, <span class="st" style="color: #20794D;">"format_mean_sd"</span>)</span>
<span id="cb17-124">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">rd_arguments</span>(rd_path))</span>
<span id="cb17-125"></span>
<span id="cb17-126">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"6. Example code in format_mean_sd.Rd:"</span>)</span>
<span id="cb17-127">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">example_code</span>(rd_path))</span>
<span id="cb17-128"></span>
<span id="cb17-129">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"7. Dropping @param denom and re-documenting..."</span>)</span>
<span id="cb17-130">  <span class="fu" style="color: #4758AB;">drop_param</span>(demo_dir, <span class="st" style="color: #20794D;">"denom"</span>)</span>
<span id="cb17-131">  <span class="fu" style="color: #4758AB;">document_package</span>(demo_dir)</span>
<span id="cb17-132"></span>
<span id="cb17-133">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"8. Undocumented arguments reported by tools::checkDocFiles():"</span>)</span>
<span id="cb17-134">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">undocumented_arguments</span>(demo_dir))</span>
<span id="cb17-135">}</span>
<span id="cb17-136"></span>
<span id="cb17-137"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb17-138">  <span class="fu" style="color: #4758AB;">run_demo</span>()</span>
<span id="cb17-139">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards &amp; R manuals</strong></p>
<ul>
<li><strong>Writing R Extensions (§1.3.1 Checking packages):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Checking-packages">cran.r-project.org/doc/manuals/r-release/R-exts.html#Checking-packages</a></li>
<li><strong>Writing R Extensions (§2.1.1 Documenting functions):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Documenting-functions">cran.r-project.org/doc/manuals/r-release/R-exts.html#Documenting-functions</a></li>
<li><strong>Writing R Extensions (§1.5.1 Specifying imports and exports):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Specifying-imports-and-exports">cran.r-project.org/doc/manuals/r-release/R-exts.html#Specifying-imports-and-exports</a></li>
<li><strong>CRAN Repository Policy:</strong> <a href="https://cran.r-project.org/web/packages/policies.html">cran.r-project.org/web/packages/policies.html</a></li>
</ul>
<p><strong>Software engineering references</strong></p>
<ul>
<li><strong>JSDoc Getting Started:</strong> <a href="https://jsdoc.app/about-getting-started">jsdoc.app/about-getting-started</a></li>
<li><strong>TypeDoc, Doc Comments:</strong> <a href="https://typedoc.org/documents/Doc_Comments.html">typedoc.org/documents/Doc_Comments.html</a></li>
<li><strong>PEP 257 Docstring Conventions:</strong> <a href="https://peps.python.org/pep-0257/">peps.python.org/pep-0257/</a></li>
<li><strong>Sphinx autodoc extension:</strong> <a href="https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html">sphinx-doc.org/en/master/usage/extensions/autodoc.html</a></li>
<li><strong>Python doctest module:</strong> <a href="https://docs.python.org/3/library/doctest.html">docs.python.org/3/library/doctest.html</a></li>
</ul>
<p><strong>R package development guides</strong></p>
<ul>
<li><strong>R Packages (2e), Function documentation:</strong> <a href="https://r-pkgs.org/man.html">r-pkgs.org/man.html</a></li>
<li><strong>roxygen2, Documenting functions:</strong> <a href="https://roxygen2.r-lib.org/articles/rd-functions.html">roxygen2.r-lib.org/articles/rd-functions.html</a></li>
<li><strong>roxygen2, (R)Markdown support:</strong> <a href="https://roxygen2.r-lib.org/articles/rd-formatting.html">roxygen2.r-lib.org/articles/rd-formatting.html</a></li>
<li><strong>roxygen2, Reusing documentation:</strong> <a href="https://roxygen2.r-lib.org/articles/reuse.html">roxygen2.r-lib.org/articles/reuse.html</a></li>
<li><strong>roxygen2, Indexing and cross-references:</strong> <a href="https://roxygen2.r-lib.org/articles/index-crossref.html">roxygen2.r-lib.org/articles/index-crossref.html</a></li>
<li><strong>roxygen2 release notes:</strong> <a href="https://roxygen2.r-lib.org/news/index.html">roxygen2.r-lib.org/news/index.html</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>roxygen2:</strong> <a href="https://roxygen2.r-lib.org/">roxygen2.r-lib.org</a> · <a href="https://cran.r-project.org/package=roxygen2">CRAN page</a></li>
<li><strong>devtools:</strong> <a href="https://devtools.r-lib.org/">devtools.r-lib.org</a> · <a href="https://cran.r-project.org/package=devtools">CRAN page</a></li>
<li><strong>usethis:</strong> <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a> · <a href="https://cran.r-project.org/package=usethis">CRAN page</a></li>
<li><strong>pkgload:</strong> <a href="https://pkgload.r-lib.org/">pkgload.r-lib.org</a> · <a href="https://cran.r-project.org/package=pkgload">CRAN page</a></li>
<li><strong>withr:</strong> <a href="https://withr.r-lib.org/">withr.r-lib.org</a> · <a href="https://cran.r-project.org/package=withr">CRAN page</a></li>
<li><strong>riskmetric:</strong> <a href="https://pharmar.github.io/riskmetric/">pharmar.github.io/riskmetric</a> · <a href="https://cran.r-project.org/package=riskmetric">CRAN page</a></li>
<li><strong>precommit:</strong> <a href="https://lorenzwalthert.github.io/precommit/articles/available-hooks.html">lorenzwalthert.github.io/precommit/articles/available-hooks.html</a> · <a href="https://cran.r-project.org/package=precommit">CRAN page</a></li>
</ul>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/package-dev.html" class="site-series-nav__series">R package development series · part 4 of 4</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 3</span><span class="site-related-card__title">Dependencies: DESCRIPTION and NAMESPACE</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/index.html" class="site-link-row" title="Move reusable analysis helpers from sourced scripts into a minimal R package, and replace workspace pollution with the devtools::load_all() loop."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">From scripts to a package</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="site-link-row" title="Use the R package development loop, read R CMD check diagnostics, and fix four recurring problems."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">The package development loop and R CMD check</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R packages</category>
  <category>R</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/roxygen2-documentation/</guid>
  <pubDate>Mon, 28 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>From scripts to a package</title>
  <link>https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem-sourcehelpers.r" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-sourcehelpers.r">The problem: <code>source("helpers.R")</code></h2>
<p>Most R developers begin building shared tools by creating a script. You write a handful of utility functions, save them to <code>helpers.R</code> or <code>utils.R</code>, and add a line to every analysis program:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1">helpers <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tempfile</span>(<span class="at" style="color: #657422;">fileext =</span> <span class="st" style="color: #20794D;">".R"</span>)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">writeLines</span>(</span>
<span id="cb1-3">  <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb1-4">    <span class="st" style="color: #20794D;">"format_mean_sd &lt;- function(x) sprintf('%.1f (%.1f)', mean(x), stats::sd(x))"</span>,</span>
<span id="cb1-5">    <span class="st" style="color: #20794D;">"summarise_ages &lt;- function(age) paste0('n = ', length(age), ', ', format_mean_sd(age))"</span></span>
<span id="cb1-6">  ),</span>
<span id="cb1-7">  helpers</span>
<span id="cb1-8">)</span>
<span id="cb1-9"><span class="fu" style="color: #4758AB;">source</span>(helpers)</span>
<span id="cb1-10"><span class="fu" style="color: #4758AB;">summarise_ages</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">64</span>, <span class="dv" style="color: #AD0000;">71</span>, <span class="dv" style="color: #AD0000;">80</span>))</span>
<span id="cb1-11"><span class="co" style="color: #5E5E5E;">#&gt; [1] "n = 3, 71.7 (8.0)"</span></span></code></pre></div></div>
<p>At first, this feels lightweight. But as an analysis codebase grows across programs and studies, three distinct problems emerge:</p>
<ol type="1">
<li><strong>Session pollution:</strong> <code>source()</code> evaluates everything directly into the global environment (<code>.GlobalEnv</code>). Utility functions sit side by side with trial datasets, filtering flags, and temporary variables. If a helper script creates intermediate objects or masks an existing name, it alters the user’s active session silently.</li>
<li><strong>Ghost functions:</strong> If you delete or rename a helper in <code>helpers.R</code> and re-source the file, the old function does not disappear from memory:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># Later you delete the helper from the file and source it again.</span></span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">writeLines</span>(<span class="st" style="color: #20794D;">"summarise_ages &lt;- function(age) paste0('n = ', length(age))"</span>, helpers)</span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;">source</span>(helpers)</span>
<span id="cb2-4"><span class="fu" style="color: #4758AB;">exists</span>(<span class="st" style="color: #20794D;">"format_mean_sd"</span>) <span class="co" style="color: #5E5E5E;"># still there, from the old file</span></span>
<span id="cb2-5"><span class="co" style="color: #5E5E5E;">#&gt; [1] TRUE</span></span>
<span id="cb2-6"><span class="fu" style="color: #4758AB;">rm</span>(format_mean_sd, summarise_ages, helpers) <span class="co" style="color: #5E5E5E;"># clear this source() demonstration</span></span></code></pre></div></div>
<p>Before the <code>rm()</code> call, the deleted function remained in <code>.GlobalEnv</code>. Without removing it or restarting R, code could keep calling that stale helper; a fresh session would no longer have it.</p>
<ol start="3" type="1">
<li><strong>No package contract or metadata:</strong> A script provides no formal declaration of what packages it requires, no version number, no integrated documentation, and no standard test harness. When different analysts copy <code>helpers.R</code> into their own project directories, the copies drift.</li>
</ol>
<p>Moving helpers into a package gives their code, metadata, documentation, and tests a common structure. <code>devtools::load_all()</code> keeps newly loaded package functions out of <code>.GlobalEnv</code>; clear any bindings left by earlier <code>source()</code> calls separately.</p>
</section>
<section id="the-web-repo-way-manifests-layouts-and-editable-installs" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-manifests-layouts-and-editable-installs">The web-repo way: manifests, layouts, and editable installs</h2>
<p>JavaScript and Python projects often organise reusable code into packages with project manifests.</p>
<p>In Node, <code>package.json</code> declares the package name, semantic version, and runtime dependencies:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode json code-with-copy"><code class="sourceCode json"><span id="cb3-1"><span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb3-2">  <span class="dt" style="color: #AD0000;">"name"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"agesum"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb3-3">  <span class="dt" style="color: #AD0000;">"version"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"0.1.0"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb3-4">  <span class="dt" style="color: #AD0000;">"main"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"src/index.js"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb3-5">  <span class="dt" style="color: #AD0000;">"dependencies"</span><span class="fu" style="color: #4758AB;">:</span> <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb3-6">    <span class="dt" style="color: #AD0000;">"lodash"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"^4.17.21"</span></span>
<span id="cb3-7">  <span class="fu" style="color: #4758AB;">},</span></span>
<span id="cb3-8">  <span class="dt" style="color: #AD0000;">"devDependencies"</span><span class="fu" style="color: #4758AB;">:</span> <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb3-9">    <span class="dt" style="color: #AD0000;">"vitest"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"^1.6.0"</span></span>
<span id="cb3-10">  <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb3-11"><span class="fu" style="color: #4758AB;">}</span></span></code></pre></div></div>
<p>In Python, <code>pyproject.toml</code> standardises build specifications and metadata:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode toml code-with-copy"><code class="sourceCode toml"><span id="cb4-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">[build-system]</span></span>
<span id="cb4-2"><span class="dt" style="color: #AD0000;">requires</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="op" style="color: #5E5E5E;">[</span><span class="st" style="color: #20794D;">"hatchling"</span><span class="op" style="color: #5E5E5E;">]</span></span>
<span id="cb4-3"><span class="dt" style="color: #AD0000;">build-backend</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"hatchling.build"</span></span>
<span id="cb4-4"></span>
<span id="cb4-5"><span class="kw" style="color: #003B4F;
font-weight: bold;">[project]</span></span>
<span id="cb4-6"><span class="dt" style="color: #AD0000;">name</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"agesum"</span></span>
<span id="cb4-7"><span class="dt" style="color: #AD0000;">version</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"0.1.0"</span></span>
<span id="cb4-8"><span class="dt" style="color: #AD0000;">dependencies</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="op" style="color: #5E5E5E;">[</span></span>
<span id="cb4-9">  <span class="st" style="color: #20794D;">"polars&gt;=0.20.0"</span></span>
<span id="cb4-10"><span class="op" style="color: #5E5E5E;">]</span></span></code></pre></div></div>
<p>Both ecosystems commonly keep source code and tests in structured directories. For Python, an editable install (<code>pip install -e .</code>) makes development files importable without copying them; ordinary source edits do not require reinstalling the project. An already running Python session may need to reload a module, and metadata or compiled-code changes may need another install or build.</p>
<p>The R package structure maps directly to these concepts:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>Concept</th>
<th>Node / JavaScript (<code>package.json</code>)</th>
<th>Python (<code>pyproject.toml</code>)</th>
<th>R package</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Manifest &amp; metadata</td>
<td><code>package.json</code></td>
<td><code>pyproject.toml</code> (<code>[project]</code>)</td>
<td><code>DESCRIPTION</code></td>
</tr>
<tr class="even">
<td>Source code layout</td>
<td><code>src/</code></td>
<td><code>src/&lt;pkg&gt;/</code></td>
<td><code>R/</code></td>
</tr>
<tr class="odd">
<td>Exported interface</td>
<td><code>exports</code> / <code>main</code> field</td>
<td>Names re-exported in <code>__init__.py</code></td>
<td><code>NAMESPACE</code> (<code>export()</code> lines)</td>
</tr>
<tr class="even">
<td>Automated test suite</td>
<td><code>test/</code> (Vitest, Jest)</td>
<td><code>tests/</code> (pytest)</td>
<td><code>tests/testthat/</code></td>
</tr>
<tr class="odd">
<td>Excluded build assets</td>
<td><code>files</code> field / <code>.npmignore</code></td>
<td>Build backend exclusion rules</td>
<td><code>.Rbuildignore</code></td>
</tr>
<tr class="even">
<td>In-session dev workflow</td>
<td><code>npm link</code> / workspaces</td>
<td><code>pip install -e .</code> (editable install)</td>
<td><code>devtools::load_all()</code></td>
</tr>
</tbody>
</table>
</div>
</section>
<section id="the-r-way-anatomy-creation-and-the-load_all-loop" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-anatomy-creation-and-the-load_all-loop">The R way: anatomy, creation, and the <code>load_all()</code> loop</h2>
<p>An R package is a directory structured according to R’s conventions. <code>DESCRIPTION</code> and <code>NAMESPACE</code> are required; a package with R functions also has an <code>R/</code> directory. The other directories below serve particular purposes and may be absent:</p>
<ul>
<li><strong><code>DESCRIPTION</code>:</strong> The project manifest. It defines the package name, title, version, author details, license, and external package dependencies (<code>Imports</code> and <code>Suggests</code>).</li>
<li><strong><code>NAMESPACE</code>:</strong> Declares which functions are exported to callers and which functions are imported from other packages. Although it resembles R code, R parses it as an export/import specification rather than executing it.</li>
<li><strong><code>R/</code>:</strong> Contains R code files defining functions. Files in <code>R/</code> should only assign objects; they should not run analysis scripts or attach libraries.</li>
<li><strong><code>man/</code>:</strong> Help documentation files in Rd format. You rarely write Rd files manually; roxygen2 generates them from code comments (covered in a later post).</li>
<li><strong><code>tests/testthat/</code>:</strong> Contains automated unit tests alongside the test runner script <code>tests/testthat.R</code> (see <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html">testthat essentials</a>).</li>
<li><strong><code>.Rbuildignore</code>:</strong> Lists Perl-compatible regular expressions (one per line) matching files and folders to exclude when building a package bundle.</li>
</ul>
<p>After <code>create_package()</code>, <code>use_r("ages")</code> and <code>use_testthat(3)</code> (all shown below), the tree is small:</p>
<pre><code>agesum/
├── DESCRIPTION
├── NAMESPACE
├── R/
│   └── ages.R
└── tests/
    ├── testthat/
    └── testthat.R</code></pre>
<section id="creating-the-package-skeleton" class="level3">
<h3 class="anchored" data-anchor-id="creating-the-package-skeleton">Creating the package skeleton</h3>
<p>The <code>{usethis}</code> package creates this skeleton in one step. Run this command outside of any existing R project or repository:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb6-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(<span class="st" style="color: #20794D;">"~/code/agesum"</span>)</span></code></pre></div></div>
<p><code>usethis::create_package()</code> writes <code>DESCRIPTION</code>, <code>NAMESPACE</code>, and an empty <code>R/</code> directory. Its <code>rstudio</code> argument defaults to <code>rstudioapi::isAvailable()</code>, which is <code>TRUE</code> inside RStudio; then it also writes <code>&lt;pkg&gt;.Rproj</code>, <code>.gitignore</code>, and <code>.Rbuildignore</code>.</p>
<p>The generated <code>DESCRIPTION</code> file provides the standard package metadata template:</p>
<pre><code>Package: agesum
Title: What the Package Does (One Line, Title Case)
Version: 0.0.0.9000
Authors@R: 
    person("First", "Last", , "first.last@example.com", role = c("aut", "cre"))
Description: What the package does (one paragraph).
License: `use_mit_license()`, `use_gpl3_license()` or friends to pick a
    license
Config/roxygen2/version: 8.1.0
Encoding: UTF-8
Roxygen: list(markdown = TRUE)</code></pre>
<p>Several details in this file are worth noting:</p>
<ul>
<li><code>Version: 0.0.0.9000</code> is usethis’s default development version; update it as you release the package.</li>
<li><code>Config/roxygen2/version: 8.1.0</code> records the roxygen2 version used to generate documentation (which replaced the older <code>RoxygenNote</code> field starting in roxygen2 8.0.0).</li>
<li>The <code>License</code> line is a placeholder. You can set an appropriate open-source or proprietary license using helpers such as <code>usethis::use_mit_license()</code> or <code>usethis::use_proprietary_license()</code> (see <a href="https://insightsurge-dev.web.app/posts/repo-hygiene-files/index.html">repo hygiene files</a>).</li>
</ul>
<p>To add code and testing directories to your new package, run:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb8-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_r</span>(<span class="st" style="color: #20794D;">"ages"</span>)   <span class="co" style="color: #5E5E5E;"># creates R/ages.R</span></span>
<span id="cb8-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_testthat</span>(<span class="dv" style="color: #AD0000;">3</span>) <span class="co" style="color: #5E5E5E;"># creates tests/testthat/ and tests/testthat.R</span></span></code></pre></div></div>
<p>Inside <code>R/ages.R</code>, define your functions:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">format_mean_sd <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) {</span>
<span id="cb9-2">  <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"%.1f (%.1f)"</span>, <span class="fu" style="color: #4758AB;">mean</span>(x), stats<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">sd</span>(x))</span>
<span id="cb9-3">}</span>
<span id="cb9-4"></span>
<span id="cb9-5">summarise_ages <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb9-6">  <span class="fu" style="color: #4758AB;">paste0</span>(<span class="st" style="color: #20794D;">"n = "</span>, <span class="fu" style="color: #4758AB;">length</span>(age), <span class="st" style="color: #20794D;">", mean (SD) = "</span>, <span class="fu" style="color: #4758AB;">format_mean_sd</span>(age))</span>
<span id="cb9-7">}</span></code></pre></div></div>
<p>The new <code>NAMESPACE</code> has no exports yet. <code>devtools::load_all()</code> makes these functions callable during development, but an installed user cannot call <code>summarise_ages()</code> through <code>agesum::</code> until it is exported; a later post covers that step.</p>
<p>Format and lint your package files with Air and lintr just like any other R project (see <a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html">hooks, formatting, and linting</a>).</p>
</section>
<section id="the-devtoolsload_all-loop" class="level3">
<h3 class="anchored" data-anchor-id="the-devtoolsload_all-loop">The <code>devtools::load_all()</code> loop</h3>
<p>In a script-based workflow, developers rely on <code>source()</code> to pull updated functions into memory. In package development, the core workflow engine is <code>devtools::load_all()</code> (in RStudio, <code>Cmd+Shift+L</code> on macOS or <code>Ctrl+Shift+L</code> on Windows and Linux; Positron has a “load package” shortcut too).</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb10-1">devtools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">load_all</span>() <span class="co" style="color: #5E5E5E;"># Cmd/Ctrl + Shift + L</span></span>
<span id="cb10-2"><span class="co" style="color: #5E5E5E;">#&gt; ℹ Loading agesum</span></span>
<span id="cb10-3"><span class="fu" style="color: #4758AB;">summarise_ages</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">64</span>, <span class="dv" style="color: #AD0000;">71</span>, <span class="dv" style="color: #AD0000;">80</span>))</span>
<span id="cb10-4"><span class="co" style="color: #5E5E5E;">#&gt; [1] "n = 3, mean (SD) = 71.7 (8.0)"</span></span>
<span id="cb10-5"><span class="fu" style="color: #4758AB;">format_mean_sd</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">64</span>, <span class="dv" style="color: #AD0000;">71</span>, <span class="dv" style="color: #AD0000;">80</span>)) <span class="co" style="color: #5E5E5E;"># internal helper: visible during development</span></span>
<span id="cb10-6"><span class="co" style="color: #5E5E5E;">#&gt; [1] "71.7 (8.0)"</span></span></code></pre></div></div>
<p>Under the hood, <code>devtools::load_all()</code> calls <code>pkgload::load_all()</code>. It approximates building, installing, and attaching the package, without installing anything. It provides several advantages over sourcing:</p>
<ol type="1">
<li><strong>Clean namespace separation:</strong> Sourced scripts put functions into <code>.GlobalEnv</code>. In contrast, <code>load_all()</code> loads them into the package namespace and attaches <code>package:agesum</code> to R’s search path. These package functions do not create new <code>.GlobalEnv</code> bindings.</li>
<li><strong>Access to internal functions:</strong> By default (<code>export_all = TRUE</code>), <code>load_all()</code> makes unexported helpers available in your interactive console. You can inspect and test internal algorithms directly without adding temporary export declarations.</li>
<li><strong>Cleanup within the package:</strong> Re-running <code>devtools::load_all()</code> after deleting or renaming a function in <code>R/</code> removes it from the reloaded package environment. It does not remove an old function left in <code>.GlobalEnv</code> by an earlier <code>source()</code>; remove that binding or restart R.</li>
<li><strong>Dependency handling:</strong> External packages declared in <code>DESCRIPTION</code> <code>Imports</code> are loaded into memory so that internal package calls succeed, without attaching them to the search path.</li>
<li><strong>Test helper availability:</strong> If your package uses <code>{testthat}</code>, files matching <code>tests/testthat/helper-*.R</code> are loaded into memory automatically during <code>load_all()</code>.</li>
</ol>
</section>
<section id="when-top-level-code-in-r-runs" class="level3">
<h3 class="anchored" data-anchor-id="when-top-level-code-in-r-runs">When top-level code in <code>R/</code> runs</h3>
<p>When transitioning from scripts to packages, the most critical adjustment is understanding when code executes.</p>
<p>In a script, top-level expressions execute sequentially every time the file is sourced:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="co" style="color: #5E5E5E;"># Acceptable in a one-off script, but WRONG inside a package R/ file:</span></span>
<span id="cb11-2"><span class="fu" style="color: #4758AB;">library</span>(dplyr)</span>
<span id="cb11-3">study_data <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">read.csv</span>(<span class="st" style="color: #20794D;">"data/raw.csv"</span>)</span>
<span id="cb11-4">run_date <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">Sys.Date</span>()</span></code></pre></div></div>
<p>For an installed package, top-level expressions in <code>R/</code> are evaluated when the package binary is created (often while installing from source). <code>library()</code> later loads the saved objects; it does not re-run those expressions. During development, <code>devtools::load_all()</code> re-sources <code>R/</code> files on each load. A top-level <code>run_date &lt;- Sys.Date()</code> can therefore change during development but remain fixed at the package binary’s build date for installed users.</p>
<p>Likewise, avoid calling <code>library()</code> or <code>source()</code> at the top level of an <code>R/</code> file:</p>
<ul>
<li>Dependencies belong in <code>DESCRIPTION</code> (<code>Imports</code>), referenced in code via <code>pkg::fun()</code> or imported via <code>NAMESPACE</code>.</li>
<li>File loading belongs in package data workflows (<code>data/</code> or <code>inst/extdata/</code>), not top-level <code>read.csv()</code> calls.</li>
<li>Files in <code>R/</code> should do exactly one thing: define and assign functions and objects.</li>
</ul>
</section>
</section>
<section id="when-to-use-a-script-vs-a-package" class="level2">
<h2 class="anchored" data-anchor-id="when-to-use-a-script-vs-a-package">When to use a script vs a package</h2>
<p>A practical rule of thumb is to keep a study-specific analysis in its project and package functions that several analyses will reuse:</p>
<ul>
<li><strong>Use analysis projects and scripts</strong> for study-specific deliverables: deriving study ADaM datasets, generating numbered clinical study report tables, figures, and listings (TFLs), or running exploratory analyses. These workflows have specific data inputs and fixed outputs, best managed in project directories using tools like renv, targets, or Quarto.</li>
<li><strong>Use a package</strong> for logic that will be reused across studies, projects, or team members: standardised statistical algorithms, company-wide table formatting helpers, custom plotting themes, and shared validation utilities.</li>
</ul>
</section>
<section id="the-gxp-angle-a-place-to-collect-evidence" class="level2">
<h2 class="anchored" data-anchor-id="the-gxp-angle-a-place-to-collect-evidence">The GxP angle: a place to collect evidence</h2>
<p>A package gives code, version metadata, documentation, and tests predictable locations. In regulated work, that can make it easier to collect evidence for a risk assessment, but the structure alone does not establish that the code is suitable for its intended use.</p>
<p>The R Validation Hub white paper considers a package’s purpose, maintenance practices, community usage, and testing. Teams still need to assess those criteria for their intended use, run and review appropriate tests, and keep the results. See <a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html">validation-ready R packages</a>.</p>
</section>
<section id="looking-ahead" class="level2">
<h2 class="anchored" data-anchor-id="looking-ahead">Looking ahead</h2>
<p>Turning scripts into a minimal package is the first step toward robust R engineering. The subsequent posts in this series expand each piece of the package workflow:</p>
<ul>
<li>Post 2 covers the package development cycle and running <code>R CMD check</code>.</li>
<li>Post 3 examines managing dependencies and importing functions in <code>NAMESPACE</code>.</li>
<li>Post 4 details writing function documentation and roxygen2 tags.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/scripts/first-package-demo.R">View <code>first-package-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/scripts/first-package-demo.R" download="first-package-demo.R">Download</a></p>
<p>Builds a throwaway package in a temporary directory, writes a function and helper into <code>R/</code>, loads them with <code>pkgload::load_all()</code>, and shows how reloading drops the deleted helper. The function is available during development; exporting it for installed users is covered later. Requires <code>{usethis}</code>, <code>{pkgload}</code>, <code>{withr}</code>, and <code>{testthat}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>first-package-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="co" style="color: #5E5E5E;"># From scripts to a package: builds a throwaway package in a temporary folder,</span></span>
<span id="cb12-2"><span class="co" style="color: #5E5E5E;"># writes one function and one helper into R/, loads the</span></span>
<span id="cb12-3"><span class="co" style="color: #5E5E5E;"># package with pkgload::load_all() and calls the function. Then it edits the</span></span>
<span id="cb12-4"><span class="co" style="color: #5E5E5E;"># file and loads again, to show that load_all() replaces the old code (unlike</span></span>
<span id="cb12-5"><span class="co" style="color: #5E5E5E;"># source(), which leaves deleted functions behind in your workspace).</span></span>
<span id="cb12-6"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb12-7"><span class="co" style="color: #5E5E5E;">#   Rscript first-package-demo.R</span></span>
<span id="cb12-8"></span>
<span id="cb12-9"><span class="co" style="color: #5E5E5E;"># The code a script writer would have kept in a sourced helpers file.</span></span>
<span id="cb12-10">ages_code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb12-11">  <span class="st" style="color: #20794D;">"# Internal helper: not exported, but visible after load_all()."</span>,</span>
<span id="cb12-12">  <span class="st" style="color: #20794D;">"format_mean_sd &lt;- function(x) {"</span>,</span>
<span id="cb12-13">  <span class="st" style="color: #20794D;">"  sprintf(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">%.1f (%.1f)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, mean(x), stats::sd(x))"</span>,</span>
<span id="cb12-14">  <span class="st" style="color: #20794D;">"}"</span>,</span>
<span id="cb12-15">  <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb12-16">  <span class="st" style="color: #20794D;">"#' Summarise ages as n and mean (SD)"</span>,</span>
<span id="cb12-17">  <span class="st" style="color: #20794D;">"summarise_ages &lt;- function(age) {"</span>,</span>
<span id="cb12-18">  <span class="st" style="color: #20794D;">"  paste0(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">n = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, length(age), </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, mean (SD) = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, format_mean_sd(age))"</span>,</span>
<span id="cb12-19">  <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb12-20">)</span>
<span id="cb12-21"></span>
<span id="cb12-22"><span class="co" style="color: #5E5E5E;"># The same file after an edit: the helper is gone.</span></span>
<span id="cb12-23">ages_code_edited <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb12-24">  <span class="st" style="color: #20794D;">"#' Summarise ages as n"</span>,</span>
<span id="cb12-25">  <span class="st" style="color: #20794D;">"summarise_ages &lt;- function(age) {"</span>,</span>
<span id="cb12-26">  <span class="st" style="color: #20794D;">"  paste0(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">n = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, length(age))"</span>,</span>
<span id="cb12-27">  <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb12-28">)</span>
<span id="cb12-29"></span>
<span id="cb12-30"><span class="co" style="color: #5E5E5E;"># Creates the package at `path` (the folder name is the package name) and</span></span>
<span id="cb12-31"><span class="co" style="color: #5E5E5E;"># returns its path.</span></span>
<span id="cb12-32">create_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb12-33">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_options</span>(<span class="at" style="color: #657422;">usethis.quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-34">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(path, <span class="at" style="color: #657422;">rstudio =</span> <span class="cn" style="color: #8f5902;">FALSE</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb12-35">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">with_project</span>(path, {</span>
<span id="cb12-36">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_testthat</span>(<span class="dv" style="color: #AD0000;">3</span>)</span>
<span id="cb12-37">  })</span>
<span id="cb12-38">  <span class="fu" style="color: #4758AB;">writeLines</span>(ages_code, <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"ages.R"</span>))</span>
<span id="cb12-39">  <span class="fu" style="color: #4758AB;">invisible</span>(path)</span>
<span id="cb12-40">}</span>
<span id="cb12-41"></span>
<span id="cb12-42"><span class="co" style="color: #5E5E5E;"># Every file in the package, relative to its root.</span></span>
<span id="cb12-43">package_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb12-44">  <span class="fu" style="color: #4758AB;">sort</span>(<span class="fu" style="color: #4758AB;">list.files</span>(path, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">all.files =</span> <span class="cn" style="color: #8f5902;">TRUE</span>))</span>
<span id="cb12-45">}</span>
<span id="cb12-46"></span>
<span id="cb12-47"><span class="co" style="color: #5E5E5E;"># Loads the package from source and returns its namespace.</span></span>
<span id="cb12-48">load_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb12-49">  pkgload<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">load_all</span>(path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)<span class="sc" style="color: #5E5E5E;">$</span>env</span>
<span id="cb12-50">}</span>
<span id="cb12-51"></span>
<span id="cb12-52">edit_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb12-53">  <span class="fu" style="color: #4758AB;">writeLines</span>(ages_code_edited, <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"ages.R"</span>))</span>
<span id="cb12-54">}</span>
<span id="cb12-55"></span>
<span id="cb12-56"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb12-57"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-58">  path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"agesdemo"</span>)</span>
<span id="cb12-59">  <span class="fu" style="color: #4758AB;">create_demo_package</span>(path)</span>
<span id="cb12-60">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">package_files</span>(path))</span>
<span id="cb12-61"></span>
<span id="cb12-62">  <span class="fu" style="color: #4758AB;">load_demo_package</span>(path)</span>
<span id="cb12-63">  ages <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">64</span>, <span class="dv" style="color: #AD0000;">71</span>, <span class="dv" style="color: #AD0000;">80</span>)</span>
<span id="cb12-64">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">summarise_ages</span>(ages))</span>
<span id="cb12-65">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">format_mean_sd</span>(ages)) <span class="co" style="color: #5E5E5E;"># internal, yet callable after load_all()</span></span>
<span id="cb12-66"></span>
<span id="cb12-67">  <span class="fu" style="color: #4758AB;">edit_demo_package</span>(path)</span>
<span id="cb12-68">  <span class="fu" style="color: #4758AB;">load_demo_package</span>(path)</span>
<span id="cb12-69">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">summarise_ages</span>(ages))</span>
<span id="cb12-70">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">exists</span>(<span class="st" style="color: #20794D;">"format_mean_sd"</span>)) <span class="co" style="color: #5E5E5E;"># FALSE: the deleted helper is gone</span></span>
<span id="cb12-71">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards &amp; R manuals</strong></p>
<ul>
<li><strong>Writing R Extensions (§1.1 Package structure, §1.1.5, §1.3.2, §1.5):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html">cran.r-project.org/doc/manuals/r-release/R-exts.html</a></li>
<li><strong>R Validation Hub:</strong> <em>A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure</em> — <a href="https://www.pharmar.org/white-paper/">pharmar.org/white-paper</a></li>
</ul>
<p><strong>R package development guide</strong></p>
<ul>
<li><strong>R Packages (2e), Introduction:</strong> <a href="https://r-pkgs.org/introduction.html">r-pkgs.org/introduction.html</a></li>
<li><strong>R Packages (2e), The whole game:</strong> <a href="https://r-pkgs.org/whole-game.html">r-pkgs.org/whole-game.html</a></li>
<li><strong>R Packages (2e), Package structure and state:</strong> <a href="https://r-pkgs.org/structure.html">r-pkgs.org/structure.html</a></li>
<li><strong>R Packages (2e), Fundamental development workflows:</strong> <a href="https://r-pkgs.org/workflow101.html">r-pkgs.org/workflow101.html</a></li>
<li><strong>R Packages (2e), R code:</strong> <a href="https://r-pkgs.org/code.html">r-pkgs.org/code.html</a></li>
<li><strong>R Packages (2e), Package lifecycle:</strong> <a href="https://r-pkgs.org/lifecycle.html">r-pkgs.org/lifecycle.html</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>usethis:</strong> <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a> · <a href="https://cran.r-project.org/package=usethis">CRAN page</a></li>
<li><strong>pkgload:</strong> <a href="https://pkgload.r-lib.org/">pkgload.r-lib.org</a> · <a href="https://cran.r-project.org/package=pkgload">CRAN page</a></li>
<li><strong>devtools:</strong> <a href="https://devtools.r-lib.org/">devtools.r-lib.org</a> · <a href="https://cran.r-project.org/package=devtools">CRAN page</a></li>
<li><strong>roxygen2:</strong> <a href="https://roxygen2.r-lib.org/">roxygen2.r-lib.org</a> · <a href="https://cran.r-project.org/package=roxygen2">CRAN page</a></li>
<li><strong>testthat:</strong> <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a> · <a href="https://cran.r-project.org/package=testthat">CRAN page</a></li>
<li><strong>withr:</strong> <a href="https://withr.r-lib.org/">withr.r-lib.org</a> · <a href="https://cran.r-project.org/package=withr">CRAN page</a></li>
<li><strong>desc:</strong> <a href="https://desc.r-lib.org/">desc.r-lib.org</a> · <a href="https://cran.r-project.org/package=desc">CRAN page</a></li>
</ul>
<p><strong>Web-repo specifications</strong></p>
<ul>
<li><strong>Python Packaging User Guide (pyproject.toml):</strong> <a href="https://packaging.python.org/en/latest/guides/writing-pyproject-toml/">packaging.python.org/en/latest/guides/writing-pyproject-toml</a></li>
<li><strong>Python Packaging User Guide (src layout):</strong> <a href="https://packaging.python.org/en/latest/discussions/src-layout-vs-flat-layout/">packaging.python.org/en/latest/discussions/src-layout-vs-flat-layout</a></li>
<li><strong>pip local project installs (editable mode):</strong> <a href="https://pip.pypa.io/en/stable/topics/local-project-installs/">pip.pypa.io/en/stable/topics/local-project-installs</a></li>
<li><strong>npm package.json documentation:</strong> <a href="https://docs.npmjs.com/cli/configuring-npm/package-json">docs.npmjs.com/cli/configuring-npm/package-json</a></li>
<li><strong>npm link and workspaces:</strong> <a href="https://docs.npmjs.com/cli/link.html/">npm link</a> · <a href="https://docs.npmjs.com/cli/using-npm/workspaces/">workspaces</a></li>
<li><strong>Positron R keyboard shortcuts:</strong> <a href="https://positron.posit.co/guide-r.html">Positron R guide</a></li>
</ul>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/package-dev.html" class="site-series-nav__series">R package development series · part 1 of 4</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 2</span><span class="site-related-card__title">The package development loop and R CMD check</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html" class="site-link-row" title="Set up testthat 3rd edition, structure unit tests with expectations, run them locally and in CI, and build reproducible verification suites."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">testthat essentials</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html" class="site-link-row" title="Catch syntax errors, stale documentation, and styling differences automatically before code reaches review."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Pre-commit hooks, formatting &amp; linting</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/</guid>
  <pubDate>Mon, 28 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>The package development loop and R CMD check</title>
  <link>https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem-check-output-as-a-wall-of-noise" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-check-output-as-a-wall-of-noise">The problem: check output as a wall of noise</h2>
<p><code>R CMD check</code> prints a long list of <code>* checking ...</code> lines, sometimes followed by diagnostics. A NOTE does not necessarily mean a package is broken, but dismissing diagnostics because code works in your console can hide a real problem. The check inspects package structure, metadata, code, documentation, examples, and tests. <code>devtools::check()</code> first builds a source tarball, then checks it in an independent R process.</p>
</section>
<section id="the-web-repo-way-fast-inner-loops-and-pre-merge-gates" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-fast-inner-loops-and-pre-merge-gates">The web-repo way: fast inner loops and pre-merge gates</h2>
<p>Python and Node projects use lint, test, and build commands locally. CI can repeat them on a fresh runner and check a built artifact. Branch protection makes a passing CI job a merge requirement. R packages have a local loop (<code>load_all()</code>, <code>document()</code>, and <code>test()</code>) and a built-package check.</p>
</section>
<section id="the-r-way-the-loop-the-check-and-four-common-diagnostics" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-the-loop-the-check-and-four-common-diagnostics">The R way: the loop, the check, and four common diagnostics</h2>
<section id="the-inner-loop-load-document-test-check" class="level3">
<h3 class="anchored" data-anchor-id="the-inner-loop-load-document-test-check">The inner loop: load, document, test, check</h3>
<p>Four <code>{devtools}</code> commands form the development loop:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Step (RStudio shortcut)</th>
<th>Calls</th>
<th>What it does, and when</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Load</strong> (<code>Cmd/Ctrl+Shift+L</code>)</td>
<td><code>pkgload::load_all()</code></td>
<td>Loads the source into a package-like namespace without installing, internal functions included. Run it after every edit in <code>R/</code>.</td>
</tr>
<tr class="even">
<td><strong>Document</strong> (<code>Cmd/Ctrl+Shift+D</code>)</td>
<td><code>roxygen2::roxygenise()</code></td>
<td>Rewrites <code>man/*.Rd</code> and <code>NAMESPACE</code> from roxygen comments. Run it after changing roxygen tags, exports or imports.</td>
</tr>
<tr class="odd">
<td><strong>Test</strong> (<code>Cmd/Ctrl+Shift+T</code>)</td>
<td><code>testthat::test_local()</code></td>
<td>Runs <code>tests/testthat/</code> against your current source. Run it after changing behaviour or tests.</td>
</tr>
<tr class="even">
<td><strong>Check</strong> (<code>Cmd/Ctrl+Shift+E</code>)</td>
<td><code>pkgbuild::build()</code>, then <code>rcmdcheck::rcmdcheck()</code></td>
<td>Builds the <code>.tar.gz</code> and runs the full <code>R CMD check</code> in a fresh R process. Run it before a pull request, a release or a merge.</td>
</tr>
</tbody>
</table>
</div>
<p>Unlike <code>devtools::test()</code>, <code>devtools::check()</code> builds a <code>.tar.gz</code> archive with <code>pkgbuild::build()</code>, then passes it to <code>rcmdcheck::rcmdcheck()</code> in an independent R process. Your interactive workspace cannot affect the check. The archive excludes files listed in <code>.Rbuildignore</code>.</p>
<div class="callout callout-style-default callout-important callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Important</span>Always document before checking
</div>
</div>
<div class="callout-body-container callout-body">
<p>In older workflows, developers assumed <code>devtools::check()</code> automatically re-documented their package. Under modern versions of <code>{roxygen2}</code> and <code>{usethis}</code>, new packages record <code>Config/roxygen2/version</code> in <code>DESCRIPTION</code> rather than the older <code>RoxygenNote</code> field. If <code>RoxygenNote</code> is absent, <code>devtools::check()</code> skips documentation generation silently.</p>
<p>To ensure your <code>NAMESPACE</code> and <code>man/</code> files match your latest code before the build tarball is created, run <code>devtools::document()</code> explicitly, or pass <code>document = TRUE</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb1-1">devtools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">document</span>()</span>
<span id="cb1-2">devtools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">check</span>()</span>
<span id="cb1-3"><span class="co" style="color: #5E5E5E;"># Or in a single invocation:</span></span>
<span id="cb1-4">devtools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">check</span>(<span class="at" style="color: #657422;">document =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span></code></pre></div></div>
</div>
</div>
<p>Notice also that <code>devtools::check()</code> is not identical to calling the command-line <code>R CMD check</code> directly. By default, <code>devtools::check()</code> configures sensible development defaults: it turns on <code>--as-cran</code>, adds <code>--no-manual</code> (bypassing the requirement for LaTeX to build a PDF manual), includes <code>--timings</code>, sets the environment variable <code>NOT_CRAN = "true"</code> so that testthat tests using <code>skip_on_cran()</code> run locally, and turns off incoming CRAN feasibility checks.</p>
</section>
<section id="what-r-cmd-check-actually-does" class="level3">
<h3 class="anchored" data-anchor-id="what-r-cmd-check-actually-does">What R CMD check actually does</h3>
<p>Section 1.3.1 of <em>Writing R Extensions</em> specifies the responsibilities of <code>R CMD check</code>. When executed against a package tarball, the check runner performs a comprehensive inspection:</p>
<ul>
<li><strong>Unpacks and checks structure:</strong> It validates directory names, file permissions, and confirms that all top-level files conform to the standard R package specification.</li>
<li><strong>Inspects metadata:</strong> It parses <code>DESCRIPTION</code> to verify required fields, licenses, valid R package version syntax, and package dependency syntax.</li>
<li><strong>Installs into a private library:</strong> It creates a dedicated <code>&lt;package&gt;.Rcheck/</code> directory at the check output location and installs the package there, separate from your usual library.</li>
<li><strong>Checks R code:</strong> It checks syntax, then uses <code>{codetools}</code> to report possible problems such as undefined functions and variables.</li>
<li><strong>Verifies documentation:</strong> It compares Rd files in <code>man/</code> against the code, ensuring all exported functions have documentation and that listed argument names match the actual function signatures.</li>
<li><strong>Executes examples:</strong> It runs eligible documentation examples (excluding <code>\dontrun{}</code> code), with C collation and <code>LANGUAGE=en</code>; an example failure is reported as an ERROR.</li>
<li><strong>Executes the test suite:</strong> It runs all test files in <code>tests/</code> in that isolated installation. A failing test expectation or uncaught error produces a check ERROR.</li>
<li><strong>Rebuilds vignettes:</strong> It renders all vignettes in <code>vignettes/</code> from source, ensuring reproducible execution.</li>
</ul>
<p>The companion’s one-function package produced 39 <code>* checking</code> lines on this machine; other packages and check settings differ.</p>
</section>
<section id="reading-the-log-error-vs-warning-vs-note" class="level3">
<h3 class="anchored" data-anchor-id="reading-the-log-error-vs-warning-vs-note">Reading the log: ERROR vs WARNING vs NOTE</h3>
<p>As Hadley Wickham and Jenny Bryan summarise in <em>R Packages</em> (2e), check results fall into three explicit tiers:</p>
<ul>
<li><strong>ERROR:</strong> Severe problems that you must fix regardless of whether you submit to CRAN or share code internally. Examples include syntax errors, failing tests, unexecutable examples, or missing package dependencies. An ERROR causes the check command to exit with a nonzero status.</li>
<li><strong>WARNING:</strong> Likely problems that must be resolved for public distribution and should rarely be accepted internally. Examples include undeclared package imports (<code>pkg::fun()</code> without declaring <code>pkg</code> in <code>DESCRIPTION</code>), non-ASCII characters in R source files, or documented arguments that do not exist in code. Warnings leave an exit status of 0, but the standard GitHub Action for R packages fails on them by default (see the CI section below).</li>
<li><strong>NOTE:</strong> Mild issues or informational observations. Examples include variables flagged by <code>codetools</code> during data masking, declared dependencies that are never referenced, or non-standard files at the package root. A NOTE leaves an exit status of 0.</li>
</ul>
<p>CRAN policy asks for checks without warnings or significant notes; it allows an explanation for notes that cannot be eliminated. For internal packages, investigate each new diagnostic and record why any remaining NOTE is acceptable.</p>
</section>
<section id="four-recurring-diagnostics-and-how-to-respond" class="level3">
<h3 class="anchored" data-anchor-id="four-recurring-diagnostics-and-how-to-respond">Four recurring diagnostics and how to respond</h3>
<p>The following examples show the reported message and a practical fix.</p>
<section id="global-variable-bindings-in-data-masking-note" class="level4">
<h4 class="anchored" data-anchor-id="global-variable-bindings-in-data-masking-note">1. Global variable bindings in data masking (NOTE)</h4>
<p>When writing data transformation functions with packages like <code>{dplyr}</code>, developers write column names directly:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># R/adults.R</span></span>
<span id="cb2-2"><span class="co" style="color: #5E5E5E;">#' Filter for adult subjects</span></span>
<span id="cb2-3"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb2-4"><span class="co" style="color: #5E5E5E;">#' @param data A data frame containing an AGE column.</span></span>
<span id="cb2-5"><span class="co" style="color: #5E5E5E;">#' @return A filtered data frame.</span></span>
<span id="cb2-6"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb2-7">adults <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data) {</span>
<span id="cb2-8">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">filter</span>(data, AGE <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">18</span>)</span>
<span id="cb2-9">}</span></code></pre></div></div>
<p>Running <code>devtools::check()</code> on this code produces a diagnostic NOTE:</p>
<pre class="text"><code>* checking R code for possible problems ... NOTE
adults: no visible binding for global variable ‘AGE’
Undefined global functions or variables:
  AGE</code></pre>
<p><code>codetools</code> inspects R code using standard lexical scoping rules. Because <code>AGE</code> is neither passed as an argument to <code>adults()</code> nor defined locally inside the function, the checker flags it as a potentially missing global object.</p>
<p>The modern tidyverse solution is to use the <code>.data</code> pronoun from <code>{rlang}</code>, and import <code>.data</code> in your documentation tags:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># R/adults.R</span></span>
<span id="cb4-2"><span class="co" style="color: #5E5E5E;">#' Filter for adult subjects</span></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb4-4"><span class="co" style="color: #5E5E5E;">#' @param data A data frame containing an AGE column.</span></span>
<span id="cb4-5"><span class="co" style="color: #5E5E5E;">#' @return A filtered data frame.</span></span>
<span id="cb4-6"><span class="co" style="color: #5E5E5E;">#' @importFrom rlang .data</span></span>
<span id="cb4-7"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb4-8">adults <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data) {</span>
<span id="cb4-9">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">filter</span>(data, .data<span class="sc" style="color: #5E5E5E;">$</span>AGE <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">18</span>)</span>
<span id="cb4-10">}</span></code></pre></div></div>
<p>Two parts are required: using <code>.data$AGE</code> tells <code>filter()</code> to look inside the data frame, and <code>#' @importFrom rlang .data</code> tells R where the pronoun comes from (with <code>rlang</code> declared in <code>DESCRIPTION</code> <code>Imports</code>). If you use <code>.data$AGE</code> without importing <code>.data</code>, you trade one NOTE for another: <code>no visible binding for global variable ‘.data’</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Data masking vs tidy selection
</div>
</div>
<div class="callout-body-container callout-body">
<p>The <code>.data</code> pronoun applies to <strong>data-masking</strong> verbs (<code>filter()</code>, <code>mutate()</code>, <code>summarise()</code>). In <strong>tidy-selection</strong> verbs (<code>select()</code>, <code>relocate()</code>), the use of <code>.data$col</code> was deprecated in <code>tidyselect 1.2.0</code> and produces a deprecation warning.</p>
<p>For tidy selection, pass column names as character strings (<code>dplyr::select(data, "AGE")</code>) or use tidyselect helpers (<code>dplyr::select(data, dplyr::all_of(cols))</code>).</p>
</div>
</div>
<p>An alternative approach is to declare global variables using <code>utils::globalVariables()</code> in a file such as <code>R/globals.R</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># R/globals.R</span></span>
<span id="cb5-2">utils<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">globalVariables</span>(<span class="st" style="color: #20794D;">"AGE"</span>)</span></code></pre></div></div>
<p>While <code>utils::globalVariables()</code> silences the NOTE, be aware of the trade-off: it registers the name package-wide. If you accidentally register a misspelled name elsewhere, codetools will no longer flag that name as a possible missing variable. <code>.data</code> limits the change to the data-masking expression.</p>
</section>
<section id="undeclared-dependencies-warning" class="level4">
<h4 class="anchored" data-anchor-id="undeclared-dependencies-warning">2. Undeclared dependencies (WARNING)</h4>
<p>If you use a helper from an external package via <code>::</code> without declaring that package in <code>DESCRIPTION</code>:</p>
<pre class="text"><code>* checking dependencies in R code ... WARNING
'::' or ':::' import not declared from: ‘stringr’</code></pre>
<p>Packages called with <code>::</code> or <code>:::</code> must be declared in <code>DESCRIPTION</code>. Use <code>Imports</code> for a dependency required at runtime; an optional dependency can go in <code>Suggests</code> when the call is guarded. For this required <code>stringr</code> example, run <code>usethis::use_package("stringr")</code>. A declared import that is never used may produce <code>Namespace in Imports field not imported from: ‘stringr’</code>.</p>
</section>
<section id="non-ascii-characters-in-r-source-code-warning" class="level4">
<h4 class="anchored" data-anchor-id="non-ascii-characters-in-r-source-code-warning">3. Non-ASCII characters in R source code (WARNING)</h4>
<p>If you write mathematical symbols or special characters directly in an R string literal:</p>
<pre class="text"><code>* checking code files for non-ASCII characters ... WARNING
Found the following file with non-ASCII characters:
  R/adults.R
Portable packages must use only ASCII characters in their R code [...]
Use \uxxxx escapes for other characters.</code></pre>
<p>Non-ASCII bytes in R source files trigger a WARNING because files encoded on one operating system or locale may fail to parse or compile on another.</p>
<p>The fix is to write the string using standard Unicode escape sequences (<code>\uxxxx</code>):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">label <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"\u2265 18 years"</span></span>
<span id="cb8-2">label</span></code></pre></div></div>
<p>The source file contains only portable 7-bit ASCII characters, while R renders the intended symbol at runtime. You can inspect any file for non-ASCII bytes using <code>tools::showNonASCIIfile("R/adults.R")</code>.</p>
</section>
<section id="non-standard-top-level-files-note" class="level4">
<h4 class="anchored" data-anchor-id="non-standard-top-level-files-note">4. Non-standard top-level files (NOTE)</h4>
<p>If you leave ad-hoc files at the root of your package repository (such as <code>notes.txt</code> or exploratory scripts):</p>
<pre class="text"><code>* checking top-level files ... NOTE
Non-standard file/directory found at top level:
  ‘notes.txt’</code></pre>
<p>Because R packages have an explicit root layout (<code>R/</code>, <code>man/</code>, <code>vignettes/</code>, <code>tests/</code>, <code>inst/</code>, <code>data/</code>), unrecognised root files get bundled into the package tarball unless explicitly ignored. Note that this check is enabled under <code>--as-cran</code> (the default in <code>devtools::check()</code>).</p>
<p>To exclude a file from the build artifact, register it in <code>.Rbuildignore</code> using <code>usethis::use_build_ignore("notes.txt")</code>. This adds the regular expression <code>^notes\.txt$</code> to <code>.Rbuildignore</code>. Lines in <code>.Rbuildignore</code> are evaluated as Perl-compatible regular expressions, matched case-insensitively against relative file paths during <code>pkgbuild::build()</code>.</p>
</section>
</section>
<section id="a-result-you-can-assert-on-rcmdcheck" class="level3">
<h3 class="anchored" data-anchor-id="a-result-you-can-assert-on-rcmdcheck">A result you can assert on: rcmdcheck()</h3>
<p>While <code>devtools::check()</code> is designed for interactive console output, <code>{rcmdcheck}</code> provides a programmable interface. When writing automated scripts, custom build validation tools, or smoke tests, use <code>rcmdcheck::rcmdcheck()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb10-1">result <span class="ot" style="color: #003B4F;">&lt;-</span> rcmdcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">rcmdcheck</span>(</span>
<span id="cb10-2">  <span class="at" style="color: #657422;">path =</span> <span class="st" style="color: #20794D;">"."</span>,</span>
<span id="cb10-3">  <span class="at" style="color: #657422;">args =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"--no-manual"</span>, <span class="st" style="color: #20794D;">"--as-cran"</span>),</span>
<span id="cb10-4">  <span class="at" style="color: #657422;">error_on =</span> <span class="st" style="color: #20794D;">"never"</span>,</span>
<span id="cb10-5">  <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb10-6">  <span class="at" style="color: #657422;">env =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="at" style="color: #657422;">NOT_CRAN =</span> <span class="st" style="color: #20794D;">"true"</span>)</span>
<span id="cb10-7">)</span>
<span id="cb10-8"></span>
<span id="cb10-9"><span class="co" style="color: #5E5E5E;"># Inspect counts and diagnostics</span></span>
<span id="cb10-10">result<span class="sc" style="color: #5E5E5E;">$</span>status <span class="co" style="color: #5E5E5E;"># 0 if clean or warnings/notes only; nonzero on error</span></span>
<span id="cb10-11">result<span class="sc" style="color: #5E5E5E;">$</span>notes  <span class="co" style="color: #5E5E5E;"># character vector of </span><span class="al" style="color: #AD0000;">NOTE</span><span class="co" style="color: #5E5E5E;"> messages</span></span>
<span id="cb10-12"><span class="fu" style="color: #4758AB;">length</span>(result<span class="sc" style="color: #5E5E5E;">$</span>warnings)</span></code></pre></div></div>
<p>When running your own check outside CRAN, set <code>NOT_CRAN=true</code> if you need <code>skip_on_cran()</code> tests to execute; <code>rcmdcheck()</code> does not set it for you.</p>
<p><code>rcmdcheck()</code> returns a result object with <code>status</code>, <code>errors</code>, <code>warnings</code>, <code>notes</code>, and <code>checkdir</code>. Inspect the diagnostic vectors directly. The default check folder is temporary and is removed after the result object is discarded; pass <code>check_dir = "check"</code> to retain its logs.</p>
<p><code>error_on</code> controls when <code>rcmdcheck()</code> raises an R error: <code>"never"</code>, <code>"error"</code>, <code>"warning"</code>, or <code>"note"</code>. The check completes first unless it times out.</p>
</section>
<section id="the-pre-merge-gate-in-ci" class="level3">
<h3 class="anchored" data-anchor-id="the-pre-merge-gate-in-ci">The pre-merge gate in CI</h3>
<p>When configured for pull requests, CI can run the check on each one. The GitHub Action <code>r-lib/actions/check-r-package</code> runs <code>rcmdcheck::rcmdcheck()</code> on a fresh runner with these defaults:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb11-1"><span class="fu" style="color: #4758AB;">args</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">'c("--no-manual", "--as-cran")'</span></span>
<span id="cb11-2"><span class="fu" style="color: #4758AB;">error-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">'"warning"'</span></span></code></pre></div></div>
<p>A WARNING fails that job; a required status check then blocks merging until it passes. For setup details, dependency caching, and matrix configurations, see <a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html">CI with GitHub Actions</a>.</p>
</section>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/scripts/check-demo.R">View <code>check-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/scripts/check-demo.R" download="check-demo.R">Download</a></p>
<p>Builds a throwaway package in a temporary directory, triggers a <code>no visible binding for global variable</code> check NOTE, inspects it with <code>rcmdcheck::rcmdcheck()</code>, applies the <code>.data</code> fix, and re-checks clean. Requires <code>{devtools}</code>, <code>{rcmdcheck}</code>, <code>{usethis}</code>, <code>{withr}</code>, <code>{dplyr}</code>, and <code>{rlang}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>check-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="co" style="color: #5E5E5E;"># The package development loop and R CMD check: builds a throwaway package in a</span></span>
<span id="cb12-2"><span class="co" style="color: #5E5E5E;"># temporary folder, writes a function with an undeclared column name that triggers</span></span>
<span id="cb12-3"><span class="co" style="color: #5E5E5E;"># a check </span><span class="al" style="color: #AD0000;">NOTE</span><span class="co" style="color: #5E5E5E;">, runs rcmdcheck::rcmdcheck() to inspect the issue, applies the</span></span>
<span id="cb12-4"><span class="co" style="color: #5E5E5E;"># .data fix, and re-runs the check clean.</span></span>
<span id="cb12-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb12-6"><span class="co" style="color: #5E5E5E;">#   Rscript check-demo.R</span></span>
<span id="cb12-7"></span>
<span id="cb12-8">planted_column <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"AGE"</span></span>
<span id="cb12-9"></span>
<span id="cb12-10">adults_code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">FALSE</span>) {</span>
<span id="cb12-11">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (fixed) {</span>
<span id="cb12-12">    <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb12-13">      <span class="st" style="color: #20794D;">"#' Filter for adult subjects"</span>,</span>
<span id="cb12-14">      <span class="st" style="color: #20794D;">"#'"</span>,</span>
<span id="cb12-15">      <span class="st" style="color: #20794D;">"#' @param data A data frame containing an AGE column."</span>,</span>
<span id="cb12-16">      <span class="st" style="color: #20794D;">"#' @return A filtered data frame."</span>,</span>
<span id="cb12-17">      <span class="st" style="color: #20794D;">"#' @importFrom rlang .data"</span>,</span>
<span id="cb12-18">      <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb12-19">      <span class="st" style="color: #20794D;">"adults &lt;- function(data) {"</span>,</span>
<span id="cb12-20">      <span class="st" style="color: #20794D;">"  dplyr::filter(data, .data$AGE &gt;= 18)"</span>,</span>
<span id="cb12-21">      <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb12-22">    )</span>
<span id="cb12-23">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb12-24">    <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb12-25">      <span class="st" style="color: #20794D;">"#' Filter for adult subjects"</span>,</span>
<span id="cb12-26">      <span class="st" style="color: #20794D;">"#'"</span>,</span>
<span id="cb12-27">      <span class="st" style="color: #20794D;">"#' @param data A data frame containing an AGE column."</span>,</span>
<span id="cb12-28">      <span class="st" style="color: #20794D;">"#' @return A filtered data frame."</span>,</span>
<span id="cb12-29">      <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb12-30">      <span class="st" style="color: #20794D;">"adults &lt;- function(data) {"</span>,</span>
<span id="cb12-31">      <span class="st" style="color: #20794D;">"  dplyr::filter(data, AGE &gt;= 18)"</span>,</span>
<span id="cb12-32">      <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb12-33">    )</span>
<span id="cb12-34">  }</span>
<span id="cb12-35">}</span>
<span id="cb12-36"></span>
<span id="cb12-37">make_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">path =</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"checkdemo"</span>)) {</span>
<span id="cb12-38">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_options</span>(<span class="at" style="color: #657422;">usethis.quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-39">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(</span>
<span id="cb12-40">    path,</span>
<span id="cb12-41">    <span class="at" style="color: #657422;">fields =</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-42">      <span class="at" style="color: #657422;">Title =</span> <span class="st" style="color: #20794D;">"Demo Package for R CMD Check"</span>,</span>
<span id="cb12-43">      <span class="at" style="color: #657422;">Description =</span> <span class="st" style="color: #20794D;">"Filters subject-level data; used to show a check NOTE."</span></span>
<span id="cb12-44">    ),</span>
<span id="cb12-45">    <span class="at" style="color: #657422;">rstudio =</span> <span class="cn" style="color: #8f5902;">FALSE</span>,</span>
<span id="cb12-46">    <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb12-47">  )</span>
<span id="cb12-48">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">with_project</span>(path, {</span>
<span id="cb12-49">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_mit_license</span>(<span class="st" style="color: #20794D;">"Demo authors"</span>)</span>
<span id="cb12-50">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"dplyr"</span>)</span>
<span id="cb12-51">  })</span>
<span id="cb12-52">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="fu" style="color: #4758AB;">adults_code</span>(<span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">FALSE</span>), <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"adults.R"</span>))</span>
<span id="cb12-53">  devtools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">document</span>(path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-54">  <span class="fu" style="color: #4758AB;">invisible</span>(path)</span>
<span id="cb12-55">}</span>
<span id="cb12-56"></span>
<span id="cb12-57">fix_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb12-58">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_options</span>(<span class="at" style="color: #657422;">usethis.quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-59">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">with_project</span>(path, {</span>
<span id="cb12-60">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"rlang"</span>)</span>
<span id="cb12-61">  })</span>
<span id="cb12-62">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="fu" style="color: #4758AB;">adults_code</span>(<span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>), <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"adults.R"</span>))</span>
<span id="cb12-63">  devtools<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">document</span>(path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-64">  <span class="fu" style="color: #4758AB;">invisible</span>(path)</span>
<span id="cb12-65">}</span>
<span id="cb12-66"></span>
<span id="cb12-67">run_check <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>) {</span>
<span id="cb12-68">  rcmdcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">rcmdcheck</span>(</span>
<span id="cb12-69">    path,</span>
<span id="cb12-70">    <span class="at" style="color: #657422;">args =</span> <span class="st" style="color: #20794D;">"--no-manual"</span>,</span>
<span id="cb12-71">    <span class="at" style="color: #657422;">quiet =</span> quiet,</span>
<span id="cb12-72">    <span class="at" style="color: #657422;">error_on =</span> <span class="st" style="color: #20794D;">"never"</span></span>
<span id="cb12-73">  )</span>
<span id="cb12-74">}</span>
<span id="cb12-75"></span>
<span id="cb12-76">check_counts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(result) {</span>
<span id="cb12-77">  <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb12-78">    <span class="at" style="color: #657422;">errors =</span> <span class="fu" style="color: #4758AB;">length</span>(result<span class="sc" style="color: #5E5E5E;">$</span>errors),</span>
<span id="cb12-79">    <span class="at" style="color: #657422;">warnings =</span> <span class="fu" style="color: #4758AB;">length</span>(result<span class="sc" style="color: #5E5E5E;">$</span>warnings),</span>
<span id="cb12-80">    <span class="at" style="color: #657422;">notes =</span> <span class="fu" style="color: #4758AB;">length</span>(result<span class="sc" style="color: #5E5E5E;">$</span>notes)</span>
<span id="cb12-81">  )</span>
<span id="cb12-82">}</span>
<span id="cb12-83"></span>
<span id="cb12-84"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-85">  demo_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"checkdemo"</span>)</span>
<span id="cb12-86">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">dir.exists</span>(demo_dir)) {</span>
<span id="cb12-87">    <span class="fu" style="color: #4758AB;">unlink</span>(demo_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-88">  }</span>
<span id="cb12-89">  pkg_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">make_demo_package</span>(demo_dir)</span>
<span id="cb12-90">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Running initial check (expecting 1 NOTE)..."</span>)</span>
<span id="cb12-91">  res1 <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_check</span>(pkg_path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-92">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">check_counts</span>(res1))</span>
<span id="cb12-93">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">Check output:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, res1<span class="sc" style="color: #5E5E5E;">$</span>notes, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">"</span>, <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">""</span>)</span>
<span id="cb12-94"></span>
<span id="cb12-95">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Applying .data fix and re-checking..."</span>)</span>
<span id="cb12-96">  <span class="fu" style="color: #4758AB;">fix_package</span>(pkg_path)</span>
<span id="cb12-97">  res2 <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_check</span>(pkg_path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-98">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">check_counts</span>(res2))</span>
<span id="cb12-99">  <span class="fu" style="color: #4758AB;">unlink</span>(demo_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-100">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards &amp; R manuals</strong></p>
<ul>
<li><strong>Writing R Extensions (§1.3.1 Checking packages):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Checking-packages">cran.r-project.org/doc/manuals/r-release/R-exts.html#Checking-packages</a></li>
<li><strong>Writing R Extensions (§1.3.2 Building package tarballs):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Building-package-tarballs">cran.r-project.org/doc/manuals/r-release/R-exts.html#Building-package-tarballs</a></li>
<li><strong>R Internals (§Tools / <code>_R_CHECK_TOPLEVEL_FILES_</code>):</strong> <a href="https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Tools">cran.r-project.org/doc/manuals/r-release/R-ints.html#Tools</a></li>
<li><strong>CRAN Repository Policy:</strong> <a href="https://cran.r-project.org/web/packages/policies.html">cran.r-project.org/web/packages/policies.html</a></li>
<li><strong>CRAN Submission Checklist:</strong> <a href="https://cran.r-project.org/web/packages/submission_checklist.html">cran.r-project.org/web/packages/submission_checklist.html</a></li>
</ul>
<p><strong>R package development guide</strong></p>
<ul>
<li><strong>R Packages (2e), Fundamental development workflows:</strong> <a href="https://r-pkgs.org/workflow101.html">r-pkgs.org/workflow101.html</a></li>
<li><strong>R Packages (2e), R CMD check appendix:</strong> <a href="https://r-pkgs.org/R-CMD-check.html">r-pkgs.org/R-CMD-check.html</a></li>
<li><strong>R Packages (2e), Function documentation:</strong> <a href="https://r-pkgs.org/man.html">r-pkgs.org/man.html</a></li>
<li><strong>R Packages (2e), Testing basics:</strong> <a href="https://r-pkgs.org/testing-basics.html">r-pkgs.org/testing-basics.html</a></li>
<li><strong>dplyr vignette, Using dplyr in packages:</strong> <a href="https://cran.r-project.org/web/packages/dplyr/vignettes/in-packages.html">cran.r-project.org/web/packages/dplyr/vignettes/in-packages.html</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>codetools:</strong> <a href="https://cran.r-project.org/package=codetools">CRAN page</a></li>
<li><strong>devtools:</strong> <a href="https://devtools.r-lib.org/">devtools.r-lib.org</a> · <a href="https://cran.r-project.org/package=devtools">CRAN page</a></li>
<li><strong>dplyr:</strong> <a href="https://dplyr.tidyverse.org/">dplyr.tidyverse.org</a> · <a href="https://cran.r-project.org/package=dplyr">CRAN page</a></li>
<li><strong>pkgbuild:</strong> <a href="https://pkgbuild.r-lib.org/">pkgbuild.r-lib.org</a> · <a href="https://cran.r-project.org/package=pkgbuild">CRAN page</a></li>
<li><strong>pkgload:</strong> <a href="https://pkgload.r-lib.org/">pkgload.r-lib.org</a> · <a href="https://cran.r-project.org/package=pkgload">CRAN page</a></li>
<li><strong>rcmdcheck:</strong> <a href="https://r-lib.github.io/rcmdcheck/">r-lib.github.io/rcmdcheck</a> · <a href="https://cran.r-project.org/package=rcmdcheck">CRAN page</a></li>
<li><strong>rlang:</strong> <a href="https://rlang.r-lib.org/">rlang.r-lib.org</a> · <a href="https://cran.r-project.org/package=rlang">CRAN page</a></li>
<li><strong>roxygen2:</strong> <a href="https://roxygen2.r-lib.org/">roxygen2.r-lib.org</a> · <a href="https://cran.r-project.org/package=roxygen2">CRAN page</a></li>
<li><strong>stringr:</strong> <a href="https://cran.r-project.org/package=stringr">CRAN page</a></li>
<li><strong>testthat:</strong> <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a> · <a href="https://cran.r-project.org/package=testthat">CRAN page</a></li>
<li><strong>tidyselect:</strong> <a href="https://tidyselect.r-lib.org/">tidyselect.r-lib.org</a> · <a href="https://cran.r-project.org/package=tidyselect">CRAN page</a></li>
<li><strong>usethis:</strong> <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a> · <a href="https://cran.r-project.org/package=usethis">CRAN page</a></li>
<li><strong>withr:</strong> <a href="https://withr.r-lib.org/">withr.r-lib.org</a> · <a href="https://cran.r-project.org/package=withr">CRAN page</a></li>
</ul>
<p><strong>CI actions</strong></p>
<ul>
<li><strong>r-lib/actions (check-r-package):</strong> <a href="https://github.com/r-lib/actions/tree/v2/check-r-package">github.com/r-lib/actions/tree/v2/check-r-package</a></li>
</ul>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/package-dev.html" class="site-series-nav__series">R package development series · part 2 of 4</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 1</span><span class="site-related-card__title">From scripts to a package</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 3</span><span class="site-related-card__title">Dependencies: DESCRIPTION and NAMESPACE</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html" class="site-link-row" title="Run R CMD check, tests, and link validation automatically on clean GitHub Actions runners with pinned dependencies."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">CI with GitHub Actions</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html" class="site-link-row" title="Set up testthat 3rd edition, structure unit tests with expectations, run them locally and in CI, and build reproducible verification suites."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">testthat essentials</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html" class="site-link-row" title="Catch syntax errors, stale documentation, and styling differences automatically before code reaches review."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Pre-commit hooks, formatting &amp; linting</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/</guid>
  <pubDate>Mon, 28 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Companion code: show it, link it, test it</title>
  <link>https://insightsurge-dev.web.app/posts/companion-code/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<p>Technical articles and engineering handbooks often need runnable code that is too long or too self-contained to show inline. An article might walk through an architecture, a testing strategy, or a migration pattern, but a reader wanting to adapt it needs the complete script: imports, helper functions, execution guards, and command-line arguments.</p>
<p>Shipping companion files alongside Quarto articles looks deceptively simple. You add a folder of scripts, declare them as site resources, and link them in prose. But without strict patterns and automated verification, documentation and companion code quickly drift apart.</p>
<section id="the-problem-drift-between-prose-and-files" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-drift-between-prose-and-files">The problem: drift between prose and files</h2>
<p>On my blog, I accumulated fifteen companion R scripts and a collection of configuration templates, including git hooks, issue forms, and CI workflows. Hosting the files was never an issue: my site configuration published them directly using resource patterns in <code>_quarto.yml</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="fu" style="color: #4758AB;">resources</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"templates/**"</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"posts/*/scripts/**"</span></span></code></pre></div></div>
<p>Quarto’s resource declarations instruct the generator to copy drop-in templates and each post’s companion script folder into the rendered site directory verbatim without evaluating them. Most companion scripts were linked, but inconsistently across posts. However, discoverability, consistency, and structural integrity degraded over time:</p>
<ol type="1">
<li><strong>Inconsistent presentation:</strong> Companion scripts were linked across articles under varying headings (“Trying it yourself”, “Executable demo script”, “Runnable walkthrough”) and placed at arbitrary locations within posts.</li>
<li><strong>Missing links:</strong> One script existed on disk but was mentioned in the post only as plain text, leaving readers with no link or download button.</li>
<li><strong>Path ambiguity:</strong> Readers could not distinguish between downloadable companion files and local paths inside their own project. A code example reading a configuration template looked like a file the reader was expected to have locally, while execution commands mixed internal repository paths with reader commands.</li>
<li><strong>Orphaned templates:</strong> Ten configuration templates in the repository were never referenced or linked from any article. A multi-file agent skill folder had only its primary markdown document linked, leaving its supporting scripts invisible.</li>
<li><strong>Ghost references:</strong> An article referred to a template file name that did not exist on disk.</li>
</ol>
<p>When companion code is treated as a passive file drop rather than a verified interface, broken links and orphaned assets slip past manual review.</p>
</section>
<section id="the-web-repo-way-transclusion-and-build-gates" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-transclusion-and-build-gates">The web-repo way: transclusion and build gates</h2>
<p>Modern static documentation engines in software engineering address this problem with transclusion: embedding external source files directly into rendered pages at build time.</p>
<ul>
<li><p><strong>Material for MkDocs:</strong> The <code>pymdownx.snippets</code> Markdown extension allows documentation pages to pull code from external files using a snippet directive such as <code>--8&lt;-- "path/to/file.py"</code>. The source file remains a normal script that can be tested, linted, and versioned independently, while the documentation pulls in the exact file contents during site generation.</p></li>
<li><p><strong>Docusaurus:</strong> Using Webpack’s <code>raw-loader</code> within MDX pages, authors import scripts directly into code block components:</p>
<pre class="mdx"><code>import CodeBlock from '@theme/CodeBlock';
import DemoSource from '!!raw-loader!./demo.js';

&lt;CodeBlock language="javascript"&gt;{DemoSource}&lt;/CodeBlock&gt;</code></pre></li>
<li><p><strong>Sphinx:</strong> Python’s documentation framework provides the <code>.. literalinclude:: filename.py</code> directive to embed files directly into pages with syntax highlighting and line numbers.</p></li>
</ul>
<p>In all three ecosystems, the rendered page and the underlying file share a single source of truth. Software repositories pair this with automated CI gates: offline link checkers like <a href="https://lychee.cli.rs/">lychee</a> scan the rendered HTML output for dead links, and build assertions confirm that every tracked asset exists in the final release directory.</p>
</section>
<section id="the-r-way-show-it-link-it-test-it" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-show-it-link-it-test-it">The R way: show it, link it, test it</h2>
<p>In Quarto, I use shortcodes, collapsed callouts, a path convention, and automated verification tests.</p>
<section id="the-presentation-pattern" class="level3">
<h3 class="anchored" data-anchor-id="the-presentation-pattern">1 · The presentation pattern</h3>
<p>Every post that ships a companion script ends with a dedicated <code>## Companion code</code> section directly before the sources. The section contains a paired View and Download link, a brief explanation, and a collapsed callout displaying the full script:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb3-1"><span class="fu" style="color: #4758AB;">## Companion code</span></span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;">[</span><span class="ot" style="color: #003B4F;">View `demo.R`</span><span class="co" style="color: #5E5E5E;">](scripts/demo.R)</span> · <span class="co" style="color: #5E5E5E;">[</span><span class="ot" style="color: #003B4F;">Download</span><span class="co" style="color: #5E5E5E;">](scripts/demo.R)</span>{download="demo.R"}</span>
<span id="cb3-4"></span>
<span id="cb3-5">Description of what the script does and required packages.</span>
<span id="cb3-6"></span>
<span id="cb3-7">::: {.callout-note collapse="true"}</span>
<span id="cb3-8"><span class="fu" style="color: #4758AB;">## Full script: `demo.R`</span></span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="in" style="color: #5E5E5E;">```r</span></span>
<span id="cb3-11">{{<span class="sc" style="color: #5E5E5E;">&lt;</span> include scripts<span class="sc" style="color: #5E5E5E;">/</span>demo.R <span class="sc" style="color: #5E5E5E;">&gt;</span>}}</span>
<span id="cb3-12"><span class="in" style="color: #5E5E5E;">```</span></span>
<span id="cb3-13">:::</span></code></pre></div></div>
<p>The example uses triple curly braces to display the shortcode literally without running it (see <a href="https://quarto.org/docs/extensions/shortcodes.html#escaping">Quarto shortcode escaping</a>). In a published article, normal double braces transclude the script at render time.</p>
<p>This structure solves several practical problems:</p>
<ul>
<li><strong>Single source of truth:</strong> Quarto evaluates the <code>include</code> shortcode at render time inside the fenced code block. Quarto and Pandoc escape the code and apply syntax highlighting, while Quarto’s <code>code-copy</code> feature provides the copy-to-clipboard button. The embedded text and the downloadable file come from the exact same file on disk.</li>
<li><strong>No R needed at render time:</strong> The shortcode runs during Quarto’s text processing phase. As long as the post contains no executable chunks, it does not invoke Knitr or evaluate R expressions. The site can be built in lightweight CI containers without an R runtime installed.</li>
<li><strong>Uncluttered layout:</strong> Long scripts do not distract from the article’s narrative. Readers who only want the concept see a compact section; readers who want the code can view it in the page or download it with one click.</li>
</ul>
</section>
<section id="the-path-convention" class="level3">
<h3 class="anchored" data-anchor-id="the-path-convention">2 · The path convention</h3>
<p>To eliminate ambiguity between published assets and a reader’s internal project layout, I use a path rule across the articles:</p>
<ul>
<li><strong>Published assets are always links:</strong> Any mention of a companion script path in prose must be a Markdown hyperlink pointing to the real file on disk (for example, <a href="https://insightsurge-dev.web.app/posts/companion-code/scripts/companion-check.R">scripts/companion-check.R</a>).</li>
<li><strong>Reader paths use project-relative prefixes:</strong> When an article or code example describes a file in the reader’s project, it must use standard project paths such as <code>R/clean-data.R</code>, never a companion folder prefix.</li>
<li><strong>Reader-facing header comments:</strong> The companion script itself is displayed directly on the webpage. Header comments must instruct the reader on how to execute the standalone file (for example, <code># Usage: Rscript companion-check.R</code>), avoiding internal repository paths.</li>
</ul>
</section>
<section id="automated-verification" class="level3">
<h3 class="anchored" data-anchor-id="automated-verification">3 · Automated verification</h3>
<p>Manual vigilance does not prevent broken links or forgotten files. I guard the pattern with three automated layers:</p>
<section id="a-the-unit-test" class="level4">
<h4 class="anchored" data-anchor-id="a-the-unit-test">A · The unit test</h4>
<p>The site’s own test suite runs <code>tests/testthat/test-site-companions.R</code>, while my companion script (<a href="https://insightsurge-dev.web.app/posts/companion-code/scripts/companion-check.R">scripts/companion-check.R</a>) packages these checks into a reusable function, <code>check_companions()</code>, that can be called directly in a project’s own tests:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"companion checker validates site structure"</span>, {</span>
<span id="cb4-2">  <span class="co" style="color: #5E5E5E;"># Validates that every companion script is linked in prose,</span></span>
<span id="cb4-3">  <span class="co" style="color: #5E5E5E;"># embedded via an include shortcode, and exists on disk.</span></span>
<span id="cb4-4">  report <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">check_companions</span>(<span class="at" style="color: #657422;">root =</span> <span class="st" style="color: #20794D;">"."</span>)</span>
<span id="cb4-5">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">nrow</span>(report), <span class="dv" style="color: #AD0000;">0</span>L)</span>
<span id="cb4-6">})</span></code></pre></div></div>
<p>The test asserts five structural rules:</p>
<ol type="1">
<li>Every post companion script is hyperlinked in its post and included within a <code>## Companion code</code> section.</li>
<li>Every configuration file in the site template directory is hyperlinked from at least one post.</li>
<li>Every Markdown link pointing to a companion script or template resolves to an existing file on disk.</li>
<li>Every shortcode include target exists on disk.</li>
<li>No unlinked companion path appears in prose, and no companion path appears inside code blocks other than an include shortcode.</li>
</ol>
<p>When run against the blog before adopting this standard, the test identified one unlinked script, ten unlinked template files, and three command blocks that showed source-repository paths to readers.</p>
</section>
<section id="b-ci-output-verification" class="level4">
<h4 class="anchored" data-anchor-id="b-ci-output-verification">B · CI output verification</h4>
<p>Unit tests run against source files. To verify that Quarto’s resource configuration actually published every asset, the GitHub Actions workflow includes a post-render shell check before deployment:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb5-1"><span class="va" style="color: #111111;">missing</span><span class="op" style="color: #5E5E5E;">=</span>0</span>
<span id="cb5-2"><span class="cf" style="color: #003B4F;
font-weight: bold;">while</span> <span class="va" style="color: #111111;">IFS</span><span class="op" style="color: #5E5E5E;">=</span> <span class="bu" style="color: null;">read</span> <span class="at" style="color: #657422;">-r</span> <span class="va" style="color: #111111;">f</span><span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">do</span></span>
<span id="cb5-3">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> <span class="bu" style="color: null;">[</span> <span class="ot" style="color: #003B4F;">!</span> <span class="ot" style="color: #003B4F;">-f</span> <span class="st" style="color: #20794D;">"_site/</span><span class="va" style="color: #111111;">$f</span><span class="st" style="color: #20794D;">"</span> <span class="bu" style="color: null;">]</span><span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">then</span> <span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"::error::not published: </span><span class="va" style="color: #111111;">$f</span><span class="st" style="color: #20794D;">"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="va" style="color: #111111;">missing</span><span class="op" style="color: #5E5E5E;">=</span>1<span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">fi</span></span>
<span id="cb5-4"><span class="cf" style="color: #003B4F;
font-weight: bold;">done</span> <span class="op" style="color: #5E5E5E;">&lt;</span> <span class="op" style="color: #5E5E5E;">&lt;(</span><span class="fu" style="color: #4758AB;">git</span> ls-files <span class="st" style="color: #20794D;">'posts/*/scripts/*'</span> <span class="st" style="color: #20794D;">'templates/*'</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb5-5"><span class="bu" style="color: null;">exit</span> <span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$missing</span><span class="st" style="color: #20794D;">"</span></span></code></pre></div></div>
<p>The workflow runs this verification across all tracked companion scripts and template files. If an author modifies <code>_quarto.yml</code> and accidentally excludes companion assets, CI fails immediately before preview deployment or static publication. An offline link checker (<a href="https://lychee.cli.rs/">lychee</a>) then scans the rendered HTML files in <code>_site/</code> to ensure all relative links resolve.</p>
</section>
<section id="c-post-checker-integration" class="level4">
<h4 class="anchored" data-anchor-id="c-post-checker-integration">C · Post checker integration</h4>
<p>My repository uses a pre-flight checker (<code>tools/check-post.R</code>) that parses and evaluates code blocks in articles to ensure example code runs without errors. Because include shortcodes are Quarto directives rather than valid R expressions, the checker skips code blocks that contain only include shortcodes (escaped or not), preventing false parse failures while keeping all other R blocks verified.</p>
</section>
</section>
</section>
<section id="which-option-when" class="level2">
<h2 class="anchored" data-anchor-id="which-option-when">Which option when</h2>
<p>Teams building technical documentation in Quarto have several options for sharing code. Selecting the right mechanism depends on execution requirements and project scope:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>Mechanism</th>
<th>How it works</th>
<th>Best suited for</th>
<th>Trade-offs</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Include in callout</strong> (Recommended)</td>
<td>Quarto <code>include</code> shortcode inside a collapsed callout</td>
<td>Standalone scripts, utilities, and configuration templates</td>
<td>Static display only; code is not executed in the reader’s browser</td>
</tr>
<tr class="even">
<td><strong>Quarto Code Tools</strong> (<code>code-tools: true</code>)</td>
<td>HTML header dropdown with “View Source”</td>
<td>Showing the article’s own <code>.qmd</code> source document</td>
<td>Default button shows page source; <code>source: &lt;url&gt;</code> is restricted to one URL per page</td>
</tr>
<tr class="odd">
<td><strong><code>code-fold</code></strong></td>
<td>Folds computational code cells</td>
<td>Collapsing long executed blocks within an analysis</td>
<td>Only works on executed Knitr/Jupyter cells; does not fold static markdown code blocks</td>
</tr>
<tr class="even">
<td><strong>Executed code + <code>freeze</code></strong></td>
<td>Runs R code at render time; caches outputs in <code>_freeze/</code></td>
<td>Articles where tables or figures must be generated dynamically</td>
<td>Requires full R runtime in CI or manual commitment and synchronization of <code>_freeze/</code></td>
</tr>
<tr class="odd">
<td><strong>Quarto Live (webR)</strong></td>
<td>WebAssembly in the browser (<code>r-wasm/quarto-live</code>)</td>
<td>Interactive workshops, exercises, and small educational snippets</td>
<td>Needs a render engine (knitr or Jupyter) at build time; downloads WebAssembly binaries from external CDNs; not every package works in webR; test the ones you need</td>
</tr>
<tr class="even">
<td><strong>Separate examples repo</strong></td>
<td>External GitHub repository</td>
<td>Multi-file R packages, full Shiny apps, and large pipelines</td>
<td>A second repository to keep in step with the posts</td>
</tr>
</tbody>
</table>
</div>
<p>For standalone R scripts, tests, and configuration templates, the static include pattern requires no R at render time, one test in <code>testthat</code>, and one CI step.</p>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/companion-code/scripts/companion-check.R">View <code>companion-check.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/companion-code/scripts/companion-check.R" download="companion-check.R">Download</a></p>
<p>Scans Quarto posts and templates to verify that every companion file is linked, included, and published without broken references or unlinked paths in prose. Base R only.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>companion-check.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="co" style="color: #5E5E5E;"># Companion code checker for Quarto sites and blogs</span></span>
<span id="cb6-2"><span class="co" style="color: #5E5E5E;"># Scans posts and templates to verify companion assets are linked, included,</span></span>
<span id="cb6-3"><span class="co" style="color: #5E5E5E;"># and published without broken references or unlinked paths in prose.</span></span>
<span id="cb6-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb6-5"><span class="co" style="color: #5E5E5E;"># Usage:</span></span>
<span id="cb6-6"><span class="co" style="color: #5E5E5E;">#   Rscript companion-check.R</span></span>
<span id="cb6-7"><span class="co" style="color: #5E5E5E;">#   Or from R:</span></span>
<span id="cb6-8"><span class="co" style="color: #5E5E5E;">#   source("companion-check.R")</span></span>
<span id="cb6-9"><span class="co" style="color: #5E5E5E;">#   problems &lt;- check_companions(</span></span>
<span id="cb6-10"><span class="co" style="color: #5E5E5E;">#     root = ".",</span></span>
<span id="cb6-11"><span class="co" style="color: #5E5E5E;">#     allow = c('- "templates/**"', '- "posts/*/scripts/**"')</span></span>
<span id="cb6-12"><span class="co" style="color: #5E5E5E;">#   )</span></span>
<span id="cb6-13"></span>
<span id="cb6-14">extract_markdown_links <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(lines) {</span>
<span id="cb6-15">  matches <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">gregexpr</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">[[^</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">]]*</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">]</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">(([^)]+)</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">)"</span>, lines, <span class="at" style="color: #657422;">perl =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-16">  reg_matches <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">regmatches</span>(lines, matches)</span>
<span id="cb6-17">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb6-18"></span>
<span id="cb6-19">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (i <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_along</span>(lines)) {</span>
<span id="cb6-20">    hits <span class="ot" style="color: #003B4F;">&lt;-</span> reg_matches[[i]]</span>
<span id="cb6-21">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(hits) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-22">      raw_targets <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">".*</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">]</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">(([^)]+)</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">).*"</span>, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">1"</span>, hits)</span>
<span id="cb6-23">      clean_targets <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">vapply</span>(</span>
<span id="cb6-24">        raw_targets,</span>
<span id="cb6-25">        <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(tgt) {</span>
<span id="cb6-26">          <span class="co" style="color: #5E5E5E;"># Strip optional trailing attributes like {download="x.R"} or quotes</span></span>
<span id="cb6-27">          clean <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">{.*$"</span>, <span class="st" style="color: #20794D;">""</span>, tgt)</span>
<span id="cb6-28">          <span class="fu" style="color: #4758AB;">trimws</span>(clean)</span>
<span id="cb6-29">        },</span>
<span id="cb6-30">        <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">1</span>),</span>
<span id="cb6-31">        <span class="at" style="color: #657422;">USE.NAMES =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb6-32">      )</span>
<span id="cb6-33"></span>
<span id="cb6-34">      results[[<span class="fu" style="color: #4758AB;">length</span>(results) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb6-35">        <span class="at" style="color: #657422;">line =</span> <span class="fu" style="color: #4758AB;">rep</span>(i, <span class="fu" style="color: #4758AB;">length</span>(clean_targets)),</span>
<span id="cb6-36">        <span class="at" style="color: #657422;">target =</span> clean_targets,</span>
<span id="cb6-37">        <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb6-38">      )</span>
<span id="cb6-39">    }</span>
<span id="cb6-40">  }</span>
<span id="cb6-41"></span>
<span id="cb6-42">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(results) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-43">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb6-44">      <span class="at" style="color: #657422;">line =</span> <span class="fu" style="color: #4758AB;">integer</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-45">      <span class="at" style="color: #657422;">target =</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-46">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb6-47">    ))</span>
<span id="cb6-48">  }</span>
<span id="cb6-49">  <span class="fu" style="color: #4758AB;">do.call</span>(rbind, results)</span>
<span id="cb6-50">}</span>
<span id="cb6-51"></span>
<span id="cb6-52">extract_includes <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(lines) {</span>
<span id="cb6-53">  <span class="co" style="color: #5E5E5E;"># Match {{&lt; include ... &gt;}} only when not preceded by { (ignoring escaped {{&lt; ... &gt;}})</span></span>
<span id="cb6-54">  matches <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">gregexpr</span>(</span>
<span id="cb6-55">    <span class="st" style="color: #20794D;">"(?&lt;!</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">{)</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">{</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">{&lt;</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*include</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s+([^ &gt;]+)</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*&gt;</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">}</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">}"</span>,</span>
<span id="cb6-56">    lines,</span>
<span id="cb6-57">    <span class="at" style="color: #657422;">perl =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb6-58">  )</span>
<span id="cb6-59">  reg_matches <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">regmatches</span>(lines, matches)</span>
<span id="cb6-60">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb6-61"></span>
<span id="cb6-62">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (i <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_along</span>(lines)) {</span>
<span id="cb6-63">    hits <span class="ot" style="color: #003B4F;">&lt;-</span> reg_matches[[i]]</span>
<span id="cb6-64">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(hits) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-65">      targets <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">".*include</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s+([^ &gt;]+).*"</span>, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">1"</span>, hits)</span>
<span id="cb6-66">      results[[<span class="fu" style="color: #4758AB;">length</span>(results) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb6-67">        <span class="at" style="color: #657422;">line =</span> <span class="fu" style="color: #4758AB;">rep</span>(i, <span class="fu" style="color: #4758AB;">length</span>(targets)),</span>
<span id="cb6-68">        <span class="at" style="color: #657422;">target =</span> <span class="fu" style="color: #4758AB;">trimws</span>(targets),</span>
<span id="cb6-69">        <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb6-70">      )</span>
<span id="cb6-71">    }</span>
<span id="cb6-72">  }</span>
<span id="cb6-73"></span>
<span id="cb6-74">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(results) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-75">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb6-76">      <span class="at" style="color: #657422;">line =</span> <span class="fu" style="color: #4758AB;">integer</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-77">      <span class="at" style="color: #657422;">target =</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-78">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb6-79">    ))</span>
<span id="cb6-80">  }</span>
<span id="cb6-81">  <span class="fu" style="color: #4758AB;">do.call</span>(rbind, results)</span>
<span id="cb6-82">}</span>
<span id="cb6-83"></span>
<span id="cb6-84">check_companions <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">root =</span> <span class="st" style="color: #20794D;">"."</span>, <span class="at" style="color: #657422;">allow =</span> <span class="fu" style="color: #4758AB;">character</span>()) {</span>
<span id="cb6-85">  root <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">normalizePath</span>(root, <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-86">  posts_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(root, <span class="st" style="color: #20794D;">"posts"</span>)</span>
<span id="cb6-87">  templates_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(root, <span class="st" style="color: #20794D;">"templates"</span>)</span>
<span id="cb6-88"></span>
<span id="cb6-89">  problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb6-90">  add_problem <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(file, line, rule, message) {</span>
<span id="cb6-91">    norm_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">normalizePath</span>(file, <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb6-92">    rel_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">startsWith</span>(norm_file, <span class="fu" style="color: #4758AB;">paste0</span>(root, <span class="st" style="color: #20794D;">"/"</span>))) {</span>
<span id="cb6-93">      <span class="fu" style="color: #4758AB;">substring</span>(norm_file, <span class="fu" style="color: #4758AB;">nchar</span>(root) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">2</span>L)</span>
<span id="cb6-94">    } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb6-95">      norm_file</span>
<span id="cb6-96">    }</span>
<span id="cb6-97">    problems[[<span class="fu" style="color: #4758AB;">length</span>(problems) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L]] <span class="ot" style="color: #003B4F;">&lt;&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb6-98">      <span class="at" style="color: #657422;">file =</span> rel_file,</span>
<span id="cb6-99">      <span class="at" style="color: #657422;">line =</span> <span class="fu" style="color: #4758AB;">as.integer</span>(line),</span>
<span id="cb6-100">      <span class="at" style="color: #657422;">rule =</span> rule,</span>
<span id="cb6-101">      <span class="at" style="color: #657422;">message =</span> message,</span>
<span id="cb6-102">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb6-103">    )</span>
<span id="cb6-104">  }</span>
<span id="cb6-105"></span>
<span id="cb6-106">  <span class="co" style="color: #5E5E5E;"># 1. Discover all posts</span></span>
<span id="cb6-107">  post_qmds <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>)</span>
<span id="cb6-108">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">dir.exists</span>(posts_dir)) {</span>
<span id="cb6-109">    candidate_dirs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list.dirs</span>(posts_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb6-110">    candidate_indices <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(candidate_dirs, <span class="st" style="color: #20794D;">"index.qmd"</span>)</span>
<span id="cb6-111">    post_qmds <span class="ot" style="color: #003B4F;">&lt;-</span> candidate_indices[<span class="fu" style="color: #4758AB;">file.exists</span>(candidate_indices)]</span>
<span id="cb6-112">  }</span>
<span id="cb6-113"></span>
<span id="cb6-114">  <span class="co" style="color: #5E5E5E;"># 2. Discover all companion scripts</span></span>
<span id="cb6-115">  all_scripts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>)</span>
<span id="cb6-116">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">dir.exists</span>(posts_dir)) {</span>
<span id="cb6-117">    all_post_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list.files</span>(posts_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">full.names =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-118">    all_scripts <span class="ot" style="color: #003B4F;">&lt;-</span> all_post_files[<span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"/scripts/[^/]+$"</span>, all_post_files)]</span>
<span id="cb6-119">  }</span>
<span id="cb6-120"></span>
<span id="cb6-121">  <span class="co" style="color: #5E5E5E;"># 3. Discover all templates</span></span>
<span id="cb6-122">  all_templates <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>)</span>
<span id="cb6-123">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">dir.exists</span>(templates_dir)) {</span>
<span id="cb6-124">    all_templates <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list.files</span>(</span>
<span id="cb6-125">      templates_dir,</span>
<span id="cb6-126">      <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb6-127">      <span class="at" style="color: #657422;">full.names =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb6-128">    )</span>
<span id="cb6-129">  }</span>
<span id="cb6-130"></span>
<span id="cb6-131">  <span class="co" style="color: #5E5E5E;"># Track linked templates across all posts</span></span>
<span id="cb6-132">  linked_template_paths <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>)</span>
<span id="cb6-133"></span>
<span id="cb6-134">  <span class="co" style="color: #5E5E5E;"># Check each post</span></span>
<span id="cb6-135">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (qmd <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> post_qmds) {</span>
<span id="cb6-136">    lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readLines</span>(qmd, <span class="at" style="color: #657422;">warn =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb6-137">    checked_lines <span class="ot" style="color: #003B4F;">&lt;-</span> lines</span>
<span id="cb6-138">    checked_lines[<span class="fu" style="color: #4758AB;">trimws</span>(lines) <span class="sc" style="color: #5E5E5E;">%in%</span> allow] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">""</span></span>
<span id="cb6-139">    link_info <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">extract_markdown_links</span>(checked_lines)</span>
<span id="cb6-140">    include_info <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">extract_includes</span>(checked_lines)</span>
<span id="cb6-141"></span>
<span id="cb6-142">    <span class="co" style="color: #5E5E5E;"># Validate Markdown links pointing to scripts or templates</span></span>
<span id="cb6-143">    companion_links <span class="ot" style="color: #003B4F;">&lt;-</span> link_info[</span>
<span id="cb6-144">      <span class="fu" style="color: #4758AB;">grepl</span>(</span>
<span id="cb6-145">        <span class="st" style="color: #20794D;">"^(scripts/|templates/|</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">./</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">./templates/)"</span>,</span>
<span id="cb6-146">        link_info<span class="sc" style="color: #5E5E5E;">$</span>target</span>
<span id="cb6-147">      ),</span>
<span id="cb6-148">    ]</span>
<span id="cb6-149">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (j <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_len</span>(<span class="fu" style="color: #4758AB;">nrow</span>(companion_links))) {</span>
<span id="cb6-150">      tgt <span class="ot" style="color: #003B4F;">&lt;-</span> companion_links<span class="sc" style="color: #5E5E5E;">$</span>target[j]</span>
<span id="cb6-151">      line_num <span class="ot" style="color: #003B4F;">&lt;-</span> companion_links<span class="sc" style="color: #5E5E5E;">$</span>line[j]</span>
<span id="cb6-152">      full_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">normalizePath</span>(<span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">dirname</span>(qmd), tgt), <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb6-153"></span>
<span id="cb6-154">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">file.exists</span>(full_path)) {</span>
<span id="cb6-155">        <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-156">          qmd,</span>
<span id="cb6-157">          line_num,</span>
<span id="cb6-158">          <span class="st" style="color: #20794D;">"broken_link"</span>,</span>
<span id="cb6-159">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Markdown link target '%s' does not exist on disk"</span>, tgt)</span>
<span id="cb6-160">        )</span>
<span id="cb6-161">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (</span>
<span id="cb6-162">        <span class="fu" style="color: #4758AB;">startsWith</span>(</span>
<span id="cb6-163">          full_path,</span>
<span id="cb6-164">          <span class="fu" style="color: #4758AB;">paste0</span>(<span class="fu" style="color: #4758AB;">normalizePath</span>(templates_dir, <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">FALSE</span>), <span class="st" style="color: #20794D;">"/"</span>)</span>
<span id="cb6-165">        )</span>
<span id="cb6-166">      ) {</span>
<span id="cb6-167">        linked_template_paths <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(linked_template_paths, full_path)</span>
<span id="cb6-168">      }</span>
<span id="cb6-169">    }</span>
<span id="cb6-170"></span>
<span id="cb6-171">    <span class="co" style="color: #5E5E5E;"># Validate include shortcodes</span></span>
<span id="cb6-172">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (j <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_len</span>(<span class="fu" style="color: #4758AB;">nrow</span>(include_info))) {</span>
<span id="cb6-173">      inc <span class="ot" style="color: #003B4F;">&lt;-</span> include_info<span class="sc" style="color: #5E5E5E;">$</span>target[j]</span>
<span id="cb6-174">      line_num <span class="ot" style="color: #003B4F;">&lt;-</span> include_info<span class="sc" style="color: #5E5E5E;">$</span>line[j]</span>
<span id="cb6-175">      full_inc <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">normalizePath</span>(<span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">dirname</span>(qmd), inc), <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb6-176"></span>
<span id="cb6-177">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">file.exists</span>(full_inc)) {</span>
<span id="cb6-178">        <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-179">          qmd,</span>
<span id="cb6-180">          line_num,</span>
<span id="cb6-181">          <span class="st" style="color: #20794D;">"missing_include_target"</span>,</span>
<span id="cb6-182">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Include target '%s' does not exist on disk"</span>, inc)</span>
<span id="cb6-183">        )</span>
<span id="cb6-184">      }</span>
<span id="cb6-185">    }</span>
<span id="cb6-186"></span>
<span id="cb6-187">    <span class="co" style="color: #5E5E5E;"># Verify script linkage and companion code sections for this post's scripts</span></span>
<span id="cb6-188">    post_scripts <span class="ot" style="color: #003B4F;">&lt;-</span> all_scripts[<span class="fu" style="color: #4758AB;">dirname</span>(<span class="fu" style="color: #4758AB;">dirname</span>(all_scripts)) <span class="sc" style="color: #5E5E5E;">==</span> <span class="fu" style="color: #4758AB;">dirname</span>(qmd)]</span>
<span id="cb6-189">    has_companion_section <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">any</span>(lines <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"## Companion code"</span>)</span>
<span id="cb6-190"></span>
<span id="cb6-191">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(post_scripts) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span>has_companion_section) {</span>
<span id="cb6-192">      <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-193">        qmd,</span>
<span id="cb6-194">        <span class="dv" style="color: #AD0000;">1</span>L,</span>
<span id="cb6-195">        <span class="st" style="color: #20794D;">"missing_section"</span>,</span>
<span id="cb6-196">        <span class="st" style="color: #20794D;">"Post contains companion scripts but has no '## Companion code' section"</span></span>
<span id="cb6-197">      )</span>
<span id="cb6-198">    }</span>
<span id="cb6-199"></span>
<span id="cb6-200">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (s <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> post_scripts) {</span>
<span id="cb6-201">      script_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">basename</span>(s)</span>
<span id="cb6-202">      rel_script_link <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="st" style="color: #20794D;">"scripts"</span>, script_file)</span>
<span id="cb6-203"></span>
<span id="cb6-204">      <span class="co" style="color: #5E5E5E;"># Check script is linked</span></span>
<span id="cb6-205">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>rel_script_link <span class="sc" style="color: #5E5E5E;">%in%</span> link_info<span class="sc" style="color: #5E5E5E;">$</span>target) {</span>
<span id="cb6-206">        <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-207">          qmd,</span>
<span id="cb6-208">          <span class="dv" style="color: #AD0000;">1</span>L,</span>
<span id="cb6-209">          <span class="st" style="color: #20794D;">"unlinked_script"</span>,</span>
<span id="cb6-210">          <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb6-211">            <span class="st" style="color: #20794D;">"Companion script '%s' is not linked in %s"</span>,</span>
<span id="cb6-212">            rel_script_link,</span>
<span id="cb6-213">            <span class="fu" style="color: #4758AB;">basename</span>(qmd)</span>
<span id="cb6-214">          )</span>
<span id="cb6-215">        )</span>
<span id="cb6-216">      }</span>
<span id="cb6-217"></span>
<span id="cb6-218">      <span class="co" style="color: #5E5E5E;"># Check script is included</span></span>
<span id="cb6-219">      expected_include <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="st" style="color: #20794D;">"scripts"</span>, script_file)</span>
<span id="cb6-220">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>expected_include <span class="sc" style="color: #5E5E5E;">%in%</span> include_info<span class="sc" style="color: #5E5E5E;">$</span>target) {</span>
<span id="cb6-221">        <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-222">          qmd,</span>
<span id="cb6-223">          <span class="dv" style="color: #AD0000;">1</span>L,</span>
<span id="cb6-224">          <span class="st" style="color: #20794D;">"missing_include"</span>,</span>
<span id="cb6-225">          <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb6-226">            <span class="st" style="color: #20794D;">"Companion script '%s' is not embedded with {{&lt; include %s &gt;}}"</span>,</span>
<span id="cb6-227">            rel_script_link,</span>
<span id="cb6-228">            rel_script_link</span>
<span id="cb6-229">          )</span>
<span id="cb6-230">        )</span>
<span id="cb6-231">      }</span>
<span id="cb6-232">    }</span>
<span id="cb6-233"></span>
<span id="cb6-234">    <span class="co" style="color: #5E5E5E;"># Check for unlinked prose paths</span></span>
<span id="cb6-235">    path_pattern <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"(?:^|[^a-zA-Z0-9_.-])(?:scripts/|templates/|</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">./</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">./templates/)"</span></span>
<span id="cb6-236">    <span class="co" style="color: #5E5E5E;"># A fence closes only on a bare run of at least as many backticks as</span></span>
<span id="cb6-237">    <span class="co" style="color: #5E5E5E;"># opened it, so a ```` fence can show a ``` example inside it.</span></span>
<span id="cb6-238">    fence_len <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="dv" style="color: #AD0000;">0</span>L</span>
<span id="cb6-239"></span>
<span id="cb6-240">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (i <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_along</span>(lines)) {</span>
<span id="cb6-241">      line <span class="ot" style="color: #003B4F;">&lt;-</span> lines[i]</span>
<span id="cb6-242">      ticks <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">nchar</span>(<span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"^(`*).*$"</span>, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">1"</span>, line))</span>
<span id="cb6-243">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (ticks <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">3</span>L) {</span>
<span id="cb6-244">        <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (fence_len <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-245">          fence_len <span class="ot" style="color: #003B4F;">&lt;-</span> ticks</span>
<span id="cb6-246">          <span class="cf" style="color: #003B4F;
font-weight: bold;">next</span></span>
<span id="cb6-247">        }</span>
<span id="cb6-248">        <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (ticks <span class="sc" style="color: #5E5E5E;">&gt;=</span> fence_len <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"^`+</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*$"</span>, line)) {</span>
<span id="cb6-249">          fence_len <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="dv" style="color: #AD0000;">0</span>L</span>
<span id="cb6-250">          <span class="cf" style="color: #003B4F;
font-weight: bold;">next</span></span>
<span id="cb6-251">        }</span>
<span id="cb6-252">      }</span>
<span id="cb6-253">      in_fence <span class="ot" style="color: #003B4F;">&lt;-</span> fence_len <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L</span>
<span id="cb6-254"></span>
<span id="cb6-255">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">trimws</span>(line) <span class="sc" style="color: #5E5E5E;">%in%</span> allow) {</span>
<span id="cb6-256">        <span class="cf" style="color: #003B4F;
font-weight: bold;">next</span></span>
<span id="cb6-257">      }</span>
<span id="cb6-258"></span>
<span id="cb6-259">      <span class="co" style="color: #5E5E5E;"># Full URLs in hosting examples are not repository-relative paths.</span></span>
<span id="cb6-260">      path_text <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">gsub</span>(<span class="st" style="color: #20794D;">"https?://[^[:space:]`</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">&lt;&gt;]+"</span>, <span class="st" style="color: #20794D;">""</span>, line, <span class="at" style="color: #657422;">perl =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-261"></span>
<span id="cb6-262">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (in_fence) {</span>
<span id="cb6-263">        <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">grepl</span>(path_pattern, path_text, <span class="at" style="color: #657422;">perl =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)) {</span>
<span id="cb6-264">          <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"^</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">{</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">{&lt;</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*include</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s+</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">S+</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*&gt;</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">}</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">}</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">s*$"</span>, line)) {</span>
<span id="cb6-265">            <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-266">              qmd,</span>
<span id="cb6-267">              i,</span>
<span id="cb6-268">              <span class="st" style="color: #20794D;">"forbidden_code_path"</span>,</span>
<span id="cb6-269">              <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb6-270">                <span class="st" style="color: #20794D;">"Forbidden companion path inside code block: %s"</span>,</span>
<span id="cb6-271">                <span class="fu" style="color: #4758AB;">trimws</span>(line)</span>
<span id="cb6-272">              )</span>
<span id="cb6-273">            )</span>
<span id="cb6-274">          }</span>
<span id="cb6-275">        }</span>
<span id="cb6-276">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb6-277">        stripped <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">gsub</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">[[^</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">]]*</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">]</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">([^)]+</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">)"</span>, <span class="st" style="color: #20794D;">""</span>, path_text, <span class="at" style="color: #657422;">perl =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-278">        <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">grepl</span>(path_pattern, stripped, <span class="at" style="color: #657422;">perl =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)) {</span>
<span id="cb6-279">          <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-280">            qmd,</span>
<span id="cb6-281">            i,</span>
<span id="cb6-282">            <span class="st" style="color: #20794D;">"unlinked_prose"</span>,</span>
<span id="cb6-283">            <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Unlinked companion path in prose: %s"</span>, <span class="fu" style="color: #4758AB;">trimws</span>(line))</span>
<span id="cb6-284">          )</span>
<span id="cb6-285">        }</span>
<span id="cb6-286">      }</span>
<span id="cb6-287">    }</span>
<span id="cb6-288">  }</span>
<span id="cb6-289"></span>
<span id="cb6-290">  <span class="co" style="color: #5E5E5E;"># Check for orphaned template files</span></span>
<span id="cb6-291">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (tmpl <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> all_templates) {</span>
<span id="cb6-292">    tmpl_norm <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">normalizePath</span>(tmpl, <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb6-293">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>tmpl_norm <span class="sc" style="color: #5E5E5E;">%in%</span> linked_template_paths) {</span>
<span id="cb6-294">      rel_tmpl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">startsWith</span>(tmpl_norm, <span class="fu" style="color: #4758AB;">paste0</span>(root, <span class="st" style="color: #20794D;">"/"</span>))) {</span>
<span id="cb6-295">        <span class="fu" style="color: #4758AB;">substring</span>(tmpl_norm, <span class="fu" style="color: #4758AB;">nchar</span>(root) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">2</span>L)</span>
<span id="cb6-296">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb6-297">        tmpl_norm</span>
<span id="cb6-298">      }</span>
<span id="cb6-299">      <span class="fu" style="color: #4758AB;">add_problem</span>(</span>
<span id="cb6-300">        tmpl,</span>
<span id="cb6-301">        <span class="dv" style="color: #AD0000;">1</span>L,</span>
<span id="cb6-302">        <span class="st" style="color: #20794D;">"unlinked_template"</span>,</span>
<span id="cb6-303">        <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Template file '%s' is not linked from any post"</span>, rel_tmpl)</span>
<span id="cb6-304">      )</span>
<span id="cb6-305">    }</span>
<span id="cb6-306">  }</span>
<span id="cb6-307"></span>
<span id="cb6-308">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(problems) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-309">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb6-310">      <span class="at" style="color: #657422;">file =</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-311">      <span class="at" style="color: #657422;">line =</span> <span class="fu" style="color: #4758AB;">integer</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-312">      <span class="at" style="color: #657422;">rule =</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-313">      <span class="at" style="color: #657422;">message =</span> <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">0</span>),</span>
<span id="cb6-314">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb6-315">    ))</span>
<span id="cb6-316">  }</span>
<span id="cb6-317"></span>
<span id="cb6-318">  <span class="fu" style="color: #4758AB;">do.call</span>(rbind, problems)</span>
<span id="cb6-319">}</span>
<span id="cb6-320"></span>
<span id="cb6-321"><span class="co" style="color: #5E5E5E;"># Standalone demo: builds a mock site in tempdir(), seeds issues, and prints report</span></span>
<span id="cb6-322"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-323">  demo_root <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="fu" style="color: #4758AB;">paste0</span>(<span class="st" style="color: #20794D;">"companion-demo-"</span>, <span class="fu" style="color: #4758AB;">Sys.getpid</span>()))</span>
<span id="cb6-324">  <span class="fu" style="color: #4758AB;">dir.create</span>(</span>
<span id="cb6-325">    <span class="fu" style="color: #4758AB;">file.path</span>(demo_root, <span class="st" style="color: #20794D;">"posts"</span>, <span class="st" style="color: #20794D;">"analysis-demo"</span>, <span class="st" style="color: #20794D;">"scripts"</span>),</span>
<span id="cb6-326">    <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb6-327">  )</span>
<span id="cb6-328">  <span class="fu" style="color: #4758AB;">dir.create</span>(<span class="fu" style="color: #4758AB;">file.path</span>(demo_root, <span class="st" style="color: #20794D;">"templates"</span>), <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-329"></span>
<span id="cb6-330">  <span class="co" style="color: #5E5E5E;"># Create mock template</span></span>
<span id="cb6-331">  tmpl_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_root, <span class="st" style="color: #20794D;">"templates"</span>, <span class="st" style="color: #20794D;">"pipeline.yml"</span>)</span>
<span id="cb6-332">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="st" style="color: #20794D;">"name: pipeline"</span>, tmpl_file)</span>
<span id="cb6-333"></span>
<span id="cb6-334">  <span class="co" style="color: #5E5E5E;"># Create mock script</span></span>
<span id="cb6-335">  script_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(</span>
<span id="cb6-336">    demo_root,</span>
<span id="cb6-337">    <span class="st" style="color: #20794D;">"posts"</span>,</span>
<span id="cb6-338">    <span class="st" style="color: #20794D;">"analysis-demo"</span>,</span>
<span id="cb6-339">    <span class="st" style="color: #20794D;">"scripts"</span>,</span>
<span id="cb6-340">    <span class="st" style="color: #20794D;">"demo.R"</span></span>
<span id="cb6-341">  )</span>
<span id="cb6-342">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"# Demo script"</span>, <span class="st" style="color: #20794D;">"message('Hello from demo!')"</span>), script_file)</span>
<span id="cb6-343"></span>
<span id="cb6-344">  <span class="co" style="color: #5E5E5E;"># Create mock post with deliberate defects:</span></span>
<span id="cb6-345">  <span class="co" style="color: #5E5E5E;"># 1. Unlinked script (script exists, but never linked or included)</span></span>
<span id="cb6-346">  <span class="co" style="color: #5E5E5E;"># 2. Broken link to non-existent script</span></span>
<span id="cb6-347">  <span class="co" style="color: #5E5E5E;"># 3. Unlinked prose path</span></span>
<span id="cb6-348">  <span class="co" style="color: #5E5E5E;"># 4. Missing ## Companion code section</span></span>
<span id="cb6-349">  post_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_root, <span class="st" style="color: #20794D;">"posts"</span>, <span class="st" style="color: #20794D;">"analysis-demo"</span>, <span class="st" style="color: #20794D;">"index.qmd"</span>)</span>
<span id="cb6-350">  <span class="fu" style="color: #4758AB;">writeLines</span>(</span>
<span id="cb6-351">    <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb6-352">      <span class="st" style="color: #20794D;">"---"</span>,</span>
<span id="cb6-353">      <span class="st" style="color: #20794D;">"title: 'Mock Analysis'"</span>,</span>
<span id="cb6-354">      <span class="st" style="color: #20794D;">"---"</span>,</span>
<span id="cb6-355">      <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb6-356">      <span class="st" style="color: #20794D;">"This post discusses scripts/demo.R in prose without linking it."</span>,</span>
<span id="cb6-357">      <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb6-358">      <span class="st" style="color: #20794D;">"Check out [broken file](scripts/missing.R)."</span>,</span>
<span id="cb6-359">      <span class="st" style="color: #20794D;">""</span></span>
<span id="cb6-360">    ),</span>
<span id="cb6-361">    post_file</span>
<span id="cb6-362">  )</span>
<span id="cb6-363"></span>
<span id="cb6-364">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Running companion check on mock Quarto site with planted defects...</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb6-365">  report <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">check_companions</span>(demo_root)</span>
<span id="cb6-366"></span>
<span id="cb6-367">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">nrow</span>(report) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb6-368">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Identified %d companion code issues:</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">"</span>, <span class="fu" style="color: #4758AB;">nrow</span>(report)))</span>
<span id="cb6-369">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (k <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_len</span>(<span class="fu" style="color: #4758AB;">nrow</span>(report))) {</span>
<span id="cb6-370">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb6-371">        <span class="st" style="color: #20794D;">"- [%s] %s:%d - %s</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb6-372">        report<span class="sc" style="color: #5E5E5E;">$</span>rule[k],</span>
<span id="cb6-373">        report<span class="sc" style="color: #5E5E5E;">$</span>file[k],</span>
<span id="cb6-374">        report<span class="sc" style="color: #5E5E5E;">$</span>line[k],</span>
<span id="cb6-375">        report<span class="sc" style="color: #5E5E5E;">$</span>message[k]</span>
<span id="cb6-376">      ))</span>
<span id="cb6-377">    }</span>
<span id="cb6-378">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb6-379">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"All companion checks passed cleanly.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb6-380">  }</span>
<span id="cb6-381"></span>
<span id="cb6-382">  <span class="fu" style="color: #4758AB;">unlink</span>(demo_root, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-383">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Quarto documentation</strong></p>
<ul>
<li><strong>Quarto Includes</strong>: <a href="https://quarto.org/docs/authoring/includes.html">quarto.org/docs/authoring/includes.html</a></li>
<li><strong>Quarto Shortcode Escaping</strong>: <a href="https://quarto.org/docs/extensions/shortcodes.html#escaping">quarto.org/docs/extensions/shortcodes.html#escaping</a></li>
<li><strong>Quarto HTML Code Tools</strong>: <a href="https://quarto.org/docs/output-formats/html-code.html#code-tools">quarto.org/docs/output-formats/html-code.html#code-tools</a></li>
<li><strong>Quarto Code Folding</strong>: <a href="https://quarto.org/docs/output-formats/html-code.html#folding-code">quarto.org/docs/output-formats/html-code.html#folding-code</a></li>
<li><strong>Quarto Code Execution and Freeze</strong>: <a href="https://quarto.org/docs/projects/code-execution.html#freeze">quarto.org/docs/projects/code-execution.html#freeze</a></li>
</ul>
<p><strong>Web documentation platforms</strong></p>
<ul>
<li><strong>Material for MkDocs Snippets</strong>: <a href="https://squidfunk.github.io/mkdocs-material/reference/code-blocks/">squidfunk.github.io/mkdocs-material/reference/code-blocks/</a></li>
<li><strong>PyMdown Extensions Snippets</strong>: <a href="https://facelessuser.github.io/pymdown-extensions/extensions/snippets/">facelessuser.github.io/pymdown-extensions/extensions/snippets/</a></li>
<li><strong>Docusaurus Code Blocks</strong>: <a href="https://docusaurus.io/docs/markdown-features/react#importing-code-snippets">docusaurus.io/docs/markdown-features/react#importing-code-snippets</a></li>
<li><strong>Sphinx Literal Include Directive</strong>: <a href="https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude">sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude</a></li>
<li><strong>Lychee Link Checker</strong>: <a href="https://lychee.cli.rs/">lychee.cli.rs</a></li>
</ul>
<p><strong>Interactive R environments</strong></p>
<ul>
<li><strong>Quarto Live</strong>: <a href="https://r-wasm.github.io/quarto-live/">r-wasm.github.io/quarto-live</a></li>
<li><strong>webR Documentation</strong>: <a href="https://docs.r-wasm.org/webr/latest/">docs.r-wasm.org/webr/latest</a></li>
</ul>
<p><strong>R packages</strong></p>
<ul>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>withr</strong>: <a href="https://withr.r-lib.org/">withr.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-11-13:</strong> The site’s test files now carry a <code>site-</code> or <code>post-</code> prefix, so the test named here is <code>tests/testthat/test-site-companions.R</code>.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 15 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/handoffs-agentic-context/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 14</span><span class="site-related-card__title">Handoffs &amp; agentic context</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/hosted-site-pitfalls/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 16</span><span class="site-related-card__title">It worked locally: two hosting bugs every check missed</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/building-this-blog/index.html" class="site-link-row" title="How we transformed a 14-part topic site into a Quarto engineering blog and portfolio using URL aliases, living-document conventions, and multi-model agentic collaboration."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Building this blog: from numbered topics to a living Quarto publication</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/index.html" class="site-link-row" title="Validate internal links across rendered documentation in CI using offline link scanners to block broken references before release."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Catch broken links before your readers do</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/series-registry-quarto/index.html" class="site-link-row" title="Model series and related posts as structured data with a YAML registry and a Pandoc Lua filter, guarded by testthat so missing references fail in CI."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Content as data: a series registry for a Quarto blog</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Quarto</category>
  <category>R</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/companion-code/</guid>
  <pubDate>Sat, 26 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Content as data: a series registry for a Quarto blog</title>
  <link>https://insightsurge-dev.web.app/posts/series-registry-quarto/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>As a technical publication grows, articles rarely stand alone: tutorials form sequential tracks, practical guides build on setups, and standalone articles cross-reference deeper dives.</p>
<p>Managing these relationships manually in markdown leads to two failure modes:</p>
<ol type="1">
<li><strong>Stale cross-references.</strong> Numbered directories (<code>topics/01-setup</code>) break when inserting intermediate articles. Switching to flat semantic slugs (<code>posts/setup/</code>) solves URLs, but hand-written “See also” lists decay as slugs change or series are reorganised.</li>
<li><strong>Planned content has nowhere to live.</strong> Roadmaps include planned series that are not yet written. In a file-driven site, planned topics remain invisible, or links to pages that do not yet exist return 404 errors.</li>
</ol>
<p>To scale cleanly, content relationships must be managed as <strong>structured data</strong>.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>Static-site generators decouple content structure from presentation using data files and schemas:</p>
<ul>
<li><strong>Hugo (Related Content):</strong> configured under <code>related</code> in the site configuration, with weighted indices on front matter such as tags, dates or heading fragments, and a score <code>threshold</code>. Templates call <code>.Site.RegularPages.Related .</code> to get a ranked list.</li>
<li><strong>Jekyll (<code>site.related_posts</code>):</strong> up to ten related posts, which by default are simply the ten most recent. Better matches need the <code>--lsi</code> option (latent semantic indexing), which requires the classifier-reborn plugin; GitHub Pages does not support it.</li>
<li><strong>Astro (content collections):</strong> collections are defined in <code>src/content.config.ts</code>, with an optional schema that validates each entry. In a schema, <code>reference()</code> declares a property as an entry from another collection, which templates then query with <code>getEntry()</code> or <code>getEntries()</code>.</li>
<li><strong>Eleventy (<code>_data/</code>):</strong> files in the global data folder are available to every template under their file name, so shared data lives apart from the pages.</li>
</ul>
<p>Across these frameworks, the pattern is consistent: declare relationships in structured data files and let the generator assemble navigation components.</p>
</section>
<section id="the-r-way-content-as-data-in-quarto" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-content-as-data-in-quarto">The R way: Content as data in Quarto</h2>
<p>This blog uses the content-as-data pattern to automate navigation across all series and articles. In Quarto, we implement this with four coordinated components:</p>
<ol type="1">
<li>A YAML series registry (<code>_data/series.yml</code>) declaring all series, tracks, and overarching relationships.</li>
<li>Front matter in posts defining series membership and curated related posts.</li>
<li>A Pandoc Lua filter (<code>_filters/related.lua</code>) that executes during rendering to build navigation cards.</li>
<li>A <code>{testthat}</code> validation test (<code>tests/testthat/test-site-series-registry.R</code>) that catches broken references in CI.</li>
</ol>
<section id="the-series-registry" class="level3">
<h3 class="anchored" data-anchor-id="the-series-registry">1 · The series registry</h3>
<p>The registry file <code>_data/series.yml</code> acts as the single source of truth for all tracks:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="fu" style="color: #4758AB;">series</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> basics</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">status</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> live</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">track</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> engineering</span></span>
<span id="cb1-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">related</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-6"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="fu" style="color: #4758AB;">to</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> testing</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read-next</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">note</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Tests build on foundations."</span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb1-7"></span>
<span id="cb1-8"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> testing</span></span>
<span id="cb1-9"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">status</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> live</span></span>
<span id="cb1-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">track</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> engineering</span></span>
<span id="cb1-11"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">related</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-12"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="fu" style="color: #4758AB;">to</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> basics</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read-first</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">note</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Package and repo setup."</span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb1-13"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="fu" style="color: #4758AB;">to</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> reporting</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> see-also</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">note</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Testing reporting outputs."</span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb1-14"></span>
<span id="cb1-15"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> reporting</span></span>
<span id="cb1-16"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">status</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> planned</span></span>
<span id="cb1-17"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">track</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> pharma</span></span>
<span id="cb1-18"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Clinical Reporting in R"</span></span>
<span id="cb1-19"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">summary</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Tables, listings and figures for clinical studies in R."</span></span>
<span id="cb1-20"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">related</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-21"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="fu" style="color: #4758AB;">to</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> testing</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> builds-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span></code></pre></div></div>
<p>Every series defines an identifier, status (<code>live</code> or <code>planned</code>), track, and typed links. Live series pull their title and summary directly from their overview page (<code>series/&lt;id&gt;.qmd</code>), avoiding duplicated copy. Planned series carry titles and summaries in YAML, presenting a clear roadmap without dead links.</p>
</section>
<section id="post-front-matter" class="level3">
<h3 class="anchored" data-anchor-id="post-front-matter">2 · Post front matter</h3>
<p>Individual posts reference their series and declare hand-picked cross-references:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="pp" style="color: #AD0000;">---</span></span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Writing robust unit tests with testthat"</span></span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;">date</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> 2026-09-27</span></span>
<span id="cb2-4"><span class="fu" style="color: #4758AB;">series</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> testing</span></span>
<span id="cb2-5"><span class="fu" style="color: #4758AB;">order</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">1</span></span>
<span id="cb2-6"><span class="fu" style="color: #4758AB;">categories</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="st" style="color: #20794D;">"R"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Best practices"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb2-7"><span class="fu" style="color: #4758AB;">related</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-8"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="fu" style="color: #4758AB;">post</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> project-structure</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read-first</span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb2-9"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="fu" style="color: #4758AB;">post</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> property-based-testing</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read-next</span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb2-10"><span class="pp" style="color: #AD0000;">---</span></span></code></pre></div></div>
<p>Posts in a series specify <code>series: &lt;id&gt;</code>, a sequential <code>order: &lt;n&gt;</code>, and up to three curated <code>related:</code> entries. Standalone posts (such as this article) omit <code>series:</code> and <code>order:</code>: they receive related cards, but no series header.</p>
</section>
<section id="the-pandoc-lua-filter" class="level3">
<h3 class="anchored" data-anchor-id="the-pandoc-lua-filter">3 · The Pandoc Lua filter</h3>
<p>The filter is listed under <code>filters:</code> in <code>_quarto.yml</code>, so Quarto runs it on every page. It reads the registry and the front matter of every post, works out what the current page needs, and appends Pandoc elements to the end of the page:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode lua code-with-copy"><code class="sourceCode lua"><span id="cb3-1"><span class="co" style="color: #5E5E5E;">-- Simplified from the filter this blog uses. `plain()` turns Pandoc metadata</span></span>
<span id="cb3-2"><span class="co" style="color: #5E5E5E;">-- into Lua strings and tables; `load_site()` reads the registry and, with</span></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;">-- pandoc.system.list_directory(), the front matter of every post.</span></span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="co" style="color: #5E5E5E;">-- The front matter of a .qmd file (or a whole .yml file) as Lua values.</span></span>
<span id="cb3-6"><span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">function</span> read_yaml<span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">path</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">whole_file</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-7">  <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">f</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="fu" style="color: #4758AB;">io.open</span><span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">path</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">"r"</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-8">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">not</span> <span class="va" style="color: #111111;">f</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">then</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">nil</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">end</span></span>
<span id="cb3-9">  <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">text</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="va" style="color: #111111;">f</span><span class="op" style="color: #5E5E5E;">:</span><span class="fu" style="color: #4758AB;">read</span><span class="op" style="color: #5E5E5E;">(</span><span class="st" style="color: #20794D;">"a"</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-10">  <span class="va" style="color: #111111;">f</span><span class="op" style="color: #5E5E5E;">:</span><span class="fu" style="color: #4758AB;">close</span><span class="op" style="color: #5E5E5E;">()</span></span>
<span id="cb3-11">  <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">pattern</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"^%-%-%-</span><span class="sc" style="color: #5E5E5E;">\r</span><span class="st" style="color: #20794D;">?</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">(.-)</span><span class="sc" style="color: #5E5E5E;">\r</span><span class="st" style="color: #20794D;">?</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">%-%-%-"</span></span>
<span id="cb3-12">  <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">yaml</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="va" style="color: #111111;">whole_file</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">and</span> <span class="va" style="color: #111111;">text</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">or</span> <span class="va" style="color: #111111;">text</span><span class="op" style="color: #5E5E5E;">:</span><span class="fu" style="color: #4758AB;">match</span><span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">pattern</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-13">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">not</span> <span class="va" style="color: #111111;">yaml</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">then</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> <span class="op" style="color: #5E5E5E;">{}</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">end</span></span>
<span id="cb3-14">  <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> plain<span class="op" style="color: #5E5E5E;">(</span></span>
<span id="cb3-15">    <span class="va" style="color: #111111;">pandoc</span><span class="op" style="color: #5E5E5E;">.</span>read<span class="op" style="color: #5E5E5E;">(</span><span class="st" style="color: #20794D;">"---</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span> <span class="op" style="color: #5E5E5E;">..</span> <span class="va" style="color: #111111;">yaml</span> <span class="op" style="color: #5E5E5E;">..</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">---</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">"markdown"</span><span class="op" style="color: #5E5E5E;">).</span><span class="va" style="color: #111111;">meta</span></span>
<span id="cb3-16">  <span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-17"><span class="kw" style="color: #003B4F;
font-weight: bold;">end</span></span>
<span id="cb3-18"></span>
<span id="cb3-19"><span class="co" style="color: #5E5E5E;">-- A card is a Pandoc Link to a .qmd file, so Quarto resolves the URL.</span></span>
<span id="cb3-20"><span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">function</span> card<span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">href</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">label</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">title</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">body</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-21">  <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> <span class="va" style="color: #111111;">pandoc</span><span class="op" style="color: #5E5E5E;">.</span>Link<span class="op" style="color: #5E5E5E;">({</span></span>
<span id="cb3-22">    <span class="va" style="color: #111111;">pandoc</span><span class="op" style="color: #5E5E5E;">.</span>Span<span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">label</span><span class="op" style="color: #5E5E5E;">,</span> <span class="op" style="color: #5E5E5E;">{</span> <span class="va" style="color: #111111;">class</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"eyebrow"</span> <span class="op" style="color: #5E5E5E;">}),</span></span>
<span id="cb3-23">    <span class="va" style="color: #111111;">pandoc</span><span class="op" style="color: #5E5E5E;">.</span>Span<span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">title</span><span class="op" style="color: #5E5E5E;">,</span> <span class="op" style="color: #5E5E5E;">{</span> <span class="va" style="color: #111111;">class</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"card-title"</span> <span class="op" style="color: #5E5E5E;">}),</span></span>
<span id="cb3-24">    <span class="va" style="color: #111111;">pandoc</span><span class="op" style="color: #5E5E5E;">.</span>Span<span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">body</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">or</span> <span class="st" style="color: #20794D;">""</span><span class="op" style="color: #5E5E5E;">,</span> <span class="op" style="color: #5E5E5E;">{</span> <span class="va" style="color: #111111;">class</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"card-body"</span> <span class="op" style="color: #5E5E5E;">}),</span></span>
<span id="cb3-25">  <span class="op" style="color: #5E5E5E;">},</span> <span class="va" style="color: #111111;">href</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">""</span><span class="op" style="color: #5E5E5E;">,</span> <span class="op" style="color: #5E5E5E;">{</span> <span class="va" style="color: #111111;">class</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"related-card"</span> <span class="op" style="color: #5E5E5E;">})</span></span>
<span id="cb3-26"><span class="kw" style="color: #003B4F;
font-weight: bold;">end</span></span>
<span id="cb3-27"></span>
<span id="cb3-28"><span class="kw" style="color: #003B4F;
font-weight: bold;">function</span> Pandoc<span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">doc</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-29">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">not</span> <span class="va" style="color: #111111;">quarto</span><span class="op" style="color: #5E5E5E;">.</span><span class="va" style="color: #111111;">doc</span><span class="op" style="color: #5E5E5E;">.</span>is_format<span class="op" style="color: #5E5E5E;">(</span><span class="st" style="color: #20794D;">"html"</span><span class="op" style="color: #5E5E5E;">)</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">then</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> <span class="va" style="color: #111111;">doc</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">end</span></span>
<span id="cb3-30">  <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">rel</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="va" style="color: #111111;">pandoc</span><span class="op" style="color: #5E5E5E;">.</span><span class="va" style="color: #111111;">path</span><span class="op" style="color: #5E5E5E;">.</span>make_relative<span class="op" style="color: #5E5E5E;">(</span></span>
<span id="cb3-31">    <span class="va" style="color: #111111;">quarto</span><span class="op" style="color: #5E5E5E;">.</span><span class="va" style="color: #111111;">doc</span><span class="op" style="color: #5E5E5E;">.</span><span class="va" style="color: #111111;">input_file</span><span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb3-32">    <span class="va" style="color: #111111;">quarto</span><span class="op" style="color: #5E5E5E;">.</span><span class="va" style="color: #111111;">project</span><span class="op" style="color: #5E5E5E;">.</span><span class="va" style="color: #111111;">directory</span></span>
<span id="cb3-33">  <span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-34">  <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">pattern</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="st" style="color: #20794D;">"^posts/([^/]+)/index%.qmd$"</span></span>
<span id="cb3-35">  <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">slug</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="va" style="color: #111111;">rel</span><span class="op" style="color: #5E5E5E;">:</span><span class="fu" style="color: #4758AB;">match</span><span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">pattern</span><span class="op" style="color: #5E5E5E;">)</span></span>
<span id="cb3-36">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> <span class="va" style="color: #111111;">slug</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">then</span></span>
<span id="cb3-37">    <span class="kw" style="color: #003B4F;
font-weight: bold;">local</span> <span class="va" style="color: #111111;">series</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">posts</span> <span class="op" style="color: #5E5E5E;">=</span> load_site<span class="op" style="color: #5E5E5E;">()</span></span>
<span id="cb3-38">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> <span class="cn" style="color: #8f5902;">_</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">block</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">ipairs</span><span class="op" style="color: #5E5E5E;">(</span>post_blocks<span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">slug</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">series</span><span class="op" style="color: #5E5E5E;">,</span> <span class="va" style="color: #111111;">posts</span><span class="op" style="color: #5E5E5E;">))</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">do</span></span>
<span id="cb3-39">      <span class="va" style="color: #111111;">doc</span><span class="op" style="color: #5E5E5E;">.</span><span class="va" style="color: #111111;">blocks</span><span class="op" style="color: #5E5E5E;">:</span><span class="fu" style="color: #4758AB;">insert</span><span class="op" style="color: #5E5E5E;">(</span><span class="va" style="color: #111111;">block</span><span class="op" style="color: #5E5E5E;">)</span>   <span class="co" style="color: #5E5E5E;">-- series nav, then "Keep reading" cards</span></span>
<span id="cb3-40">    <span class="cf" style="color: #003B4F;
font-weight: bold;">end</span></span>
<span id="cb3-41">  <span class="cf" style="color: #003B4F;
font-weight: bold;">end</span></span>
<span id="cb3-42">  <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> <span class="va" style="color: #111111;">doc</span></span>
<span id="cb3-43"><span class="kw" style="color: #003B4F;
font-weight: bold;">end</span></span></code></pre></div></div>
<p>Because the filter emits native Pandoc <code>Link</code> elements targeting <code>.qmd</code> files, Quarto resolves them to final URLs, allowing offline link checkers to verify them automatically.</p>
</section>
</section>
<section id="design-decisions-and-lessons-learned" class="level2">
<h2 class="anchored" data-anchor-id="design-decisions-and-lessons-learned">Design decisions and lessons learned</h2>
<p>Refining this system surfaced several practical engineering lessons:</p>
<section id="hand-picked-links-beat-automated-heuristics" class="level3">
<h3 class="anchored" data-anchor-id="hand-picked-links-beat-automated-heuristics">1 · Hand-picked links beat automated heuristics</h3>
<p>We initially attempted to populate cards entirely by matching category overlap. The recommendations were poor. High-level technical categories (such as “R” or “Best practices”) are broad; two posts sharing those categories might cover unrelated topics like OIDC secrets and SDTM mapping.</p>
<p>We switched to a layered heuristic: 1. <strong>Curated first:</strong> Authors explicitly define up to three targets in <code>related:</code>. 2. <strong>Category fill-in:</strong> if a post lists fewer than three, the filter fills the gaps with posts from other series (or from no series) that share at least two categories, ranked by the number shared, then newest first. Posts in the same series are already one click away in the series nav.</p>
</section>
<section id="typed-links-tell-the-reader-why-to-click" class="level3">
<h3 class="anchored" data-anchor-id="typed-links-tell-the-reader-why-to-click">2 · Typed links tell the reader why to click</h3>
<p>A generic “Related” label forces readers to guess why an article was suggested. Typed relationships clarify intent immediately: - <code>read-first</code>: Essential background before tackling the current post. - <code>read-next</code>: The logical next step in the workflow. - <code>builds-on</code>: Advanced techniques expanding the core concept. - <code>see-also</code>: Tangential or complementary practices in another domain.</p>
</section>
<section id="why-a-lua-filter-rather-than-r-in-ci" class="level3">
<h3 class="anchored" data-anchor-id="why-a-lua-filter-rather-than-r-in-ci">3 · Why a Lua filter rather than R in CI</h3>
<p>Our site keeps one rule: <strong>rendering needs no R</strong>. The render job in CI installs Quarto, which bundles Pandoc, but not R.</p>
<p>We considered two alternatives: - <strong>An R script generating JSON:</strong> An R script could parse front matter with <code>{yaml}</code> and output a committed JSON file. However, this requires committing generated artifacts and enforcing freshness tests in CI. - <strong>Client-side JavaScript over <code>search.json</code>:</strong> the browser could build the cards from Quarto’s search index. But the cards would exist only after JavaScript runs, not in the HTML, so neither readers without JavaScript nor a link checker would see them.</p>
<p>A Lua filter runs inside Quarto with nothing extra to install, and the cards are part of the rendered HTML.</p>
</section>
<section id="gotcha-listing-placement-and-container-ids" class="level3">
<h3 class="anchored" data-anchor-id="gotcha-listing-placement-and-container-ids">4 · Gotcha: Listing placement and container IDs</h3>
<p>When adding cards to series landing pages, we ran into an unexpected layout issue. <a href="https://quarto.org/docs/websites/website-listings.html#listing-location">Quarto’s listings documentation</a> explains that listings are appended to the page by default; a div whose id matches the listing’s id controls where one appears.</p>
<p>The trap is which <code>id</code>. In our tests with Quarto 1.8.27, a listing without an explicit <code>id</code> looks for a div with the id <code>listing</code>, while the rendered listing container gets <code>id="listing-listing"</code>. We first added a div with the container’s id, and Quarto ignored it. Without the right div, the listing is appended after everything else on the page, so it landed <em>below</em> the cards our filter had added.</p>
<p>The filter now checks for a div with the id <code>listing</code> and, if there isn’t one, inserts <code>pandoc.Div({}, { id = "listing" })</code> before its cards. Giving each listing an explicit <code>id</code> and placing the div by hand works too; the filter just means no page has to remember.</p>
</section>
</section>
<section id="the-testthat-safety-net" class="level2">
<h2 class="anchored" data-anchor-id="the-testthat-safety-net">The testthat safety net</h2>
<p>Our filter skips anything it can’t resolve, so a typo never breaks the build. The cost: if an author mistypes a slug in <code>related:</code>, the card quietly disappears.</p>
<p>Silent omission creates a subtle failure mode: 1. A mistyped slug drops the card from rendering. 2. Because the link never renders into HTML, an offline link checker cannot detect a 404 error. 3. The broken recommendation remains unnoticed in production.</p>
<p>To prevent this, we write a <code>{testthat}</code> validation test. R developers routinely write tests for data frames and analysis pipelines; using <code>{testthat}</code> to validate publishing metadata is a natural extension:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;">library</span>(testthat)</span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;"># Front matter from two posts, as yaml::yaml.load() returns it</span></span>
<span id="cb4-4">posts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb4-5">  <span class="at" style="color: #657422;">intro =</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb4-6">    <span class="at" style="color: #657422;">series =</span> <span class="st" style="color: #20794D;">"basics"</span>,</span>
<span id="cb4-7">    <span class="at" style="color: #657422;">order =</span> <span class="dv" style="color: #AD0000;">1</span>L,</span>
<span id="cb4-8">    <span class="at" style="color: #657422;">related =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">post =</span> <span class="st" style="color: #20794D;">"setup"</span>, <span class="at" style="color: #657422;">type =</span> <span class="st" style="color: #20794D;">"read-first"</span>))</span>
<span id="cb4-9">  ),</span>
<span id="cb4-10">  <span class="at" style="color: #657422;">setup =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">related =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">post =</span> <span class="st" style="color: #20794D;">"intro"</span>, <span class="at" style="color: #657422;">type =</span> <span class="st" style="color: #20794D;">"read-next"</span>)))</span>
<span id="cb4-11">)</span>
<span id="cb4-12">link_types <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"read-first"</span>, <span class="st" style="color: #20794D;">"read-next"</span>, <span class="st" style="color: #20794D;">"builds-on"</span>, <span class="st" style="color: #20794D;">"see-also"</span>)</span>
<span id="cb4-13"></span>
<span id="cb4-14"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"every related link resolves"</span>, {</span>
<span id="cb4-15">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (slug <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">names</span>(posts)) {</span>
<span id="cb4-16">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (r <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> posts[[slug]]<span class="sc" style="color: #5E5E5E;">$</span>related) {</span>
<span id="cb4-17">      <span class="fu" style="color: #4758AB;">expect_true</span>(r<span class="sc" style="color: #5E5E5E;">$</span>post <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">names</span>(posts), <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">paste</span>(slug, <span class="st" style="color: #20794D;">"-&gt;"</span>, r<span class="sc" style="color: #5E5E5E;">$</span>post))</span>
<span id="cb4-18">      <span class="fu" style="color: #4758AB;">expect_false</span>(<span class="fu" style="color: #4758AB;">identical</span>(r<span class="sc" style="color: #5E5E5E;">$</span>post, slug), <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">paste</span>(slug, <span class="st" style="color: #20794D;">"self-link"</span>))</span>
<span id="cb4-19">      <span class="fu" style="color: #4758AB;">expect_true</span>(r<span class="sc" style="color: #5E5E5E;">$</span>type <span class="sc" style="color: #5E5E5E;">%in%</span> link_types, <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">paste</span>(slug, r<span class="sc" style="color: #5E5E5E;">$</span>type))</span>
<span id="cb4-20">    }</span>
<span id="cb4-21">  }</span>
<span id="cb4-22">})</span></code></pre></div></div>
<p>The real test also checks the registry, and that live series match their pages and the navbar. To check that it works, we broke the site’s data on purpose in four ways: - An unknown series link (<code>to: phantom-series</code>). - A broken post slug (<code>post: missing-slug</code>). - An invalid relationship type (<code>type: deep-dive</code>). - A duplicate order index (<code>order: 1</code> assigned twice in the same series).</p>
<p>Each one failed the test. The same test runs in CI, so a typo fails the pull request instead of reaching readers.</p>
</section>
<section id="what-is-next" class="level2">
<h2 class="anchored" data-anchor-id="what-is-next">What is next</h2>
<p>Treating content relationships as structured data lays the groundwork for planned enhancements:</p>
<ul>
<li><strong>Learning paths:</strong> Curating cross-series reading paths for specific roles (such as onboarding clinical programmers).</li>
<li><strong>Visual series maps:</strong> Rendering dependency graphs that illustrate how foundational practices lead to advanced workflows.</li>
<li><strong>Track-grouped navigation:</strong> Organizing top-level navigation dropdowns by track as the library of series expands.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/series-registry-quarto/scripts/check-registry.R">View <code>check-registry.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/series-registry-quarto/scripts/check-registry.R" download="check-registry.R">Download</a></p>
<p>The standalone validator uses base R and <code>{yaml}</code>. It exposes <code>read_registry()</code>, <code>read_front_matter()</code>, <code>scan_posts()</code>, and <code>check_registry()</code>. Run the downloaded file with <code>Rscript check-registry.R</code> from the directory where you saved it. Its demo builds a tiny site with a broken post slug and prints the problem; the tests also cover a clean site and the four planted error types.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>check-registry.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># Validates a Quarto series registry and post front matter.</span></span>
<span id="cb5-2"><span class="co" style="color: #5E5E5E;"># Checks that series IDs, post slugs, link types, and series ordering</span></span>
<span id="cb5-3"><span class="co" style="color: #5E5E5E;"># resolve without broken references or gaps.</span></span>
<span id="cb5-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb5-5"><span class="co" style="color: #5E5E5E;"># Run the downloaded file from the directory where you saved it:</span></span>
<span id="cb5-6"><span class="co" style="color: #5E5E5E;">#   Rscript check-registry.R</span></span>
<span id="cb5-7"></span>
<span id="cb5-8">read_registry <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb5-9">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">file.exists</span>(path)) {</span>
<span id="cb5-10">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Registry file '%s' does not exist."</span>, path), <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb5-11">  }</span>
<span id="cb5-12">  data <span class="ot" style="color: #003B4F;">&lt;-</span> yaml<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">read_yaml</span>(path)</span>
<span id="cb5-13">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.list</span>(data) <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(data<span class="sc" style="color: #5E5E5E;">$</span>series)) {</span>
<span id="cb5-14">    data<span class="sc" style="color: #5E5E5E;">$</span>series</span>
<span id="cb5-15">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.list</span>(data)) {</span>
<span id="cb5-16">    data</span>
<span id="cb5-17">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb5-18">    <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb5-19">  }</span>
<span id="cb5-20">}</span>
<span id="cb5-21"></span>
<span id="cb5-22">read_front_matter <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb5-23">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">file.exists</span>(path)) {</span>
<span id="cb5-24">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>())</span>
<span id="cb5-25">  }</span>
<span id="cb5-26">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readLines</span>(path, <span class="at" style="color: #657422;">warn =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb5-27">  fences <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">which</span>(lines <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"---"</span>)</span>
<span id="cb5-28">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(fences) <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">2</span>) {</span>
<span id="cb5-29">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>())</span>
<span id="cb5-30">  }</span>
<span id="cb5-31">  yaml_text <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">paste</span>(lines[(fences[<span class="dv" style="color: #AD0000;">1</span>] <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>)<span class="sc" style="color: #5E5E5E;">:</span>(fences[<span class="dv" style="color: #AD0000;">2</span>] <span class="sc" style="color: #5E5E5E;">-</span> <span class="dv" style="color: #AD0000;">1</span>)], <span class="at" style="color: #657422;">collapse =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb5-32">  parsed <span class="ot" style="color: #003B4F;">&lt;-</span> yaml<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">yaml.load</span>(yaml_text)</span>
<span id="cb5-33">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.list</span>(parsed)) parsed <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb5-34">}</span>
<span id="cb5-35"></span>
<span id="cb5-36">scan_posts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(dir) {</span>
<span id="cb5-37">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(dir)) {</span>
<span id="cb5-38">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>())</span>
<span id="cb5-39">  }</span>
<span id="cb5-40">  slugs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list.files</span>(dir)</span>
<span id="cb5-41">  slugs <span class="ot" style="color: #003B4F;">&lt;-</span> slugs[<span class="fu" style="color: #4758AB;">dir.exists</span>(<span class="fu" style="color: #4758AB;">file.path</span>(dir, slugs))]</span>
<span id="cb5-42">  post_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(dir, slugs, <span class="st" style="color: #20794D;">"index.qmd"</span>)</span>
<span id="cb5-43">  valid <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.exists</span>(post_files)</span>
<span id="cb5-44">  slugs <span class="ot" style="color: #003B4F;">&lt;-</span> slugs[valid]</span>
<span id="cb5-45">  post_files <span class="ot" style="color: #003B4F;">&lt;-</span> post_files[valid]</span>
<span id="cb5-46">  stats<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">setNames</span>(</span>
<span id="cb5-47">    <span class="fu" style="color: #4758AB;">lapply</span>(post_files, read_front_matter),</span>
<span id="cb5-48">    slugs</span>
<span id="cb5-49">  )</span>
<span id="cb5-50">}</span>
<span id="cb5-51"></span>
<span id="cb5-52">check_registry <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb5-53">  registry,</span>
<span id="cb5-54">  posts,</span>
<span id="cb5-55">  <span class="at" style="color: #657422;">allowed_types =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"read-first"</span>, <span class="st" style="color: #20794D;">"read-next"</span>, <span class="st" style="color: #20794D;">"builds-on"</span>, <span class="st" style="color: #20794D;">"see-also"</span>)</span>
<span id="cb5-56">) {</span>
<span id="cb5-57">  problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb5-58"></span>
<span id="cb5-59">  record <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(scope, item, problem) {</span>
<span id="cb5-60">    problems[[<span class="fu" style="color: #4758AB;">length</span>(problems) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L]] <span class="ot" style="color: #003B4F;">&lt;&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb5-61">      <span class="at" style="color: #657422;">scope =</span> scope,</span>
<span id="cb5-62">      <span class="at" style="color: #657422;">item =</span> item,</span>
<span id="cb5-63">      <span class="at" style="color: #657422;">problem =</span> problem</span>
<span id="cb5-64">    )</span>
<span id="cb5-65">  }</span>
<span id="cb5-66"></span>
<span id="cb5-67">  series_ids <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">vapply</span>(</span>
<span id="cb5-68">    registry,</span>
<span id="cb5-69">    <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(s) <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(s<span class="sc" style="color: #5E5E5E;">$</span>id)) <span class="fu" style="color: #4758AB;">as.character</span>(s<span class="sc" style="color: #5E5E5E;">$</span>id) <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb5-70">    <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">1</span>)</span>
<span id="cb5-71">  )</span>
<span id="cb5-72"></span>
<span id="cb5-73">  <span class="co" style="color: #5E5E5E;"># Check for duplicate series IDs</span></span>
<span id="cb5-74">  dup_ids <span class="ot" style="color: #003B4F;">&lt;-</span> series_ids[<span class="fu" style="color: #4758AB;">nzchar</span>(series_ids) <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="fu" style="color: #4758AB;">duplicated</span>(series_ids)]</span>
<span id="cb5-75">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (dup <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">unique</span>(dup_ids)) {</span>
<span id="cb5-76">    <span class="fu" style="color: #4758AB;">record</span>(<span class="st" style="color: #20794D;">"registry"</span>, dup, <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Duplicate series id '%s'"</span>, dup))</span>
<span id="cb5-77">  }</span>
<span id="cb5-78"></span>
<span id="cb5-79">  <span class="co" style="color: #5E5E5E;"># Validate each series in registry</span></span>
<span id="cb5-80">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (s <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> registry) {</span>
<span id="cb5-81">    sid <span class="ot" style="color: #003B4F;">&lt;-</span> s<span class="sc" style="color: #5E5E5E;">$</span>id <span class="sc" style="color: #5E5E5E;">%||%</span> <span class="st" style="color: #20794D;">"&lt;unnamed&gt;"</span></span>
<span id="cb5-82">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(s<span class="sc" style="color: #5E5E5E;">$</span>status) <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span>s<span class="sc" style="color: #5E5E5E;">$</span>status <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"live"</span>, <span class="st" style="color: #20794D;">"planned"</span>)) {</span>
<span id="cb5-83">      <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-84">        <span class="st" style="color: #20794D;">"registry"</span>,</span>
<span id="cb5-85">        sid,</span>
<span id="cb5-86">        <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Invalid status '%s' in series '%s'"</span>, s<span class="sc" style="color: #5E5E5E;">$</span>status, sid)</span>
<span id="cb5-87">      )</span>
<span id="cb5-88">    }</span>
<span id="cb5-89">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">identical</span>(s<span class="sc" style="color: #5E5E5E;">$</span>status, <span class="st" style="color: #20794D;">"planned"</span>)) {</span>
<span id="cb5-90">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(s<span class="sc" style="color: #5E5E5E;">$</span>title) <span class="sc" style="color: #5E5E5E;">||</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">nzchar</span>(<span class="fu" style="color: #4758AB;">as.character</span>(s<span class="sc" style="color: #5E5E5E;">$</span>title))) {</span>
<span id="cb5-91">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-92">          <span class="st" style="color: #20794D;">"registry"</span>,</span>
<span id="cb5-93">          sid,</span>
<span id="cb5-94">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Planned series '%s' is missing a title"</span>, sid)</span>
<span id="cb5-95">        )</span>
<span id="cb5-96">      }</span>
<span id="cb5-97">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(s<span class="sc" style="color: #5E5E5E;">$</span>summary) <span class="sc" style="color: #5E5E5E;">||</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">nzchar</span>(<span class="fu" style="color: #4758AB;">as.character</span>(s<span class="sc" style="color: #5E5E5E;">$</span>summary))) {</span>
<span id="cb5-98">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-99">          <span class="st" style="color: #20794D;">"registry"</span>,</span>
<span id="cb5-100">          sid,</span>
<span id="cb5-101">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Planned series '%s' is missing a summary"</span>, sid)</span>
<span id="cb5-102">        )</span>
<span id="cb5-103">      }</span>
<span id="cb5-104">    }</span>
<span id="cb5-105">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (edge <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> s<span class="sc" style="color: #5E5E5E;">$</span>related) {</span>
<span id="cb5-106">      target <span class="ot" style="color: #003B4F;">&lt;-</span> edge<span class="sc" style="color: #5E5E5E;">$</span>to <span class="sc" style="color: #5E5E5E;">%||%</span> <span class="st" style="color: #20794D;">"&lt;empty&gt;"</span></span>
<span id="cb5-107">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>target <span class="sc" style="color: #5E5E5E;">%in%</span> series_ids) {</span>
<span id="cb5-108">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-109">          <span class="st" style="color: #20794D;">"registry"</span>,</span>
<span id="cb5-110">          sid,</span>
<span id="cb5-111">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Unknown series link: '%s' references '%s'"</span>, sid, target)</span>
<span id="cb5-112">        )</span>
<span id="cb5-113">      }</span>
<span id="cb5-114">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">identical</span>(target, s<span class="sc" style="color: #5E5E5E;">$</span>id)) {</span>
<span id="cb5-115">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-116">          <span class="st" style="color: #20794D;">"registry"</span>,</span>
<span id="cb5-117">          sid,</span>
<span id="cb5-118">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Series '%s' has a self-link"</span>, sid)</span>
<span id="cb5-119">        )</span>
<span id="cb5-120">      }</span>
<span id="cb5-121">      link_type <span class="ot" style="color: #003B4F;">&lt;-</span> edge<span class="sc" style="color: #5E5E5E;">$</span>type <span class="sc" style="color: #5E5E5E;">%||%</span> <span class="st" style="color: #20794D;">"&lt;missing&gt;"</span></span>
<span id="cb5-122">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>link_type <span class="sc" style="color: #5E5E5E;">%in%</span> allowed_types) {</span>
<span id="cb5-123">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-124">          <span class="st" style="color: #20794D;">"registry"</span>,</span>
<span id="cb5-125">          sid,</span>
<span id="cb5-126">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Invalid link type '%s' in series '%s'"</span>, link_type, sid)</span>
<span id="cb5-127">        )</span>
<span id="cb5-128">      }</span>
<span id="cb5-129">    }</span>
<span id="cb5-130">  }</span>
<span id="cb5-131"></span>
<span id="cb5-132">  <span class="co" style="color: #5E5E5E;"># Live series IDs</span></span>
<span id="cb5-133">  live_series <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">vapply</span>(</span>
<span id="cb5-134">    <span class="fu" style="color: #4758AB;">Filter</span>(<span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(s) <span class="fu" style="color: #4758AB;">identical</span>(s<span class="sc" style="color: #5E5E5E;">$</span>status, <span class="st" style="color: #20794D;">"live"</span>), registry),</span>
<span id="cb5-135">    <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(s) <span class="fu" style="color: #4758AB;">as.character</span>(s<span class="sc" style="color: #5E5E5E;">$</span>id),</span>
<span id="cb5-136">    <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">1</span>)</span>
<span id="cb5-137">  )</span>
<span id="cb5-138"></span>
<span id="cb5-139">  post_slugs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">names</span>(posts)</span>
<span id="cb5-140"></span>
<span id="cb5-141">  <span class="co" style="color: #5E5E5E;"># Validate each post</span></span>
<span id="cb5-142">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (slug <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> post_slugs) {</span>
<span id="cb5-143">    p <span class="ot" style="color: #003B4F;">&lt;-</span> posts[[slug]]</span>
<span id="cb5-144">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(p<span class="sc" style="color: #5E5E5E;">$</span>series)) {</span>
<span id="cb5-145">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>p<span class="sc" style="color: #5E5E5E;">$</span>series <span class="sc" style="color: #5E5E5E;">%in%</span> live_series) {</span>
<span id="cb5-146">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-147">          <span class="st" style="color: #20794D;">"post"</span>,</span>
<span id="cb5-148">          slug,</span>
<span id="cb5-149">          <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb5-150">            <span class="st" style="color: #20794D;">"Unknown series link: post '%s' references unknown or non-live series '%s'"</span>,</span>
<span id="cb5-151">            slug,</span>
<span id="cb5-152">            p<span class="sc" style="color: #5E5E5E;">$</span>series</span>
<span id="cb5-153">          )</span>
<span id="cb5-154">        )</span>
<span id="cb5-155">      }</span>
<span id="cb5-156">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(p<span class="sc" style="color: #5E5E5E;">$</span>order) <span class="sc" style="color: #5E5E5E;">||</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.numeric</span>(p<span class="sc" style="color: #5E5E5E;">$</span>order)) {</span>
<span id="cb5-157">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-158">          <span class="st" style="color: #20794D;">"post"</span>,</span>
<span id="cb5-159">          slug,</span>
<span id="cb5-160">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Post '%s' has missing or non-numeric order"</span>, slug)</span>
<span id="cb5-161">        )</span>
<span id="cb5-162">      }</span>
<span id="cb5-163">    }</span>
<span id="cb5-164"></span>
<span id="cb5-165">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(p<span class="sc" style="color: #5E5E5E;">$</span>related) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">3</span>L) {</span>
<span id="cb5-166">      <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-167">        <span class="st" style="color: #20794D;">"post"</span>,</span>
<span id="cb5-168">        slug,</span>
<span id="cb5-169">        <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb5-170">          <span class="st" style="color: #20794D;">"Post '%s' has %d related links (maximum is 3)"</span>,</span>
<span id="cb5-171">          slug,</span>
<span id="cb5-172">          <span class="fu" style="color: #4758AB;">length</span>(p<span class="sc" style="color: #5E5E5E;">$</span>related)</span>
<span id="cb5-173">        )</span>
<span id="cb5-174">      )</span>
<span id="cb5-175">    }</span>
<span id="cb5-176"></span>
<span id="cb5-177">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (r <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> p<span class="sc" style="color: #5E5E5E;">$</span>related) {</span>
<span id="cb5-178">      target_post <span class="ot" style="color: #003B4F;">&lt;-</span> r<span class="sc" style="color: #5E5E5E;">$</span>post <span class="sc" style="color: #5E5E5E;">%||%</span> <span class="st" style="color: #20794D;">"&lt;empty&gt;"</span></span>
<span id="cb5-179">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>target_post <span class="sc" style="color: #5E5E5E;">%in%</span> post_slugs) {</span>
<span id="cb5-180">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-181">          <span class="st" style="color: #20794D;">"post"</span>,</span>
<span id="cb5-182">          slug,</span>
<span id="cb5-183">          <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb5-184">            <span class="st" style="color: #20794D;">"Broken slug: post '%s' references nonexistent post '%s'"</span>,</span>
<span id="cb5-185">            slug,</span>
<span id="cb5-186">            target_post</span>
<span id="cb5-187">          )</span>
<span id="cb5-188">        )</span>
<span id="cb5-189">      }</span>
<span id="cb5-190">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">identical</span>(target_post, slug)) {</span>
<span id="cb5-191">        <span class="fu" style="color: #4758AB;">record</span>(<span class="st" style="color: #20794D;">"post"</span>, slug, <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Post '%s' has a self-link"</span>, slug))</span>
<span id="cb5-192">      }</span>
<span id="cb5-193">      r_type <span class="ot" style="color: #003B4F;">&lt;-</span> r<span class="sc" style="color: #5E5E5E;">$</span>type <span class="sc" style="color: #5E5E5E;">%||%</span> <span class="st" style="color: #20794D;">"&lt;missing&gt;"</span></span>
<span id="cb5-194">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>r_type <span class="sc" style="color: #5E5E5E;">%in%</span> allowed_types) {</span>
<span id="cb5-195">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-196">          <span class="st" style="color: #20794D;">"post"</span>,</span>
<span id="cb5-197">          slug,</span>
<span id="cb5-198">          <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Invalid link type '%s' in post '%s'"</span>, r_type, slug)</span>
<span id="cb5-199">        )</span>
<span id="cb5-200">      }</span>
<span id="cb5-201">    }</span>
<span id="cb5-202">  }</span>
<span id="cb5-203"></span>
<span id="cb5-204">  <span class="co" style="color: #5E5E5E;"># Series order: 1..n without gaps or duplicates</span></span>
<span id="cb5-205">  in_series <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">Filter</span>(</span>
<span id="cb5-206">    <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(p) <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(p<span class="sc" style="color: #5E5E5E;">$</span>series) <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(p<span class="sc" style="color: #5E5E5E;">$</span>order),</span>
<span id="cb5-207">    posts</span>
<span id="cb5-208">  )</span>
<span id="cb5-209">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(in_series) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>) {</span>
<span id="cb5-210">    series_groups <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">split</span>(</span>
<span id="cb5-211">      <span class="fu" style="color: #4758AB;">vapply</span>(in_series, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(p) <span class="fu" style="color: #4758AB;">as.integer</span>(p<span class="sc" style="color: #5E5E5E;">$</span>order), <span class="fu" style="color: #4758AB;">integer</span>(<span class="dv" style="color: #AD0000;">1</span>)),</span>
<span id="cb5-212">      <span class="fu" style="color: #4758AB;">vapply</span>(in_series, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(p) <span class="fu" style="color: #4758AB;">as.character</span>(p<span class="sc" style="color: #5E5E5E;">$</span>series), <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">1</span>))</span>
<span id="cb5-213">    )</span>
<span id="cb5-214">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (sid <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">names</span>(series_groups)) {</span>
<span id="cb5-215">      ords <span class="ot" style="color: #003B4F;">&lt;-</span> series_groups[[sid]]</span>
<span id="cb5-216">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">anyDuplicated</span>(ords) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>) {</span>
<span id="cb5-217">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-218">          <span class="st" style="color: #20794D;">"post"</span>,</span>
<span id="cb5-219">          sid,</span>
<span id="cb5-220">          <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb5-221">            <span class="st" style="color: #20794D;">"Duplicate order in series '%s': parts %s"</span>,</span>
<span id="cb5-222">            sid,</span>
<span id="cb5-223">            <span class="fu" style="color: #4758AB;">paste</span>(ords[<span class="fu" style="color: #4758AB;">duplicated</span>(ords)], <span class="at" style="color: #657422;">collapse =</span> <span class="st" style="color: #20794D;">", "</span>)</span>
<span id="cb5-224">          )</span>
<span id="cb5-225">        )</span>
<span id="cb5-226">      }</span>
<span id="cb5-227">      sorted_ords <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sort</span>(<span class="fu" style="color: #4758AB;">unname</span>(ords))</span>
<span id="cb5-228">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">identical</span>(sorted_ords, <span class="fu" style="color: #4758AB;">seq_along</span>(ords))) {</span>
<span id="cb5-229">        <span class="fu" style="color: #4758AB;">record</span>(</span>
<span id="cb5-230">          <span class="st" style="color: #20794D;">"post"</span>,</span>
<span id="cb5-231">          sid,</span>
<span id="cb5-232">          <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb5-233">            <span class="st" style="color: #20794D;">"Order gap in series '%s': expected 1..%d, got %s"</span>,</span>
<span id="cb5-234">            sid,</span>
<span id="cb5-235">            <span class="fu" style="color: #4758AB;">length</span>(ords),</span>
<span id="cb5-236">            <span class="fu" style="color: #4758AB;">paste</span>(sorted_ords, <span class="at" style="color: #657422;">collapse =</span> <span class="st" style="color: #20794D;">", "</span>)</span>
<span id="cb5-237">          )</span>
<span id="cb5-238">        )</span>
<span id="cb5-239">      }</span>
<span id="cb5-240">    }</span>
<span id="cb5-241">  }</span>
<span id="cb5-242"></span>
<span id="cb5-243">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(problems) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>) {</span>
<span id="cb5-244">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb5-245">      <span class="at" style="color: #657422;">scope =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb5-246">      <span class="at" style="color: #657422;">item =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb5-247">      <span class="at" style="color: #657422;">problem =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb5-248">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb5-249">    ))</span>
<span id="cb5-250">  }</span>
<span id="cb5-251"></span>
<span id="cb5-252">  <span class="fu" style="color: #4758AB;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;">lapply</span>(problems, as.data.frame, <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span>))</span>
<span id="cb5-253">}</span>
<span id="cb5-254"></span>
<span id="cb5-255"><span class="co" style="color: #5E5E5E;"># Run demo when executed directly</span></span>
<span id="cb5-256"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb5-257">  demo_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"check-registry-demo"</span>)</span>
<span id="cb5-258">  <span class="fu" style="color: #4758AB;">dir.create</span>(</span>
<span id="cb5-259">    <span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"_data"</span>),</span>
<span id="cb5-260">    <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb5-261">    <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb5-262">  )</span>
<span id="cb5-263">  <span class="fu" style="color: #4758AB;">dir.create</span>(</span>
<span id="cb5-264">    <span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"posts"</span>),</span>
<span id="cb5-265">    <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb5-266">    <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb5-267">  )</span>
<span id="cb5-268">  <span class="fu" style="color: #4758AB;">on.exit</span>(<span class="fu" style="color: #4758AB;">unlink</span>(demo_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>), <span class="at" style="color: #657422;">add =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb5-269"></span>
<span id="cb5-270">  <span class="co" style="color: #5E5E5E;"># Sample registry</span></span>
<span id="cb5-271">  <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb5-272">    <span class="st" style="color: #20794D;">"series:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-273">    <span class="st" style="color: #20794D;">"  - id: basics</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-274">    <span class="st" style="color: #20794D;">"    status: live</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-275">    <span class="st" style="color: #20794D;">"    track: engineering</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-276">    <span class="st" style="color: #20794D;">"    related:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-277">    <span class="st" style="color: #20794D;">"      - {to: testing, type: read-next}</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-278">    <span class="st" style="color: #20794D;">"  - id: testing</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-279">    <span class="st" style="color: #20794D;">"    status: planned</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-280">    <span class="st" style="color: #20794D;">"    track: engineering</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-281">    <span class="st" style="color: #20794D;">"    title: 'Testing in R'</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-282">    <span class="st" style="color: #20794D;">"    summary: 'Unit and snapshot testing'</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-283">    <span class="at" style="color: #657422;">file =</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"_data"</span>, <span class="st" style="color: #20794D;">"series.yml"</span>),</span>
<span id="cb5-284">    <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">""</span></span>
<span id="cb5-285">  )</span>
<span id="cb5-286"></span>
<span id="cb5-287">  <span class="co" style="color: #5E5E5E;"># Sample posts</span></span>
<span id="cb5-288">  make_post <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(slug, yaml_content) {</span>
<span id="cb5-289">    pdir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"posts"</span>, slug)</span>
<span id="cb5-290">    <span class="fu" style="color: #4758AB;">dir.create</span>(pdir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb5-291">    <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb5-292">      <span class="st" style="color: #20794D;">"---</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-293">      yaml_content,</span>
<span id="cb5-294">      <span class="st" style="color: #20794D;">"---</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">Post body content.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-295">      <span class="at" style="color: #657422;">file =</span> <span class="fu" style="color: #4758AB;">file.path</span>(pdir, <span class="st" style="color: #20794D;">"index.qmd"</span>),</span>
<span id="cb5-296">      <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">""</span></span>
<span id="cb5-297">    )</span>
<span id="cb5-298">  }</span>
<span id="cb5-299"></span>
<span id="cb5-300">  <span class="fu" style="color: #4758AB;">make_post</span>(</span>
<span id="cb5-301">    <span class="st" style="color: #20794D;">"intro"</span>,</span>
<span id="cb5-302">    <span class="fu" style="color: #4758AB;">paste0</span>(</span>
<span id="cb5-303">      <span class="st" style="color: #20794D;">"title: 'Introduction'</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-304">      <span class="st" style="color: #20794D;">"series: basics</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-305">      <span class="st" style="color: #20794D;">"order: 1</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-306">      <span class="st" style="color: #20794D;">"related:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-307">      <span class="st" style="color: #20794D;">"  - {post: advanced, type: read-next}</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb5-308">    )</span>
<span id="cb5-309">  )</span>
<span id="cb5-310"></span>
<span id="cb5-311">  <span class="co" style="color: #5E5E5E;"># Planted bug: broken slug reference to 'nonexistent-post'</span></span>
<span id="cb5-312">  <span class="fu" style="color: #4758AB;">make_post</span>(</span>
<span id="cb5-313">    <span class="st" style="color: #20794D;">"advanced"</span>,</span>
<span id="cb5-314">    <span class="fu" style="color: #4758AB;">paste0</span>(</span>
<span id="cb5-315">      <span class="st" style="color: #20794D;">"title: 'Advanced Concepts'</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-316">      <span class="st" style="color: #20794D;">"series: basics</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-317">      <span class="st" style="color: #20794D;">"order: 2</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-318">      <span class="st" style="color: #20794D;">"related:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-319">      <span class="st" style="color: #20794D;">"  - {post: nonexistent-post, type: builds-on}</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb5-320">    )</span>
<span id="cb5-321">  )</span>
<span id="cb5-322"></span>
<span id="cb5-323">  <span class="fu" style="color: #4758AB;">make_post</span>(</span>
<span id="cb5-324">    <span class="st" style="color: #20794D;">"orphan-summary"</span>,</span>
<span id="cb5-325">    <span class="fu" style="color: #4758AB;">paste0</span>(</span>
<span id="cb5-326">      <span class="st" style="color: #20794D;">"title: 'Orphan Summary'</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-327">      <span class="st" style="color: #20794D;">"related:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-328">      <span class="st" style="color: #20794D;">"  - {post: intro, type: see-also}</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb5-329">    )</span>
<span id="cb5-330">  )</span>
<span id="cb5-331"></span>
<span id="cb5-332">  registry <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">read_registry</span>(<span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"_data"</span>, <span class="st" style="color: #20794D;">"series.yml"</span>))</span>
<span id="cb5-333">  posts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">scan_posts</span>(<span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"posts"</span>))</span>
<span id="cb5-334">  issues <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">check_registry</span>(registry, posts)</span>
<span id="cb5-335"></span>
<span id="cb5-336">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Validated"</span>, <span class="fu" style="color: #4758AB;">length</span>(registry), <span class="st" style="color: #20794D;">"series and"</span>, <span class="fu" style="color: #4758AB;">length</span>(posts), <span class="st" style="color: #20794D;">"posts.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb5-337">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">nrow</span>(issues) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>) {</span>
<span id="cb5-338">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"✓ No registry issues detected.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb5-339">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb5-340">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Found %d issue(s):</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, <span class="fu" style="color: #4758AB;">nrow</span>(issues)))</span>
<span id="cb5-341">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (i <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_len</span>(<span class="fu" style="color: #4758AB;">nrow</span>(issues))) {</span>
<span id="cb5-342">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb5-343">        <span class="st" style="color: #20794D;">"  [%s] %s: %s</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb5-344">        issues<span class="sc" style="color: #5E5E5E;">$</span>scope[i],</span>
<span id="cb5-345">        issues<span class="sc" style="color: #5E5E5E;">$</span>item[i],</span>
<span id="cb5-346">        issues<span class="sc" style="color: #5E5E5E;">$</span>problem[i]</span>
<span id="cb5-347">      ))</span>
<span id="cb5-348">    }</span>
<span id="cb5-349">  }</span>
<span id="cb5-350">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Quarto &amp; Pandoc documentation</strong></p>
<ul>
<li><strong>Quarto Document Listings</strong>: <a href="https://quarto.org/docs/websites/website-listings.html">quarto.org/docs/websites/website-listings.html</a></li>
<li><strong>Quarto Lua Filter API</strong>: <a href="https://quarto.org/docs/extensions/lua-api.html">quarto.org/docs/extensions/lua-api.html</a></li>
<li><strong>Pandoc Lua filters</strong> (<code>pandoc.read</code>, <code>pandoc.system.list_directory</code>, <code>pandoc.path</code>): <a href="https://pandoc.org/lua-filters.html">pandoc.org/lua-filters.html</a></li>
</ul>
<p><strong>Static site generators &amp; content collections</strong></p>
<ul>
<li><strong>Hugo Related Content</strong>: <a href="https://gohugo.io/content-management/related-content/">gohugo.io/content-management/related-content</a></li>
<li><strong>Jekyll variables</strong> (<code>site.related_posts</code>): <a href="https://jekyllrb.com/docs/variables/">jekyllrb.com/docs/variables</a></li>
<li><strong>Jekyll configuration options</strong> (<code>--lsi</code> needs classifier-reborn): <a href="https://jekyllrb.com/docs/configuration/options/">jekyllrb.com/docs/configuration/options</a></li>
<li><strong>Astro Content Collections</strong>: <a href="https://docs.astro.build/en/guides/content-collections/">docs.astro.build/en/guides/content-collections</a></li>
<li><strong>Eleventy Global Data Files</strong>: <a href="https://www.11ty.dev/docs/data-global/">11ty.dev/docs/data-global</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>testthat</strong>: <a href="https://cran.r-project.org/package=testthat">CRAN</a></li>
<li><strong>yaml</strong>: <a href="https://cran.r-project.org/package=yaml">CRAN</a></li>
<li><strong>withr</strong>: <a href="https://cran.r-project.org/package=withr">CRAN</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-11-13:</strong> The site’s test files now carry a <code>site-</code> or <code>post-</code> prefix, so the test named here is <code>tests/testthat/test-site-series-registry.R</code>.</li>
</ul>
</div>
</div>
</div>



</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor site-related">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/building-this-blog/index.html" class="site-link-row" title="How we transformed a 14-part topic site into a Quarto engineering blog and portfolio using URL aliases, living-document conventions, and multi-model agentic collaboration."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Building this blog: from numbered topics to a living Quarto publication</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/index.html" class="site-link-row" title="Validate internal links across rendered documentation in CI using offline link scanners to block broken references before release."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Catch broken links before your readers do</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
</ul>
</div>
</section>


 ]]></description>
  <category>Quarto</category>
  <category>Best practices</category>
  <category>R</category>
  <guid>https://insightsurge-dev.web.app/posts/series-registry-quarto/</guid>
  <pubDate>Sat, 26 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Coverage and tests as evidence</title>
  <link>https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem-line-coverage-is-not-tested-behaviour" class="level2">
<h2 class="anchored" data-anchor-id="the-problem-line-coverage-is-not-tested-behaviour">The problem: line coverage is not tested behaviour</h2>
<p>Earlier posts in this series covered <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html">testthat essentials</a>, <a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/index.html">fixtures and mocking</a>, <a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html">snapshots</a>, <a href="https://insightsurge-dev.web.app/posts/shiny-testserver/index.html">Shiny modules</a>, <a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/index.html">browser tests</a>, and <a href="https://insightsurge-dev.web.app/posts/property-based-testing/index.html">property testing</a>.</p>
<p>As a test suite expands, two questions emerge: how much code is tested, and how do we prove to reviewers that software meets its requirements?</p>
<p>The common metric is <strong>code coverage</strong>: the percentage of lines executed during tests. But equating line execution with verified behaviour is a mistake.</p>
<p>A line can execute without an assertion evaluating its correctness:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1">calculate_pfs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(event, days) {</span>
<span id="cb1-2">  <span class="co" style="color: #5E5E5E;"># Dummy function: event argument is unused to demonstrate unverified logic</span></span>
<span id="cb1-3">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.na</span>(event) <span class="sc" style="color: #5E5E5E;">||</span> <span class="fu" style="color: #4758AB;">is.na</span>(days)) <span class="fu" style="color: #4758AB;">return</span>(<span class="cn" style="color: #8f5902;">NA_real_</span>)</span>
<span id="cb1-4">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (days <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">0</span>) <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"Days cannot be negative"</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb1-5">  days <span class="sc" style="color: #5E5E5E;">/</span> <span class="fl" style="color: #AD0000;">30.4375</span></span>
<span id="cb1-6">}</span>
<span id="cb1-7"></span>
<span id="cb1-8"><span class="co" style="color: #5E5E5E;"># Touches lines without verifying output</span></span>
<span id="cb1-9">res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">calculate_pfs</span>(<span class="dv" style="color: #AD0000;">1</span>, <span class="dv" style="color: #AD0000;">60</span>)</span>
<span id="cb1-10">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_true</span>(<span class="cn" style="color: #8f5902;">TRUE</span>)</span></code></pre></div></div>
<p>In a coverage report, every statement in the main path turns green. Yet the test asserts nothing about the result: if the formula broke, the test would still pass.</p>
<p>This reflects Goodhart’s law: mandating a coverage threshold nudges developers toward superficial tests without real assertions.</p>
<p>Coverage is a <strong>diagnostic signal</strong>, not a quality target:</p>
<ul>
<li><strong>Low coverage</strong> provides a dependable negative signal, locating code paths and functions tests never touch.</li>
<li><strong>High coverage</strong> provides no proof of correctness: it confirms statements ran, not that boundary cases, error branches, or calculations are right.</li>
</ul>
<p>Producing reliable evidence requires both coverage metrics to spot untested gaps and traceable tests that link automated expectations directly to functional requirements.</p>
</section>
<section id="the-web-repo-way-thresholds-v8-profiling-and-machine-readable-reports" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-thresholds-v8-profiling-and-machine-readable-reports">The web-repo way: thresholds, V8 profiling, and machine-readable reports</h2>
<p>Web repositories integrate coverage into CI through engine profilers and standardized formats.</p>
<section id="instrumentation-versus-engine-profiling-istanbul-and-c8" class="level3">
<h3 class="anchored" data-anchor-id="instrumentation-versus-engine-profiling-istanbul-and-c8">Instrumentation versus engine profiling: Istanbul and c8</h3>
<p>Historically, Istanbul (<code>nyc</code>) injected counter variables into source files, adding runtime overhead.</p>
<p>Modern runners like Vitest and Jest support native V8 coverage (via <code>@vitest/coverage-v8</code> or Jest’s built-in V8 provider). The engine tracks bytecode execution ranges directly across four dimensions: lines, statements, functions, and branches (<code>if/else</code> paths and fallbacks).</p>
</section>
<section id="enforcing-coverage-gates-in-configuration" class="level3">
<h3 class="anchored" data-anchor-id="enforcing-coverage-gates-in-configuration">Enforcing coverage gates in configuration</h3>
<p>Projects enforce coverage gates in configuration. In Vitest (<code>vitest.config.ts</code>), teams set aggregate thresholds or enforce per-file rules:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb2-1"><span class="im" style="color: #00769E;">import</span> { defineConfig } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"vitest/config"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="im" style="color: #00769E;">export</span> <span class="im" style="color: #00769E;">default</span> <span class="fu" style="color: #4758AB;">defineConfig</span>({</span>
<span id="cb2-4">  test<span class="op" style="color: #5E5E5E;">:</span> {</span>
<span id="cb2-5">    coverage<span class="op" style="color: #5E5E5E;">:</span> {</span>
<span id="cb2-6">      provider<span class="op" style="color: #5E5E5E;">:</span> <span class="st" style="color: #20794D;">"v8"</span><span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-7">      reporter<span class="op" style="color: #5E5E5E;">:</span> [<span class="st" style="color: #20794D;">"text"</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">"json"</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">"cobertura"</span>]<span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-8">      thresholds<span class="op" style="color: #5E5E5E;">:</span> {</span>
<span id="cb2-9">        lines<span class="op" style="color: #5E5E5E;">:</span> <span class="dv" style="color: #AD0000;">80</span><span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-10">        functions<span class="op" style="color: #5E5E5E;">:</span> <span class="dv" style="color: #AD0000;">80</span><span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-11">        branches<span class="op" style="color: #5E5E5E;">:</span> <span class="dv" style="color: #AD0000;">75</span><span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-12">        statements<span class="op" style="color: #5E5E5E;">:</span> <span class="dv" style="color: #AD0000;">80</span><span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-13">        perFile<span class="op" style="color: #5E5E5E;">:</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">true</span><span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-14">      }<span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-15">    }<span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-16">  }<span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb2-17">})<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<p>Setting <code>perFile: true</code> prevents well-tested helpers from masking untested critical business logic. CI workflows export JUnit XML for test status and Cobertura XML for coverage, rendering them into pull request dashboards.</p>
</section>
</section>
<section id="the-r-way-measuring-coverage-with-covr" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-measuring-coverage-with-covr">The R way: measuring coverage with {covr}</h2>
<p><code>{covr}</code> is the standard framework for measuring R code coverage. Available on <a href="https://cran.r-project.org/package=covr">CRAN</a> and documented on <a href="https://covr.r-lib.org">covr.r-lib.org</a>, <code>{covr}</code> uses source references (<code>srcrefs</code>) to trace statement evaluation during tests.</p>
<section id="core-coverage-functions" class="level3">
<h3 class="anchored" data-anchor-id="core-coverage-functions">Core coverage functions</h3>
<p><code>{covr}</code> provides functions for different scopes:</p>
<ul>
<li><code>covr::package_coverage(path = ".")</code>: Standard entry point; installs the package to a temporary library and tracks evaluated expressions.</li>
<li><code>covr::file_coverage(source_files, test_files)</code>: Evaluates standalone scripts against test files.</li>
<li><code>covr::code_coverage(source_code, test_code)</code>: Evaluates coverage directly from code strings.</li>
<li><code>covr::environment_coverage(env, test_files)</code>: Measures functions defined in a specific environment.</li>
</ul>
</section>
<section id="inspecting-coverage-results-locally" class="level3">
<h3 class="anchored" data-anchor-id="inspecting-coverage-results-locally">Inspecting coverage results locally</h3>
<p>In interactive development, three functions assess test thoroughness:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">cov <span class="ot" style="color: #003B4F;">&lt;-</span> covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">package_coverage</span>()</span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;"># Return aggregate percentage as numeric(1)</span></span>
<span id="cb3-4">covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">percent_coverage</span>(cov)</span>
<span id="cb3-5"></span>
<span id="cb3-6"><span class="co" style="color: #5E5E5E;"># Return data frame of locations with no test execution</span></span>
<span id="cb3-7">covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">zero_coverage</span>(cov)</span>
<span id="cb3-8"></span>
<span id="cb3-9"><span class="co" style="color: #5E5E5E;"># Open interactive HTML report highlighting covered and uncovered lines</span></span>
<span id="cb3-10">covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">report</span>(cov)</span></code></pre></div></div>
<p><code>covr::percent_coverage(cov)</code> returns the total percentage as a number.</p>
<p><code>covr::zero_coverage(cov)</code> returns a data frame with columns <code>filename</code>, <code>functions</code>, <code>line</code>, and <code>value</code>, isolating statements that never ran. In RStudio, it also populates the Markers pane.</p>
<p><code>covr::report(cov)</code> renders an interactive HTML document with source lines colored by execution count (<code>browse</code> defaults to <code>interactive()</code>).</p>
</section>
<section id="detecting-coverage-execution" class="level3">
<h3 class="anchored" data-anchor-id="detecting-coverage-execution">Detecting coverage execution</h3>
<p>When test behaviour must adjust during coverage runs (such as skipping long benchmarks), <code>{covr}</code> sets the environment variable <code>R_COVR</code>. The helper <code>covr::in_covr()</code> returns <code>TRUE</code> during coverage:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb4-1">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"expensive benchmark runs only during standard passes"</span>, {</span>
<span id="cb4-2">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">skip_if</span>(covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">in_covr</span>(), <span class="st" style="color: #20794D;">"Skipping benchmark during coverage"</span>)</span>
<span id="cb4-3">})</span></code></pre></div></div>
</section>
</section>
<section id="running-coverage-in-continuous-integration" class="level2">
<h2 class="anchored" data-anchor-id="running-coverage-in-continuous-integration">Running coverage in continuous integration</h2>
<p>Continuous integration provides reproducible coverage measurement on every pull request. The canonical GitHub Actions workflow maintained by <code>r-lib/actions</code> (<code>examples/test-coverage.yaml</code>) demonstrates the modern pattern:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb5-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> r-lib/actions/setup-r-dependencies@v2</span></span>
<span id="cb5-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-3"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">extra-packages</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> any::covr, any::xml2</span></span>
<span id="cb5-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">needs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> coverage</span></span>
<span id="cb5-5"></span>
<span id="cb5-6"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Test coverage</span></span>
<span id="cb5-7"><span class="fu" style="color: #4758AB;">  run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">: </span><span class="ch" style="color: #20794D;">|</span></span>
<span id="cb5-8">    cov &lt;- covr::package_coverage(</span>
<span id="cb5-9">      quiet = FALSE,</span>
<span id="cb5-10">      clean = FALSE,</span>
<span id="cb5-11">      install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package")</span>
<span id="cb5-12">    )</span>
<span id="cb5-13">    print(cov)</span>
<span id="cb5-14">    covr::to_cobertura(cov)</span>
<span id="cb5-15"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">shell</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Rscript {0}</span></span>
<span id="cb5-16"></span>
<span id="cb5-17"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f</span><span class="co" style="color: #5E5E5E;"> # v7</span></span>
<span id="cb5-18"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-19"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">fail_ci_if_error</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ github.event_name != 'pull_request' || secrets.CODECOV_TOKEN }}</span></span>
<span id="cb5-20"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">files</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ./cobertura.xml</span></span>
<span id="cb5-21"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">plugins</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> noop</span></span>
<span id="cb5-22"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">disable_search</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb5-23"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">token</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ secrets.CODECOV_TOKEN }}</span></span></code></pre></div></div>
<p>This workflow decouples calculation from upload: R runs <code>covr::package_coverage(...)</code>, exports XML via <code>covr::to_cobertura(cov)</code> (using <code>{xml2}</code>), and hands <code>./cobertura.xml</code> to <code>codecov/codecov-action</code>. The official <code>r-lib/actions</code> template pins actions by immutable commit SHA for supply-chain security.</p>
</section>
<section id="tests-as-evidence-requirements-and-traceability" class="level2">
<h2 class="anchored" data-anchor-id="tests-as-evidence-requirements-and-traceability">Tests as evidence: requirements and traceability</h2>
<p>In regulated work, including clinical reporting and GxP applications, verifying software requires showing that intended functionality meets documented requirements. A passing test suite is meaningful evidence only if each test ties back to a specific requirement.</p>
<section id="naming-tests-with-requirement-identifiers" class="level3">
<h3 class="anchored" data-anchor-id="naming-tests-with-requirement-identifiers">Naming tests with requirement identifiers</h3>
<p>The simplest way to establish requirement traceability is to embed requirement identifiers directly into test descriptions:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">derive_age_years <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(days) {</span>
<span id="cb6-2">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.numeric</span>(days)) <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"days must be numeric"</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb6-3">  <span class="fu" style="color: #4758AB;">as.integer</span>(<span class="fu" style="color: #4758AB;">floor</span>(days <span class="sc" style="color: #5E5E5E;">/</span> <span class="fl" style="color: #AD0000;">365.25</span>))</span>
<span id="cb6-4">}</span>
<span id="cb6-5"></span>
<span id="cb6-6">derive_study_day <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(target_date, ref_date) {</span>
<span id="cb6-7">  diff <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as.integer</span>(<span class="fu" style="color: #4758AB;">as.Date</span>(target_date) <span class="sc" style="color: #5E5E5E;">-</span> <span class="fu" style="color: #4758AB;">as.Date</span>(ref_date))</span>
<span id="cb6-8">  <span class="fu" style="color: #4758AB;">ifelse</span>(diff <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">0</span>L, diff <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L, diff)</span>
<span id="cb6-9">}</span>
<span id="cb6-10"></span>
<span id="cb6-11">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"REQ-01: derive_age_years converts days to complete years"</span>, {</span>
<span id="cb6-12">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">derive_age_years</span>(<span class="dv" style="color: #AD0000;">731</span>), <span class="dv" style="color: #AD0000;">2</span>L)</span>
<span id="cb6-13">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_error</span>(<span class="fu" style="color: #4758AB;">derive_age_years</span>(<span class="st" style="color: #20794D;">"731"</span>), <span class="st" style="color: #20794D;">"days must be numeric"</span>)</span>
<span id="cb6-14">})</span>
<span id="cb6-15"></span>
<span id="cb6-16">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"REQ-02: derive_study_day computes 1-based day without day 0"</span>, {</span>
<span id="cb6-17">  ref <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"2026-09-27"</span></span>
<span id="cb6-18">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">derive_study_day</span>(<span class="st" style="color: #20794D;">"2026-09-27"</span>, ref), <span class="dv" style="color: #AD0000;">1</span>L)</span>
<span id="cb6-19">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">derive_study_day</span>(<span class="st" style="color: #20794D;">"2026-09-28"</span>, ref), <span class="dv" style="color: #AD0000;">2</span>L)</span>
<span id="cb6-20">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">derive_study_day</span>(<span class="st" style="color: #20794D;">"2026-09-26"</span>, ref), <span class="sc" style="color: #5E5E5E;">-</span><span class="dv" style="color: #AD0000;">1</span>L)</span>
<span id="cb6-21">})</span></code></pre></div></div>
<p>Identifiers such as <code>REQ-01</code> and <code>REQ-02</code> allow automated tooling to parse test results and construct a traceability matrix without maintaining error-prone manual spreadsheets.</p>
</section>
<section id="building-a-traceability-matrix-from-test-results" class="level3">
<h3 class="anchored" data-anchor-id="building-a-traceability-matrix-from-test-results">Building a traceability matrix from test results</h3>
<p><code>testthat::test_local()</code> and <code>testthat::test_file()</code> return a <code>testthat_results</code> object. Calling <code>as.data.frame()</code> exposes structured test execution data:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">test_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tempfile</span>(<span class="at" style="color: #657422;">fileext =</span> <span class="st" style="color: #20794D;">".R"</span>)</span>
<span id="cb7-2"><span class="fu" style="color: #4758AB;">writeLines</span>(</span>
<span id="cb7-3">  <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb7-4">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">REQ-01: derive_age_years converts days</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, { expect_equal(2L, 2L) })"</span>,</span>
<span id="cb7-5">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">REQ-02: derive_study_day computes 1-based day</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, { expect_equal(1L, 1L) })"</span></span>
<span id="cb7-6">  ),</span>
<span id="cb7-7">  test_file</span>
<span id="cb7-8">)</span>
<span id="cb7-9"></span>
<span id="cb7-10">df <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as.data.frame</span>(testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_file</span>(test_file, <span class="at" style="color: #657422;">reporter =</span> <span class="st" style="color: #20794D;">"silent"</span>))</span>
<span id="cb7-11">has_req <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"^REQ-[0-9]+:"</span>, df<span class="sc" style="color: #5E5E5E;">$</span>test)</span>
<span id="cb7-12"></span>
<span id="cb7-13">trace_table <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb7-14">  <span class="at" style="color: #657422;">requirement_id =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(has_req, <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">":.*$"</span>, <span class="st" style="color: #20794D;">""</span>, df<span class="sc" style="color: #5E5E5E;">$</span>test), <span class="cn" style="color: #8f5902;">NA_character_</span>),</span>
<span id="cb7-15">  <span class="at" style="color: #657422;">description =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(has_req, <span class="fu" style="color: #4758AB;">trimws</span>(<span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"^[^:]+:[[:space:]]*"</span>, <span class="st" style="color: #20794D;">""</span>, df<span class="sc" style="color: #5E5E5E;">$</span>test)), df<span class="sc" style="color: #5E5E5E;">$</span>test),</span>
<span id="cb7-16">  <span class="at" style="color: #657422;">test_file =</span> <span class="fu" style="color: #4758AB;">basename</span>(df<span class="sc" style="color: #5E5E5E;">$</span>file),</span>
<span id="cb7-17">  <span class="at" style="color: #657422;">passed_expectations =</span> df<span class="sc" style="color: #5E5E5E;">$</span>passed,</span>
<span id="cb7-18">  <span class="at" style="color: #657422;">status =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb7-19">    df<span class="sc" style="color: #5E5E5E;">$</span>skipped,</span>
<span id="cb7-20">    <span class="st" style="color: #20794D;">"SKIPPED"</span>,</span>
<span id="cb7-21">    <span class="fu" style="color: #4758AB;">ifelse</span>(df<span class="sc" style="color: #5E5E5E;">$</span>failed <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span>df<span class="sc" style="color: #5E5E5E;">$</span>error, <span class="st" style="color: #20794D;">"PASS"</span>, <span class="st" style="color: #20794D;">"FAIL"</span>)</span>
<span id="cb7-22">  ),</span>
<span id="cb7-23">  <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb7-24">)</span>
<span id="cb7-25"></span>
<span id="cb7-26">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">nrow</span>(trace_table), <span class="dv" style="color: #AD0000;">2</span>L)</span>
<span id="cb7-27">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(trace_table<span class="sc" style="color: #5E5E5E;">$</span>status <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"PASS"</span>))</span></code></pre></div></div>
<p>Tracking skipped tests as <code>SKIPPED</code> is vital for audit evidence: in <code>testthat_results</code>, a skipped test has <code>failed = 0</code> and <code>error = FALSE</code>. Without checking <code>df$skipped</code>, unexecuted tests would falsely register as <code>PASS</code>. This tabular view maps each requirement to its test file, pass/fail status, and expectation count, producing verification output directly from code execution.</p>
</section>
<section id="recording-results-in-ci-with-junit-xml" class="level3">
<h3 class="anchored" data-anchor-id="recording-results-in-ci-with-junit-xml">Recording results in CI with JUnit XML</h3>
<p>To record test evidence in CI, configure <code>testthat</code> to write standard JUnit XML. <code>testthat::JunitReporter</code> formats test results into XML compatible with CI dashboards:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb8-1">xml_output <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="st" style="color: #20794D;">"inst"</span>, <span class="st" style="color: #20794D;">"test-evidence"</span>, <span class="st" style="color: #20794D;">"test-results.xml"</span>)</span>
<span id="cb8-2"><span class="fu" style="color: #4758AB;">dir.create</span>(<span class="fu" style="color: #4758AB;">dirname</span>(xml_output), <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb8-3"></span>
<span id="cb8-4">reporter <span class="ot" style="color: #003B4F;">&lt;-</span> testthat<span class="sc" style="color: #5E5E5E;">::</span>MultiReporter<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(<span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb8-5">  testthat<span class="sc" style="color: #5E5E5E;">::</span>SummaryReporter<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(),</span>
<span id="cb8-6">  testthat<span class="sc" style="color: #5E5E5E;">::</span>JunitReporter<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(<span class="at" style="color: #657422;">file =</span> xml_output)</span>
<span id="cb8-7">))</span>
<span id="cb8-8"></span>
<span id="cb8-9">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_local</span>(<span class="at" style="color: #657422;">reporter =</span> reporter, <span class="at" style="color: #657422;">stop_on_failure =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span></code></pre></div></div>
<p><code>testthat::MultiReporter</code> allows simultaneous console reporting via <code>SummaryReporter</code> and machine-readable persistence via <code>JunitReporter</code>.</p>
</section>
<section id="preserving-provenance-results-commits-and-lockfiles" class="level3">
<h3 class="anchored" data-anchor-id="preserving-provenance-results-commits-and-lockfiles">Preserving provenance: results, commits, and lockfiles</h3>
<p>Evidence is only as dependable as its provenance: a report claiming tests passed has little value without the exact code and dependency versions that generated it.</p>
<p>In an automated CI pipeline:</p>
<ol type="1">
<li><strong>Test and coverage results (<code>test-results.xml</code>, <code>cobertura.xml</code>)</strong> are saved as build artifacts.</li>
<li>The <strong>Git commit SHA</strong> identifies the exact code that generated the evidence.</li>
<li>The <strong><code>renv.lock</code></strong> lockfile records the version, source, and hash of R and every dependency.</li>
</ol>
<p>Preserving these three artifacts together provides reproducible evidence: any auditor or team member can check out the exact commit, restore the identical dependency environment with <code>renv::restore()</code>, and re-execute the test suite.</p>
</section>
</section>
<section id="honest-gxp-framing-risk-based-qualification-not-pre-approved-software" class="level2">
<h2 class="anchored" data-anchor-id="honest-gxp-framing-risk-based-qualification-not-pre-approved-software">Honest GxP framing: risk-based qualification, not pre-approved software</h2>
<p>In regulated environments, developers sometimes claim that an open-source package is certified or pre-approved for regulatory submissions. Such claims misunderstand regulatory guidance.</p>
<p>As articulated in the R Validation Hub white paper (<em>A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure</em>, Nicholls et al., <a href="https://pharmar.org/white-paper/">pharmar.org</a>):</p>
<ul>
<li><strong>Software is never globally certified:</strong> Regulatory agencies (such as the FDA) do not approve third-party software packages in the abstract. Validation is the responsibility of the sponsoring organization, conducted for a specific intended use within a specific configured environment.</li>
<li><strong>Qualification versus validation:</strong> Individual packages are <em>qualified</em> by gathering objective evidence of stability, testing quality, and numerical accuracy. The <em>complete computerized system</em> (incorporating hardware, the operating system, R, supporting packages, and analytical programs) is validated for its operational workflow.</li>
<li><strong>Risk-based testing:</strong> Scrutiny should match operational risk. Base R and recommended packages undergo extensive peer review and testing by the R Core Team. Specialized packages require proportional testing: unit assertions verifying intended use cases, boundary evaluations, and comparison against known reference values.</li>
</ul>
<p>Automated unit tests and code coverage reports do not magically validate an application. Instead, they provide <strong>objective, verifiable evidence</strong> that designated requirements were executed and confirmed within a controlled environment.</p>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/scripts/coverage-demo.R">View <code>coverage-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/scripts/coverage-demo.R" download="coverage-demo.R">Download</a></p>
<p>Builds a throwaway R package containing two clinical derivation functions, measures coverage before and after adding a missing test, and writes both a requirement-to-test traceability matrix and JUnit XML output. Requires <code>{covr}</code>, <code>{testthat}</code>, <code>{usethis}</code> and <code>{withr}</code>. Running it (<code>Rscript coverage-demo.R</code>) shows the workflow:</p>
<ol type="1">
<li><strong>Initial coverage check:</strong> Evaluates coverage with <code>covr::package_coverage()</code>, finding <code>derive_study_day()</code> untested (60.0% coverage).</li>
<li><strong>Identifying missing paths:</strong> Calls <code>covr::zero_coverage()</code> to locate unreached lines in <code>R/derivations.R</code>.</li>
<li><strong>Closing coverage gaps:</strong> Adds a test for <code>REQ-02</code> checking study days (with no day 0 convention), reaching 100% coverage.</li>
<li><strong>Generating auditable evidence:</strong> Runs tests via <code>testthat::MultiReporter</code>, writing JUnit XML and outputting the traceability table mapping requirements to passing tests.</li>
</ol>
<p>The script’s operations are tested in the repository suite, confirming coverage numbers and traceability tables reflect real execution.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>coverage-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="co" style="color: #5E5E5E;"># Coverage measurement and requirement-to-test evidence:</span></span>
<span id="cb9-2"><span class="co" style="color: #5E5E5E;"># builds a throwaway package with two clinical derivation functions,</span></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;"># measures initial coverage where one function lacks tests, identifies</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;"># uncovered lines, adds the missing test, confirms complete coverage,</span></span>
<span id="cb9-5"><span class="co" style="color: #5E5E5E;"># and constructs a requirement-to-test traceability matrix alongside</span></span>
<span id="cb9-6"><span class="co" style="color: #5E5E5E;"># JUnit XML results.</span></span>
<span id="cb9-7"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb9-8"><span class="co" style="color: #5E5E5E;">#   Rscript coverage-demo.R</span></span>
<span id="cb9-9"></span>
<span id="cb9-10">demo_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb9-11">  <span class="st" style="color: #20794D;">"NAMESPACE"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-12">    <span class="st" style="color: #20794D;">"export(derive_age_years)"</span>,</span>
<span id="cb9-13">    <span class="st" style="color: #20794D;">"export(derive_study_day)"</span></span>
<span id="cb9-14">  ),</span>
<span id="cb9-15">  <span class="st" style="color: #20794D;">"R/derivations.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-16">    <span class="st" style="color: #20794D;">"#' Derive age in completed years"</span>,</span>
<span id="cb9-17">    <span class="st" style="color: #20794D;">"#' @param days Number of days elapsed since birth."</span>,</span>
<span id="cb9-18">    <span class="st" style="color: #20794D;">"#' @return Integer age in years."</span>,</span>
<span id="cb9-19">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb9-20">    <span class="st" style="color: #20794D;">"derive_age_years &lt;- function(days) {"</span>,</span>
<span id="cb9-21">    <span class="st" style="color: #20794D;">"  if (!is.numeric(days)) {"</span>,</span>
<span id="cb9-22">    <span class="st" style="color: #20794D;">"    stop(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">days must be numeric</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, call. = FALSE)"</span>,</span>
<span id="cb9-23">    <span class="st" style="color: #20794D;">"  }"</span>,</span>
<span id="cb9-24">    <span class="st" style="color: #20794D;">"  as.integer(floor(days / 365.25))"</span>,</span>
<span id="cb9-25">    <span class="st" style="color: #20794D;">"}"</span>,</span>
<span id="cb9-26">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-27">    <span class="st" style="color: #20794D;">"#' Derive study day from reference date (1-based, no day 0)"</span>,</span>
<span id="cb9-28">    <span class="st" style="color: #20794D;">"#' @param target_date Target assessment date."</span>,</span>
<span id="cb9-29">    <span class="st" style="color: #20794D;">"#' @param ref_date Reference date (typically study baseline / day 1)."</span>,</span>
<span id="cb9-30">    <span class="st" style="color: #20794D;">"#' @return Integer study day."</span>,</span>
<span id="cb9-31">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb9-32">    <span class="st" style="color: #20794D;">"derive_study_day &lt;- function(target_date, ref_date) {"</span>,</span>
<span id="cb9-33">    <span class="st" style="color: #20794D;">"  diff &lt;- as.integer(as.Date(target_date) - as.Date(ref_date))"</span>,</span>
<span id="cb9-34">    <span class="st" style="color: #20794D;">"  ifelse(diff &gt;= 0L, diff + 1L, diff)"</span>,</span>
<span id="cb9-35">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb9-36">  ),</span>
<span id="cb9-37">  <span class="st" style="color: #20794D;">"tests/testthat/test-derivations.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-38">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">REQ-01: derive_age_years converts days to completed years</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-39">    <span class="st" style="color: #20794D;">"  expect_equal(derive_age_years(731), 2L)"</span>,</span>
<span id="cb9-40">    <span class="st" style="color: #20794D;">"})"</span>,</span>
<span id="cb9-41">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-42">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">REQ-01: derive_age_years rejects non-numeric input</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-43">    <span class="st" style="color: #20794D;">"  expect_error(derive_age_years(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">731</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">), </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">days must be numeric</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-44">    <span class="st" style="color: #20794D;">"})"</span></span>
<span id="cb9-45">  )</span>
<span id="cb9-46">)</span>
<span id="cb9-47"></span>
<span id="cb9-48">make_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">path =</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"covdemo"</span>)) {</span>
<span id="cb9-49">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_options</span>(<span class="at" style="color: #657422;">usethis.quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb9-50">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(path, <span class="at" style="color: #657422;">rstudio =</span> <span class="cn" style="color: #8f5902;">FALSE</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-51">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">with_project</span>(path, {</span>
<span id="cb9-52">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_testthat</span>(<span class="dv" style="color: #AD0000;">3</span>)</span>
<span id="cb9-53">  })</span>
<span id="cb9-54">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (rel_path <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">names</span>(demo_files)) {</span>
<span id="cb9-55">    full_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(path, rel_path)</span>
<span id="cb9-56">    <span class="fu" style="color: #4758AB;">dir.create</span>(<span class="fu" style="color: #4758AB;">dirname</span>(full_path), <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-57">    <span class="fu" style="color: #4758AB;">writeLines</span>(demo_files[[rel_path]], full_path)</span>
<span id="cb9-58">  }</span>
<span id="cb9-59">  path</span>
<span id="cb9-60">}</span>
<span id="cb9-61"></span>
<span id="cb9-62">measure_coverage <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb9-63">  covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">package_coverage</span>(path)</span>
<span id="cb9-64">}</span>
<span id="cb9-65"></span>
<span id="cb9-66">coverage_percent <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(cov) {</span>
<span id="cb9-67">  covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">percent_coverage</span>(cov)</span>
<span id="cb9-68">}</span>
<span id="cb9-69"></span>
<span id="cb9-70">uncovered_locations <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(cov) {</span>
<span id="cb9-71">  covr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">zero_coverage</span>(cov)</span>
<span id="cb9-72">}</span>
<span id="cb9-73"></span>
<span id="cb9-74">add_study_day_test <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb9-75">  test_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"tests"</span>, <span class="st" style="color: #20794D;">"testthat"</span>, <span class="st" style="color: #20794D;">"test-derivations.R"</span>)</span>
<span id="cb9-76">  existing <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readLines</span>(test_file)</span>
<span id="cb9-77">  new_test <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-78">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-79">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">REQ-02: derive_study_day computes 1-based day without day 0</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-80">    <span class="st" style="color: #20794D;">"  ref &lt;- </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">2026-09-27</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb9-81">    <span class="st" style="color: #20794D;">"  expect_equal(derive_study_day(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">2026-09-27</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, ref), 1L)"</span>,</span>
<span id="cb9-82">    <span class="st" style="color: #20794D;">"  expect_equal(derive_study_day(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">2026-09-28</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, ref), 2L)"</span>,</span>
<span id="cb9-83">    <span class="st" style="color: #20794D;">"  expect_equal(derive_study_day(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">2026-09-26</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, ref), -1L)"</span>,</span>
<span id="cb9-84">    <span class="st" style="color: #20794D;">"})"</span></span>
<span id="cb9-85">  )</span>
<span id="cb9-86">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="fu" style="color: #4758AB;">c</span>(existing, new_test), test_file)</span>
<span id="cb9-87">}</span>
<span id="cb9-88"></span>
<span id="cb9-89">run_package_tests <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path, <span class="at" style="color: #657422;">reporter =</span> <span class="st" style="color: #20794D;">"silent"</span>, <span class="at" style="color: #657422;">xml_file =</span> <span class="cn" style="color: #8f5902;">NULL</span>) {</span>
<span id="cb9-90">  rep <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(xml_file)) {</span>
<span id="cb9-91">    testthat<span class="sc" style="color: #5E5E5E;">::</span>MultiReporter<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(<span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb9-92">      testthat<span class="sc" style="color: #5E5E5E;">::</span>SummaryReporter<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(),</span>
<span id="cb9-93">      testthat<span class="sc" style="color: #5E5E5E;">::</span>JunitReporter<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(<span class="at" style="color: #657422;">file =</span> xml_file)</span>
<span id="cb9-94">    ))</span>
<span id="cb9-95">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb9-96">    reporter</span>
<span id="cb9-97">  }</span>
<span id="cb9-98">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_local</span>(path, <span class="at" style="color: #657422;">reporter =</span> rep, <span class="at" style="color: #657422;">stop_on_failure =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-99">}</span>
<span id="cb9-100"></span>
<span id="cb9-101">build_traceability <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(test_results) {</span>
<span id="cb9-102">  df <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as.data.frame</span>(test_results)</span>
<span id="cb9-103">  has_req <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"^REQ-[0-9]+:"</span>, df<span class="sc" style="color: #5E5E5E;">$</span>test)</span>
<span id="cb9-104">  req_id <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ifelse</span>(has_req, <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">":.*$"</span>, <span class="st" style="color: #20794D;">""</span>, df<span class="sc" style="color: #5E5E5E;">$</span>test), <span class="cn" style="color: #8f5902;">NA_character_</span>)</span>
<span id="cb9-105">  req_desc <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb9-106">    has_req,</span>
<span id="cb9-107">    <span class="fu" style="color: #4758AB;">trimws</span>(<span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"^[^:]+:[[:space:]]*"</span>, <span class="st" style="color: #20794D;">""</span>, df<span class="sc" style="color: #5E5E5E;">$</span>test)),</span>
<span id="cb9-108">    df<span class="sc" style="color: #5E5E5E;">$</span>test</span>
<span id="cb9-109">  )</span>
<span id="cb9-110">  status <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb9-111">    df<span class="sc" style="color: #5E5E5E;">$</span>skipped,</span>
<span id="cb9-112">    <span class="st" style="color: #20794D;">"SKIPPED"</span>,</span>
<span id="cb9-113">    <span class="fu" style="color: #4758AB;">ifelse</span>(df<span class="sc" style="color: #5E5E5E;">$</span>failed <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span>df<span class="sc" style="color: #5E5E5E;">$</span>error, <span class="st" style="color: #20794D;">"PASS"</span>, <span class="st" style="color: #20794D;">"FAIL"</span>)</span>
<span id="cb9-114">  )</span>
<span id="cb9-115"></span>
<span id="cb9-116">  <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb9-117">    <span class="at" style="color: #657422;">requirement_id =</span> req_id,</span>
<span id="cb9-118">    <span class="at" style="color: #657422;">description =</span> req_desc,</span>
<span id="cb9-119">    <span class="at" style="color: #657422;">test_file =</span> <span class="fu" style="color: #4758AB;">basename</span>(df<span class="sc" style="color: #5E5E5E;">$</span>file),</span>
<span id="cb9-120">    <span class="at" style="color: #657422;">passed_expectations =</span> df<span class="sc" style="color: #5E5E5E;">$</span>passed,</span>
<span id="cb9-121">    <span class="at" style="color: #657422;">status =</span> status,</span>
<span id="cb9-122">    <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb9-123">  )</span>
<span id="cb9-124">}</span>
<span id="cb9-125"></span>
<span id="cb9-126"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb9-127">  pkg_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">make_demo_package</span>()</span>
<span id="cb9-128">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Measuring initial package coverage (derive_study_day uncovered)..."</span>)</span>
<span id="cb9-129">  cov_initial <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">measure_coverage</span>(pkg_path)</span>
<span id="cb9-130">  pct_initial <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">coverage_percent</span>(cov_initial)</span>
<span id="cb9-131">  <span class="fu" style="color: #4758AB;">message</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Initial coverage: %.1f%%"</span>, pct_initial))</span>
<span id="cb9-132"></span>
<span id="cb9-133">  zero_locs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">uncovered_locations</span>(cov_initial)</span>
<span id="cb9-134">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Uncovered code locations:"</span>)</span>
<span id="cb9-135">  <span class="fu" style="color: #4758AB;">print</span>(zero_locs[, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"filename"</span>, <span class="st" style="color: #20794D;">"functions"</span>, <span class="st" style="color: #20794D;">"line"</span>)])</span>
<span id="cb9-136"></span>
<span id="cb9-137">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">Adding test for REQ-02 (derive_study_day)..."</span>)</span>
<span id="cb9-138">  <span class="fu" style="color: #4758AB;">add_study_day_test</span>(pkg_path)</span>
<span id="cb9-139"></span>
<span id="cb9-140">  cov_updated <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">measure_coverage</span>(pkg_path)</span>
<span id="cb9-141">  pct_updated <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">coverage_percent</span>(cov_updated)</span>
<span id="cb9-142">  <span class="fu" style="color: #4758AB;">message</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Updated coverage: %.1f%%"</span>, pct_updated))</span>
<span id="cb9-143"></span>
<span id="cb9-144">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">Executing test suite and writing JUnit XML evidence..."</span>)</span>
<span id="cb9-145">  xml_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(pkg_path, <span class="st" style="color: #20794D;">"test-results.xml"</span>)</span>
<span id="cb9-146">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_package_tests</span>(pkg_path, <span class="at" style="color: #657422;">xml_file =</span> xml_path)</span>
<span id="cb9-147"></span>
<span id="cb9-148">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">Requirement-to-test traceability matrix:"</span>)</span>
<span id="cb9-149">  trace_matrix <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">build_traceability</span>(results)</span>
<span id="cb9-150">  <span class="fu" style="color: #4758AB;">print</span>(trace_matrix)</span>
<span id="cb9-151"></span>
<span id="cb9-152">  <span class="fu" style="color: #4758AB;">message</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">JUnit XML written to: %s"</span>, xml_path))</span>
<span id="cb9-153">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>covr</strong>: <a href="https://covr.r-lib.org">covr.r-lib.org</a></li>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
</ul>
<p><strong>Standards and CI references</strong></p>
<ul>
<li><strong>R Validation Hub white paper</strong> (<em>A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure</em>): <a href="https://pharmar.org/white-paper/">pharmar.org/white-paper</a></li>
<li><strong>r-lib/actions test-coverage example</strong>: <a href="https://github.com/r-lib/actions/blob/v2-branch/examples/test-coverage.yaml">github.com/r-lib/actions</a></li>
</ul>
<p><strong>Web-repo comparison</strong></p>
<ul>
<li><strong>Vitest coverage thresholds</strong>: <a href="https://vitest.dev/config/#coverage-thresholds">vitest.dev/config/#coverage-thresholds</a></li>
<li><strong>Istanbul</strong>: <a href="https://istanbul.js.org/">istanbul.js.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-series-nav__series">Testing series · part 7 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/property-based-testing/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 6</span><span class="site-related-card__title">Property-based testing in R</span></a>
</div>
</div>
</div>
<section id="also-in" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="also-in">Also in</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-link-row" title="Follow R through clinical reporting, from the data pipeline to tables, figures, listings and analysis results metadata. The parts show where open-source R packages fit in that work."><span class="is-card__eyebrow site-link-row__label">Series · 7 parts</span><span class="site-link-row__title">Pharma series</span></a></li>
</ul>
</div>
</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/test-your-guardrails/index.html" class="site-link-row" title="Challenge CI checks and pre-commit hooks deliberately with failing test PRs to prove guardrails work."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Test your guardrails: probe PRs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/index.html" class="site-link-row" title="Which R packages cover each stage of clinical reporting, from raw data to SDTM, ADaM, TFLs and submission files, and how the stages connect."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">The clinical reporting pipeline in R</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R packages</category>
  <category>CI/CD</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/</guid>
  <pubDate>Sat, 26 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>It worked locally: two hosting bugs every check missed</title>
  <link>https://insightsurge-dev.web.app/posts/hosted-site-pitfalls/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Before the pull request preview, the local verification suite reported success:</p>
<ol type="1">
<li><strong>Rendering:</strong> <code>quarto render</code> generated the entire site without a single warning.</li>
<li><strong>Automated link scanning:</strong> An offline link checker scanned 1,712 internal links across the rendered HTML files and reported 0 broken links.</li>
<li><strong>Automated tests:</strong> The full <code>testthat</code> test suite passed cleanly.</li>
<li><strong>Local manual review:</strong> We started a local <code>python3 -m http.server</code> and typed a post URL with the trailing slash into the browser address bar.</li>
</ol>
<p>The branch was pushed and the pull request opened. CI deployed the rendered site to a Firebase Hosting preview channel (see <a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html">Quarto Firebase previews</a>).</p>
<p>Clicking through the preview exposed two hosting bugs.</p>
<section id="bug-1-the-trailing-slash-and-the-404-trap" class="level3">
<h3 class="anchored" data-anchor-id="bug-1-the-trailing-slash-and-the-404-trap">Bug 1: The trailing slash and the 404 trap</h3>
<p>A post card on the blog index (<code>/blog</code>) linked to <code>posts/qc-demo/index.html</code>. After clicking it, the browser address bar showed <code>https://example.web.app/posts/qc-demo</code>.</p>
<p>Near the bottom of the article, clicking the relative <strong>View</strong> link for a companion R script navigated to:</p>
<pre class="text"><code>https://example.web.app/posts/scripts/qc-demo.R</code></pre>
<p>The browser displayed a <code>404 Not Found</code> error page.</p>
<p>Yet the file had been rendered and published. When requested directly at its full path, the server responded with <code>200 OK</code>:</p>
<pre class="text"><code>https://example.web.app/posts/qc-demo/scripts/qc-demo.R</code></pre>
<p>The bug stemmed from how web hosts implement clean URLs. In <code>firebase.json</code>, we had enabled <code>"cleanUrls": true</code>. When a user requests <code>posts/qc-demo/index.html</code>, Firebase Hosting issues an HTTP <code>301 Moved Permanently</code> redirect to <code>/posts/qc-demo</code> (without a trailing slash) and serves the page with <code>200 OK</code>.</p>
<p>Under RFC 3986 (Section 5.2.3, “Merge Paths”), when a browser resolves a relative URL reference that does not begin with a leading slash, it resolves the reference against the directory component of the base URI. When the base URL is <code>https://example.web.app/posts/qc-demo</code>:</p>
<ul>
<li>The final path segment (<code>qc-demo</code>) does not end with a slash, so the browser interprets it as a file name rather than a directory.</li>
<li>The browser strips <code>qc-demo</code> to determine the base directory, leaving <code>https://example.web.app/posts/</code>.</li>
<li>Appending the companion link produces <code>https://example.web.app/posts/scripts/qc-demo.R</code>, which does not exist.</li>
</ul>
<p>Had the base URL contained a trailing slash (<code>https://example.web.app/posts/qc-demo/</code>), the base directory would have remained <code>https://example.web.app/posts/qc-demo/</code>, resolving the relative link to the correct file.</p>
<p>Inspecting the preview server with <code>curl</code> revealed the exact redirect chain:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="co" style="color: #5E5E5E;"># Requesting the index file triggers cleanUrls redirect to the non-slashed URL</span></span>
<span id="cb3-2"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> https://example.web.app/posts/qc-demo/index.html <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-E</span> <span class="st" style="color: #20794D;">"^(HTTP|location)"</span></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;"># HTTP/2 301</span></span>
<span id="cb3-4"><span class="co" style="color: #5E5E5E;"># location: /posts/qc-demo</span></span>
<span id="cb3-5"></span>
<span id="cb3-6"><span class="co" style="color: #5E5E5E;"># The non-slashed URL serves content directly</span></span>
<span id="cb3-7"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> https://example.web.app/posts/qc-demo <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-E</span> <span class="st" style="color: #20794D;">"^(HTTP)"</span></span>
<span id="cb3-8"><span class="co" style="color: #5E5E5E;"># HTTP/2 200</span></span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="co" style="color: #5E5E5E;"># The target file exists under the slug directory</span></span>
<span id="cb3-11"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> https://example.web.app/posts/qc-demo/scripts/qc-demo.R <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-E</span> <span class="st" style="color: #20794D;">"^(HTTP)"</span></span>
<span id="cb3-12"><span class="co" style="color: #5E5E5E;"># HTTP/2 200</span></span>
<span id="cb3-13"></span>
<span id="cb3-14"><span class="co" style="color: #5E5E5E;"># But the relative link resolved from the non-slashed base URL hits 404</span></span>
<span id="cb3-15"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> https://example.web.app/posts/scripts/qc-demo.R <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-E</span> <span class="st" style="color: #20794D;">"^(HTTP)"</span></span>
<span id="cb3-16"><span class="co" style="color: #5E5E5E;"># HTTP/2 404</span></span></code></pre></div></div>
<p>Why did local checks miss this?</p>
<ul>
<li><strong>The offline link checker operates on disk:</strong> An offline tool like <code>lychee</code> parses <code>_site/posts/qc-demo/index.html</code> from the file system. Because the file physically resides in <code>_site/posts/qc-demo/</code>, the tool finds the companion file in that directory. An offline scanner does not simulate HTTP redirects.</li>
<li><strong>The local URL kept its slash:</strong> Python’s local server served <code>/posts/qc-demo/</code> without the Firebase redirect, so the browser used the post directory as the base.</li>
<li><strong>Manual review typed the trailing slash:</strong> We typed <code>/posts/qc-demo/</code> into the address bar, masking the redirect from the listing link.</li>
<li><strong>Quarto navigation links did not fail:</strong> Quarto site navigation links (such as <code>../../series/foundations.html</code>) use <code>../</code> to navigate up to the root. Because <code>..</code> cannot ascend above the site root <code>/</code>, those links functioned even from the wrong base path. Only relative child links pointing into the post’s own subdirectory broke.</li>
</ul>
</section>
<section id="bug-2-compressed-responses-and-single-line-r-scripts" class="level3">
<h3 class="anchored" data-anchor-id="bug-2-compressed-responses-and-single-line-r-scripts">Bug 2: Compressed responses and single-line R scripts</h3>
<p>Opening the valid script URL directly showed the second bug:</p>
<pre class="text"><code>https://example.web.app/posts/qc-demo/scripts/qc-demo.R</code></pre>
<p>Instead of displaying formatted R code with newlines and comments, the browser displayed the entire script as a single continuous paragraph of plain text. All indentation and line breaks were collapsed into single spaces.</p>
<p>The browser was rendering the <code>.R</code> file as HTML (<code>text/html</code>), where consecutive whitespace characters are collapsed into a single space per HTML rendering rules.</p>
<p>A plain <code>curl -sI</code> request returned this header:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb5-1"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> https://example.web.app/posts/qc-demo/scripts/qc-demo.R <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-i</span> <span class="st" style="color: #20794D;">"content-type"</span></span>
<span id="cb5-2"><span class="co" style="color: #5E5E5E;"># content-type: text/plain; charset=utf-8</span></span></code></pre></div></div>
<p>The <code>text/plain</code> response looked correct until compression headers were included.</p>
<p>The difference lay in how browsers request content. Modern web browsers automatically send compression request headers: <code>Accept-Encoding: gzip, br</code>. When <code>curl</code> sends those same headers, the server’s response changes:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="co" style="color: #5E5E5E;"># Request without compression headers</span></span>
<span id="cb6-2"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> https://example.web.app/posts/qc-demo/scripts/qc-demo.R <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-i</span> <span class="st" style="color: #20794D;">"content-type"</span></span>
<span id="cb6-3"><span class="co" style="color: #5E5E5E;"># content-type: text/plain; charset=utf-8</span></span>
<span id="cb6-4"></span>
<span id="cb6-5"><span class="co" style="color: #5E5E5E;"># Request with browser compression headers</span></span>
<span id="cb6-6"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> <span class="at" style="color: #657422;">-H</span> <span class="st" style="color: #20794D;">"Accept-Encoding: gzip, br"</span> https://example.web.app/posts/qc-demo/scripts/qc-demo.R <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-i</span> <span class="st" style="color: #20794D;">"content-type"</span></span>
<span id="cb6-7"><span class="co" style="color: #5E5E5E;"># content-type: text/html; charset=UTF-8</span></span></code></pre></div></div>
<p>On this deployment, requests with compression headers for <code>.R</code> files and the extensionless Git <code>commit-msg</code> hook returned <code>text/html; charset=UTF-8</code>. By contrast, shell scripts (<code>.sh</code>) returned <code>application/x-sh</code> (prompting a browser download), YAML (<code>.yml</code>) returned <code>text/yaml</code>, and Markdown (<code>.md</code>) returned <code>text/markdown</code>.</p>
<p>We did not find Firebase documentation explaining why compressed responses for unrecognised MIME types default to <code>text/html</code>. We report this strictly as observed production behavior.</p>
</section>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>Front-end web engineering teams have long recognized that local file systems and generic development servers do not replicate the routing, caching, and compression behavior of production content delivery networks (CDNs). They guard against hosting defects using five standard practices:</p>
<ol type="1">
<li><strong>Ephemeral preview environments:</strong> Rather than relying exclusively on local development servers, web teams deploy pull requests to isolated preview channels on the real hosting platform (such as Firebase Hosting preview channels, Netlify Deploy Previews, or Cloudflare Pages branch deployments). The preview exercises the exact edge routing, HTTP caching, and header rewrite rules of production.</li>
<li><strong>Platform emulators for local testing:</strong> The host platform’s emulator can exercise its routing rules locally. For Firebase Hosting, <code>npx firebase-tools emulators:start --only hosting --project demo-preview</code> uses a demo project ID without a Google Cloud login and lets you check clean URLs, redirects, and custom headers.</li>
<li><strong>Browser-realistic smoke tests:</strong> Automated post-deployment checks send realistic browser headers (<code>Accept-Encoding: gzip, br</code> and <code>Accept: text/html,...</code>) to verify status codes, redirect chains (<code>Location</code>), and <code>Content-Type</code> headers.</li>
<li><strong>Explicit configuration over CDN defaults:</strong> Web teams do not rely on default MIME type tables for custom file formats or extensionless assets. They declare explicit MIME mappings and security headers (such as <code>X-Content-Type-Options: nosniff</code>) in their repository configuration files.</li>
<li><strong>Configuration regression tests:</strong> Critical routing and header rules in hosting configuration files are asserted in automated unit tests so they cannot be removed accidentally during repository refactoring.</li>
</ol>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In the R ecosystem, documentation sites and analysis reports are typically compiled to static HTML directories using Quarto, pkgdown, or R Markdown. Applying web hosting discipline to these sites requires addressing the directory structure, configuring explicit host rules, and adding verification tests.</p>
<section id="directory-layout-and-relative-links-in-r-sites" class="level3">
<h3 class="anchored" data-anchor-id="directory-layout-and-relative-links-in-r-sites">1. Directory layout and relative links in R sites</h3>
<p>Static site generators in R organize content into folders with directory index files:</p>
<ul>
<li>Quarto blog articles: <code>_site/posts/&lt;slug&gt;/index.html</code></li>
<li>pkgdown documentation: <code>docs/reference/index.html</code> and <code>docs/articles/index.html</code></li>
</ul>
<p>In R engineering documentation, articles often reference downloadable companion files—such as runnable analysis scripts, raw CSV datasets, or validation test scripts—using relative paths (for example, <code>[scripts/hosting-check.R](scripts/hosting-check.R)</code>).</p>
<p>When a host serves a directory index at <code>/posts/&lt;slug&gt;</code> without a trailing slash, a relative child link resolves under <code>/posts/</code>. Check the host’s redirects and the final browser URL for pages with links into their own directories.</p>
</section>
<section id="fixing-the-trailing-slash-in-firebase.json" class="level3">
<h3 class="anchored" data-anchor-id="fixing-the-trailing-slash-in-firebase.json">2. Fixing the trailing slash in <code>firebase.json</code></h3>
<p>Firebase Hosting provides a global <code>"trailingSlash": true</code> setting that redirects static content URLs to add a trailing slash. We did not test that option. It would change URLs across the site, so it would need site-wide link and browser checks.</p>
<p>Instead of altering the global slash behavior, we configure a targeted 301 redirect rule in <code>firebase.json</code> using RE2 regular expressions:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode json code-with-copy"><code class="sourceCode json"><span id="cb7-1"><span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb7-2">  <span class="dt" style="color: #AD0000;">"hosting"</span><span class="fu" style="color: #4758AB;">:</span> <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb7-3">    <span class="dt" style="color: #AD0000;">"public"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"_site"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb7-4">    <span class="dt" style="color: #AD0000;">"cleanUrls"</span><span class="fu" style="color: #4758AB;">:</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">true</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb7-5">    <span class="dt" style="color: #AD0000;">"redirects"</span><span class="fu" style="color: #4758AB;">:</span> <span class="ot" style="color: #003B4F;">[</span></span>
<span id="cb7-6">      <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb7-7">        <span class="dt" style="color: #AD0000;">"regex"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"^/posts/([^/.]+)$"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb7-8">        <span class="dt" style="color: #AD0000;">"destination"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"/posts/:1/"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb7-9">        <span class="dt" style="color: #AD0000;">"type"</span><span class="fu" style="color: #4758AB;">:</span> <span class="dv" style="color: #AD0000;">301</span></span>
<span id="cb7-10">      <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb7-11">    <span class="ot" style="color: #003B4F;">]</span></span>
<span id="cb7-12">  <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb7-13"><span class="fu" style="color: #4758AB;">}</span></span></code></pre></div></div>
<p>This rule matches any URL path under <code>/posts/</code> that contains no subsequent slashes or file extension dots, captures the slug into group <code>:1</code>, and issues an HTTP 301 redirect that appends the trailing slash.</p>
<p>With this rule active, opening an article from the listing involves two redirects, then the page and its companion link:</p>
<ol type="1">
<li><code>posts/qc-demo/index.html</code> triggers a 301 redirect to <code>/posts/qc-demo</code> via <code>cleanUrls</code>.</li>
<li><code>/posts/qc-demo</code> triggers a 301 redirect to <code>/posts/qc-demo/</code> via the regex redirect rule.</li>
<li><code>/posts/qc-demo/</code> serves the rendered page with <code>200 OK</code>.</li>
<li>The relative companion link resolves inside the post directory and returns <code>200 OK</code>.</li>
</ol>
<p>Root pages (such as <code>/blog</code>) remain unaffected.</p>
</section>
<section id="fixing-mime-types-and-compression-headers" class="level3">
<h3 class="anchored" data-anchor-id="fixing-mime-types-and-compression-headers">3. Fixing MIME types and compression headers</h3>
<p>There is no standard media type for R source files. To ensure that R scripts, shell scripts, and extensionless files are delivered as plain text across all compression encodings, we define explicit <code>headers</code> in <code>firebase.json</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode json code-with-copy"><code class="sourceCode json"><span id="cb8-1"><span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb8-2">  <span class="dt" style="color: #AD0000;">"hosting"</span><span class="fu" style="color: #4758AB;">:</span> <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb8-3">    <span class="dt" style="color: #AD0000;">"headers"</span><span class="fu" style="color: #4758AB;">:</span> <span class="ot" style="color: #003B4F;">[</span></span>
<span id="cb8-4">      <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb8-5">        <span class="dt" style="color: #AD0000;">"source"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"**/*.@(R|sh)"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb8-6">        <span class="dt" style="color: #AD0000;">"headers"</span><span class="fu" style="color: #4758AB;">:</span> <span class="ot" style="color: #003B4F;">[</span></span>
<span id="cb8-7">          <span class="fu" style="color: #4758AB;">{</span> <span class="dt" style="color: #AD0000;">"key"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"Content-Type"</span><span class="fu" style="color: #4758AB;">,</span> <span class="dt" style="color: #AD0000;">"value"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"text/plain; charset=utf-8"</span> <span class="fu" style="color: #4758AB;">}</span><span class="ot" style="color: #003B4F;">,</span></span>
<span id="cb8-8">          <span class="fu" style="color: #4758AB;">{</span> <span class="dt" style="color: #AD0000;">"key"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"X-Content-Type-Options"</span><span class="fu" style="color: #4758AB;">,</span> <span class="dt" style="color: #AD0000;">"value"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"nosniff"</span> <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb8-9">        <span class="ot" style="color: #003B4F;">]</span></span>
<span id="cb8-10">      <span class="fu" style="color: #4758AB;">}</span><span class="ot" style="color: #003B4F;">,</span></span>
<span id="cb8-11">      <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb8-12">        <span class="dt" style="color: #AD0000;">"source"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"/templates/git-hooks/commit-msg"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb8-13">        <span class="dt" style="color: #AD0000;">"headers"</span><span class="fu" style="color: #4758AB;">:</span> <span class="ot" style="color: #003B4F;">[</span></span>
<span id="cb8-14">          <span class="fu" style="color: #4758AB;">{</span> <span class="dt" style="color: #AD0000;">"key"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"Content-Type"</span><span class="fu" style="color: #4758AB;">,</span> <span class="dt" style="color: #AD0000;">"value"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"text/plain; charset=utf-8"</span> <span class="fu" style="color: #4758AB;">}</span><span class="ot" style="color: #003B4F;">,</span></span>
<span id="cb8-15">          <span class="fu" style="color: #4758AB;">{</span> <span class="dt" style="color: #AD0000;">"key"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"X-Content-Type-Options"</span><span class="fu" style="color: #4758AB;">,</span> <span class="dt" style="color: #AD0000;">"value"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"nosniff"</span> <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb8-16">        <span class="ot" style="color: #003B4F;">]</span></span>
<span id="cb8-17">      <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb8-18">    <span class="ot" style="color: #003B4F;">]</span></span>
<span id="cb8-19">  <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb8-20"><span class="fu" style="color: #4758AB;">}</span></span></code></pre></div></div>
<p>The <code>X-Content-Type-Options: nosniff</code> header instructs browsers to follow the declared MIME type strictly, preventing browsers from attempting MIME type sniffing on response bodies.</p>
</section>
<section id="testing-like-a-browser" class="level3">
<h3 class="anchored" data-anchor-id="testing-like-a-browser">4. Testing like a browser</h3>
<p>To catch hosting bugs before release, teams should incorporate browser-like verification into their routine R workflow:</p>
<p>First, test locally using the platform emulator rather than a generic server:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb9-1"><span class="ex" style="color: null;">npx</span> firebase-tools emulators:start <span class="at" style="color: #657422;">--only</span> hosting <span class="at" style="color: #657422;">--project</span> demo-preview</span></code></pre></div></div>
<p>Second, follow the real user path: open the listing page, click into an article card, and click a companion script link.</p>
<p>Third, verify HTTP response headers using <code>curl</code> with compression flags enabled:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb10-1"><span class="ex" style="color: null;">curl</span> <span class="at" style="color: #657422;">-sI</span> <span class="at" style="color: #657422;">-H</span> <span class="st" style="color: #20794D;">"Accept-Encoding: gzip, br"</span> https://example.web.app/posts/qc-demo/scripts/qc-demo.R</span></code></pre></div></div>
<p>Fourth, write guardrail tests in <code>testthat</code> to ensure that hosting configuration rules cannot be deleted inadvertently:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="co" style="color: #5E5E5E;"># Read the hosting configuration committed with the site.</span></span>
<span id="cb11-2">config_text <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">paste</span>(<span class="fu" style="color: #4758AB;">readLines</span>(<span class="st" style="color: #20794D;">"firebase.json"</span>), <span class="at" style="color: #657422;">collapse =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb11-3"></span>
<span id="cb11-4"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"hosting configuration retains redirect and header guardrails"</span>, {</span>
<span id="cb11-5">  <span class="fu" style="color: #4758AB;">expect_match</span>(config_text, <span class="st" style="color: #20794D;">'"regex": "^/posts/([^/.]+)$"'</span>, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb11-6">  <span class="fu" style="color: #4758AB;">expect_match</span>(config_text, <span class="st" style="color: #20794D;">'"destination": "/posts/:1/"'</span>, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb11-7">  <span class="fu" style="color: #4758AB;">expect_match</span>(config_text, <span class="st" style="color: #20794D;">'"source": "**/*.@(R|sh)"'</span>, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb11-8">  <span class="fu" style="color: #4758AB;">expect_match</span>(config_text, <span class="st" style="color: #20794D;">'"source": "/templates/git-hooks/commit-msg"'</span>, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb11-9">  <span class="fu" style="color: #4758AB;">expect_match</span>(config_text, <span class="st" style="color: #20794D;">'"value": "text/plain; charset=utf-8"'</span>, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb11-10">})</span></code></pre></div></div>
</section>
<section id="other-static-hosting-platforms" class="level3">
<h3 class="anchored" data-anchor-id="other-static-hosting-platforms">5. Other static hosting platforms</h3>
<p>Different static hosting platforms document their own URL and header rules:</p>
<ul>
<li><strong>Netlify:</strong> With Pretty URLs enabled (the default), Netlify forwards a path such as <code>/about</code> to <code>/about/</code> and rewrites <code>/about.html</code> to <code>/about/</code>. Custom headers can be set in <code>_headers</code> or <code>netlify.toml</code>.</li>
<li><strong>Cloudflare Pages:</strong> Its serving rules redirect <code>/about/index.html</code> to <code>/about/</code>. Custom static-asset headers can be set in a <code>_headers</code> file in the build output.</li>
</ul>
<p>Regardless of which hosting platform you use, verify your URLs with <code>curl -sI -H "Accept-Encoding: gzip, br" &lt;url&gt;</code> before sharing rendered documentation with readers.</p>
</section>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/hosted-site-pitfalls/scripts/hosting-check.R">View <code>hosting-check.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/hosted-site-pitfalls/scripts/hosting-check.R" download="hosting-check.R">Download</a></p>
<p>A standalone verification script that scans rendered site directories for relative link traps in directory index pages and verifies HTTP response headers against browser compression encodings. Written in base R and verified with <code>testthat</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>hosting-check.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="co" style="color: #5E5E5E;"># Host verification checks: detects trailing-slash relative link traps</span></span>
<span id="cb12-2"><span class="co" style="color: #5E5E5E;"># in rendered sites and verifies HTTP response headers for non-HTML assets.</span></span>
<span id="cb12-3"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb12-4"><span class="co" style="color: #5E5E5E;"># Run with:</span></span>
<span id="cb12-5"><span class="co" style="color: #5E5E5E;">#   Rscript hosting-check.R</span></span>
<span id="cb12-6"><span class="co" style="color: #5E5E5E;">#   Rscript hosting-check.R --site _site</span></span>
<span id="cb12-7"><span class="co" style="color: #5E5E5E;">#   Rscript hosting-check.R --url https://example.web.app/posts/slug/scripts/demo.R</span></span>
<span id="cb12-8"></span>
<span id="cb12-9"><span class="co" style="color: #5E5E5E;">#' Scan a rendered directory for relative links vulnerable to trailing-slash stripping</span></span>
<span id="cb12-10"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb12-11"><span class="co" style="color: #5E5E5E;">#' In static site hosting, directory pages served as `&lt;dir&gt;/index.html` often have</span></span>
<span id="cb12-12"><span class="co" style="color: #5E5E5E;">#' the `.html` extension stripped by clean URL rules. If the host serves the page</span></span>
<span id="cb12-13"><span class="co" style="color: #5E5E5E;">#' at `/dir` without a trailing slash, RFC 3986 path resolution strips `dir` as a</span></span>
<span id="cb12-14"><span class="co" style="color: #5E5E5E;">#' file component and resolves relative links against the parent directory.</span></span>
<span id="cb12-15"><span class="co" style="color: #5E5E5E;">#' This function finds all relative child links within directory index pages.</span></span>
<span id="cb12-16"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb12-17"><span class="co" style="color: #5E5E5E;">#' @param site_dir Path to the rendered site directory (default "_site").</span></span>
<span id="cb12-18"><span class="co" style="color: #5E5E5E;">#' @return A data frame with columns: page, target, resolved_path, exists.</span></span>
<span id="cb12-19">find_relative_directory_links <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">site_dir =</span> <span class="st" style="color: #20794D;">"_site"</span>) {</span>
<span id="cb12-20">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(site_dir)) {</span>
<span id="cb12-21">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb12-22">      <span class="at" style="color: #657422;">page =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-23">      <span class="at" style="color: #657422;">target =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-24">      <span class="at" style="color: #657422;">resolved_path =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-25">      <span class="at" style="color: #657422;">exists =</span> <span class="fu" style="color: #4758AB;">logical</span>(),</span>
<span id="cb12-26">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb12-27">    ))</span>
<span id="cb12-28">  }</span>
<span id="cb12-29"></span>
<span id="cb12-30">  all_indices <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list.files</span>(</span>
<span id="cb12-31">    site_dir,</span>
<span id="cb12-32">    <span class="at" style="color: #657422;">pattern =</span> <span class="st" style="color: #20794D;">"^index</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.html$"</span>,</span>
<span id="cb12-33">    <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb12-34">    <span class="at" style="color: #657422;">full.names =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb12-35">  )</span>
<span id="cb12-36"></span>
<span id="cb12-37">  <span class="co" style="color: #5E5E5E;"># Only inspect index.html files located inside subdirectories</span></span>
<span id="cb12-38">  sub_indices <span class="ot" style="color: #003B4F;">&lt;-</span> all_indices[<span class="fu" style="color: #4758AB;">dirname</span>(all_indices) <span class="sc" style="color: #5E5E5E;">!=</span> <span class="st" style="color: #20794D;">"."</span>]</span>
<span id="cb12-39"></span>
<span id="cb12-40">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(sub_indices) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-41">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb12-42">      <span class="at" style="color: #657422;">page =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-43">      <span class="at" style="color: #657422;">target =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-44">      <span class="at" style="color: #657422;">resolved_path =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-45">      <span class="at" style="color: #657422;">exists =</span> <span class="fu" style="color: #4758AB;">logical</span>(),</span>
<span id="cb12-46">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb12-47">    ))</span>
<span id="cb12-48">  }</span>
<span id="cb12-49"></span>
<span id="cb12-50">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb12-51"></span>
<span id="cb12-52">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (sub_index <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> sub_indices) {</span>
<span id="cb12-53">    full_index_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(site_dir, sub_index)</span>
<span id="cb12-54">    lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readLines</span>(full_index_path, <span class="at" style="color: #657422;">warn =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb12-55">    page_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">dirname</span>(sub_index)</span>
<span id="cb12-56"></span>
<span id="cb12-57">    <span class="co" style="color: #5E5E5E;"># Extract href and src attribute values</span></span>
<span id="cb12-58">    href_matches <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">regmatches</span>(</span>
<span id="cb12-59">      lines,</span>
<span id="cb12-60">      <span class="fu" style="color: #4758AB;">gregexpr</span>(<span class="st" style="color: #20794D;">'(?:href|src)=["</span><span class="sc" style="color: #5E5E5E;">\'</span><span class="st" style="color: #20794D;">]([^"</span><span class="sc" style="color: #5E5E5E;">\'</span><span class="st" style="color: #20794D;">]+)["</span><span class="sc" style="color: #5E5E5E;">\'</span><span class="st" style="color: #20794D;">]'</span>, lines, <span class="at" style="color: #657422;">perl =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-61">    )</span>
<span id="cb12-62"></span>
<span id="cb12-63">    targets <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb12-64">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (m <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> href_matches) {</span>
<span id="cb12-65">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(m) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-66">        cleaned <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">'^(?:href|src)=["</span><span class="sc" style="color: #5E5E5E;">\'</span><span class="st" style="color: #20794D;">]'</span>, <span class="st" style="color: #20794D;">""</span>, m)</span>
<span id="cb12-67">        cleaned <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">'["</span><span class="sc" style="color: #5E5E5E;">\'</span><span class="st" style="color: #20794D;">]$'</span>, <span class="st" style="color: #20794D;">""</span>, cleaned)</span>
<span id="cb12-68">        targets <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(targets, cleaned)</span>
<span id="cb12-69">      }</span>
<span id="cb12-70">    }</span>
<span id="cb12-71">    targets <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">unique</span>(targets)</span>
<span id="cb12-72"></span>
<span id="cb12-73">    <span class="co" style="color: #5E5E5E;"># Filter out anchors, query-only, root-relative, parent-relative, and URI schemes</span></span>
<span id="cb12-74">    is_scheme <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"^[a-zA-Z][a-zA-Z0-9+.-]*:"</span>, targets)</span>
<span id="cb12-75">    is_root_rel <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">startsWith</span>(targets, <span class="st" style="color: #20794D;">"/"</span>)</span>
<span id="cb12-76">    is_anchor <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">startsWith</span>(targets, <span class="st" style="color: #20794D;">"#"</span>)</span>
<span id="cb12-77">    is_query <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">startsWith</span>(targets, <span class="st" style="color: #20794D;">"?"</span>)</span>
<span id="cb12-78">    is_parent_rel <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">startsWith</span>(targets, <span class="st" style="color: #20794D;">"../"</span>)</span>
<span id="cb12-79">    is_blank <span class="ot" style="color: #003B4F;">&lt;-</span> targets <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">""</span></span>
<span id="cb12-80"></span>
<span id="cb12-81">    child_relative <span class="ot" style="color: #003B4F;">&lt;-</span> targets[</span>
<span id="cb12-82">      <span class="sc" style="color: #5E5E5E;">!</span>is_scheme <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb12-83">        <span class="sc" style="color: #5E5E5E;">!</span>is_root_rel <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb12-84">        <span class="sc" style="color: #5E5E5E;">!</span>is_anchor <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb12-85">        <span class="sc" style="color: #5E5E5E;">!</span>is_query <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb12-86">        <span class="sc" style="color: #5E5E5E;">!</span>is_parent_rel <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb12-87">        <span class="sc" style="color: #5E5E5E;">!</span>is_blank</span>
<span id="cb12-88">    ]</span>
<span id="cb12-89"></span>
<span id="cb12-90">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (target <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> child_relative) {</span>
<span id="cb12-91">      <span class="co" style="color: #5E5E5E;"># Strip anchor or query string for disk path check</span></span>
<span id="cb12-92">      disk_target <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"[?#].*$"</span>, <span class="st" style="color: #20794D;">""</span>, target)</span>
<span id="cb12-93">      resolved_rel <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(page_dir, disk_target)</span>
<span id="cb12-94">      target_exists <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.exists</span>(<span class="fu" style="color: #4758AB;">file.path</span>(site_dir, resolved_rel))</span>
<span id="cb12-95"></span>
<span id="cb12-96">      results[[<span class="fu" style="color: #4758AB;">length</span>(results) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-97">        <span class="at" style="color: #657422;">page =</span> sub_index,</span>
<span id="cb12-98">        <span class="at" style="color: #657422;">target =</span> target,</span>
<span id="cb12-99">        <span class="at" style="color: #657422;">resolved_path =</span> resolved_rel,</span>
<span id="cb12-100">        <span class="at" style="color: #657422;">exists =</span> target_exists</span>
<span id="cb12-101">      )</span>
<span id="cb12-102">    }</span>
<span id="cb12-103">  }</span>
<span id="cb12-104"></span>
<span id="cb12-105">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(results) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-106">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb12-107">      <span class="at" style="color: #657422;">page =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-108">      <span class="at" style="color: #657422;">target =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-109">      <span class="at" style="color: #657422;">resolved_path =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-110">      <span class="at" style="color: #657422;">exists =</span> <span class="fu" style="color: #4758AB;">logical</span>(),</span>
<span id="cb12-111">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb12-112">    ))</span>
<span id="cb12-113">  }</span>
<span id="cb12-114"></span>
<span id="cb12-115">  <span class="fu" style="color: #4758AB;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;">lapply</span>(results, as.data.frame, <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span>))</span>
<span id="cb12-116">}</span>
<span id="cb12-117"></span>
<span id="cb12-118"><span class="co" style="color: #5E5E5E;">#' Parse raw HTTP response headers</span></span>
<span id="cb12-119"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb12-120"><span class="co" style="color: #5E5E5E;">#' Parses raw header lines returned by curl into structured status and header fields.</span></span>
<span id="cb12-121"><span class="co" style="color: #5E5E5E;">#' Correctly handles redirect chains (e.g. 301 followed by 200).</span></span>
<span id="cb12-122"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb12-123"><span class="co" style="color: #5E5E5E;">#' @param raw_headers Character vector of header lines, or a single newline-delimited string.</span></span>
<span id="cb12-124"><span class="co" style="color: #5E5E5E;">#' @return A list with status_code, protocol, headers (named vector), redirects, and chain.</span></span>
<span id="cb12-125">parse_http_headers <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(raw_headers) {</span>
<span id="cb12-126">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(raw_headers) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">1</span>L <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"[</span><span class="sc" style="color: #5E5E5E;">\r\n</span><span class="st" style="color: #20794D;">]"</span>, raw_headers)) {</span>
<span id="cb12-127">    lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">strsplit</span>(raw_headers, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\r</span><span class="st" style="color: #20794D;">?</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)[[<span class="dv" style="color: #AD0000;">1</span>]]</span>
<span id="cb12-128">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb12-129">    lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as.character</span>(raw_headers)</span>
<span id="cb12-130">  }</span>
<span id="cb12-131"></span>
<span id="cb12-132">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">trimws</span>(lines)</span>
<span id="cb12-133">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> lines[lines <span class="sc" style="color: #5E5E5E;">!=</span> <span class="st" style="color: #20794D;">""</span>]</span>
<span id="cb12-134"></span>
<span id="cb12-135">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(lines) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-136">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-137">      <span class="at" style="color: #657422;">status_code =</span> <span class="cn" style="color: #8f5902;">NA_integer_</span>,</span>
<span id="cb12-138">      <span class="at" style="color: #657422;">protocol =</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb12-139">      <span class="at" style="color: #657422;">headers =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-140">      <span class="at" style="color: #657422;">redirects =</span> <span class="fu" style="color: #4758AB;">list</span>(),</span>
<span id="cb12-141">      <span class="at" style="color: #657422;">chain =</span> <span class="fu" style="color: #4758AB;">integer</span>()</span>
<span id="cb12-142">    ))</span>
<span id="cb12-143">  }</span>
<span id="cb12-144"></span>
<span id="cb12-145">  <span class="co" style="color: #5E5E5E;"># Identify HTTP status lines (e.g. "HTTP/1.1 301 Moved Permanently" or "HTTP/2 200")</span></span>
<span id="cb12-146">  status_indices <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">grep</span>(<span class="st" style="color: #20794D;">"^HTTP/[0-9.]+ +[0-9]{3}"</span>, lines)</span>
<span id="cb12-147"></span>
<span id="cb12-148">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(status_indices) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-149">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-150">      <span class="at" style="color: #657422;">status_code =</span> <span class="cn" style="color: #8f5902;">NA_integer_</span>,</span>
<span id="cb12-151">      <span class="at" style="color: #657422;">protocol =</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb12-152">      <span class="at" style="color: #657422;">headers =</span> <span class="fu" style="color: #4758AB;">character</span>(),</span>
<span id="cb12-153">      <span class="at" style="color: #657422;">redirects =</span> <span class="fu" style="color: #4758AB;">list</span>(),</span>
<span id="cb12-154">      <span class="at" style="color: #657422;">chain =</span> <span class="fu" style="color: #4758AB;">integer</span>()</span>
<span id="cb12-155">    ))</span>
<span id="cb12-156">  }</span>
<span id="cb12-157"></span>
<span id="cb12-158">  responses <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb12-159">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (i <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_along</span>(status_indices)) {</span>
<span id="cb12-160">    start_idx <span class="ot" style="color: #003B4F;">&lt;-</span> status_indices[i]</span>
<span id="cb12-161">    end_idx <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (i <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="fu" style="color: #4758AB;">length</span>(status_indices)) {</span>
<span id="cb12-162">      status_indices[i <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L] <span class="sc" style="color: #5E5E5E;">-</span> <span class="dv" style="color: #AD0000;">1</span>L</span>
<span id="cb12-163">    } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb12-164">      <span class="fu" style="color: #4758AB;">length</span>(lines)</span>
<span id="cb12-165">    }</span>
<span id="cb12-166">    block_lines <span class="ot" style="color: #003B4F;">&lt;-</span> lines[start_idx<span class="sc" style="color: #5E5E5E;">:</span>end_idx]</span>
<span id="cb12-167"></span>
<span id="cb12-168">    status_line <span class="ot" style="color: #003B4F;">&lt;-</span> block_lines[<span class="dv" style="color: #AD0000;">1</span>]</span>
<span id="cb12-169">    status_match <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">regexec</span>(</span>
<span id="cb12-170">      <span class="st" style="color: #20794D;">"^([A-Za-z0-9/.]+) +([0-9]{3})(?: +(.*))?$"</span>,</span>
<span id="cb12-171">      status_line</span>
<span id="cb12-172">    )</span>
<span id="cb12-173">    status_parts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">regmatches</span>(status_line, status_match)[[<span class="dv" style="color: #AD0000;">1</span>]]</span>
<span id="cb12-174"></span>
<span id="cb12-175">    proto <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(status_parts) <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">2</span>L) status_parts[<span class="dv" style="color: #AD0000;">2</span>] <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="cn" style="color: #8f5902;">NA_character_</span></span>
<span id="cb12-176">    code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(status_parts) <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">3</span>L) {</span>
<span id="cb12-177">      <span class="fu" style="color: #4758AB;">as.integer</span>(status_parts[<span class="dv" style="color: #AD0000;">3</span>])</span>
<span id="cb12-178">    } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb12-179">      <span class="cn" style="color: #8f5902;">NA_integer_</span></span>
<span id="cb12-180">    }</span>
<span id="cb12-181"></span>
<span id="cb12-182">    header_lines <span class="ot" style="color: #003B4F;">&lt;-</span> block_lines[<span class="sc" style="color: #5E5E5E;">-</span><span class="dv" style="color: #AD0000;">1</span>]</span>
<span id="cb12-183">    parsed_headers <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb12-184"></span>
<span id="cb12-185">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (h_line <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> header_lines) {</span>
<span id="cb12-186">      sep_idx <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">regexpr</span>(<span class="st" style="color: #20794D;">":"</span>, h_line, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-187">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (sep_idx <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-188">        key <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tolower</span>(<span class="fu" style="color: #4758AB;">trimws</span>(<span class="fu" style="color: #4758AB;">substr</span>(h_line, <span class="dv" style="color: #AD0000;">1</span>L, sep_idx <span class="sc" style="color: #5E5E5E;">-</span> <span class="dv" style="color: #AD0000;">1</span>L)))</span>
<span id="cb12-189">        val <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">trimws</span>(<span class="fu" style="color: #4758AB;">substr</span>(h_line, sep_idx <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L, <span class="fu" style="color: #4758AB;">nchar</span>(h_line)))</span>
<span id="cb12-190">        parsed_headers[key] <span class="ot" style="color: #003B4F;">&lt;-</span> val</span>
<span id="cb12-191">      }</span>
<span id="cb12-192">    }</span>
<span id="cb12-193"></span>
<span id="cb12-194">    responses[[<span class="fu" style="color: #4758AB;">length</span>(responses) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-195">      <span class="at" style="color: #657422;">protocol =</span> proto,</span>
<span id="cb12-196">      <span class="at" style="color: #657422;">status_code =</span> code,</span>
<span id="cb12-197">      <span class="at" style="color: #657422;">headers =</span> parsed_headers</span>
<span id="cb12-198">    )</span>
<span id="cb12-199">  }</span>
<span id="cb12-200"></span>
<span id="cb12-201">  final_resp <span class="ot" style="color: #003B4F;">&lt;-</span> responses[[<span class="fu" style="color: #4758AB;">length</span>(responses)]]</span>
<span id="cb12-202">  chain <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">vapply</span>(responses, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(r) r<span class="sc" style="color: #5E5E5E;">$</span>status_code, <span class="fu" style="color: #4758AB;">integer</span>(<span class="dv" style="color: #AD0000;">1</span>))</span>
<span id="cb12-203"></span>
<span id="cb12-204">  redirects <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb12-205">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(responses) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">1</span>L) {</span>
<span id="cb12-206">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (j <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_len</span>(<span class="fu" style="color: #4758AB;">length</span>(responses) <span class="sc" style="color: #5E5E5E;">-</span> <span class="dv" style="color: #AD0000;">1</span>L)) {</span>
<span id="cb12-207">      redirects[[j]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-208">        <span class="at" style="color: #657422;">status_code =</span> responses[[j]]<span class="sc" style="color: #5E5E5E;">$</span>status_code,</span>
<span id="cb12-209">        <span class="at" style="color: #657422;">location =</span> <span class="fu" style="color: #4758AB;">unname</span>(responses[[j]]<span class="sc" style="color: #5E5E5E;">$</span>headers[<span class="st" style="color: #20794D;">"location"</span>])</span>
<span id="cb12-210">      )</span>
<span id="cb12-211">    }</span>
<span id="cb12-212">  }</span>
<span id="cb12-213"></span>
<span id="cb12-214">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-215">    <span class="at" style="color: #657422;">status_code =</span> final_resp<span class="sc" style="color: #5E5E5E;">$</span>status_code,</span>
<span id="cb12-216">    <span class="at" style="color: #657422;">protocol =</span> final_resp<span class="sc" style="color: #5E5E5E;">$</span>protocol,</span>
<span id="cb12-217">    <span class="at" style="color: #657422;">headers =</span> final_resp<span class="sc" style="color: #5E5E5E;">$</span>headers,</span>
<span id="cb12-218">    <span class="at" style="color: #657422;">redirects =</span> redirects,</span>
<span id="cb12-219">    <span class="at" style="color: #657422;">chain =</span> chain</span>
<span id="cb12-220">  )</span>
<span id="cb12-221">}</span>
<span id="cb12-222"></span>
<span id="cb12-223"><span class="co" style="color: #5E5E5E;">#' Check HTTP headers for MIME type misclassifications</span></span>
<span id="cb12-224"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb12-225"><span class="co" style="color: #5E5E5E;">#' Flags responses where non-HTML assets (.R, .sh, .yml, extensionless scripts)</span></span>
<span id="cb12-226"><span class="co" style="color: #5E5E5E;">#' are served as text/html when compressed or requested with browser headers.</span></span>
<span id="cb12-227"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb12-228"><span class="co" style="color: #5E5E5E;">#' @param raw_headers Character vector of header lines or string.</span></span>
<span id="cb12-229"><span class="co" style="color: #5E5E5E;">#' @param url_path Optional URL or path to infer expected file type.</span></span>
<span id="cb12-230"><span class="co" style="color: #5E5E5E;">#' @return A list with valid (logical), status_code, content_type, content_encoding, nosniff, and issue.</span></span>
<span id="cb12-231">check_content_type <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(raw_headers, <span class="at" style="color: #657422;">url_path =</span> <span class="st" style="color: #20794D;">""</span>) {</span>
<span id="cb12-232">  parsed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">parse_http_headers</span>(raw_headers)</span>
<span id="cb12-233"></span>
<span id="cb12-234">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.na</span>(parsed<span class="sc" style="color: #5E5E5E;">$</span>status_code)) {</span>
<span id="cb12-235">    <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-236">      <span class="at" style="color: #657422;">valid =</span> <span class="cn" style="color: #8f5902;">FALSE</span>,</span>
<span id="cb12-237">      <span class="at" style="color: #657422;">status_code =</span> <span class="cn" style="color: #8f5902;">NA_integer_</span>,</span>
<span id="cb12-238">      <span class="at" style="color: #657422;">content_type =</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb12-239">      <span class="at" style="color: #657422;">content_encoding =</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb12-240">      <span class="at" style="color: #657422;">nosniff =</span> <span class="cn" style="color: #8f5902;">FALSE</span>,</span>
<span id="cb12-241">      <span class="at" style="color: #657422;">issue =</span> <span class="st" style="color: #20794D;">"Could not parse HTTP response headers"</span></span>
<span id="cb12-242">    ))</span>
<span id="cb12-243">  }</span>
<span id="cb12-244"></span>
<span id="cb12-245">  ct <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">unname</span>(parsed<span class="sc" style="color: #5E5E5E;">$</span>headers[<span class="st" style="color: #20794D;">"content-type"</span>])</span>
<span id="cb12-246">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.na</span>(ct)) {</span>
<span id="cb12-247">    ct <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"missing"</span></span>
<span id="cb12-248">  }</span>
<span id="cb12-249"></span>
<span id="cb12-250">  ce <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">unname</span>(parsed<span class="sc" style="color: #5E5E5E;">$</span>headers[<span class="st" style="color: #20794D;">"content-encoding"</span>])</span>
<span id="cb12-251">  nosniff_hdr <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">unname</span>(parsed<span class="sc" style="color: #5E5E5E;">$</span>headers[<span class="st" style="color: #20794D;">"x-content-type-options"</span>])</span>
<span id="cb12-252">  nosniff <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(nosniff_hdr) <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="fu" style="color: #4758AB;">tolower</span>(nosniff_hdr) <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"nosniff"</span></span>
<span id="cb12-253"></span>
<span id="cb12-254">  <span class="co" style="color: #5E5E5E;"># Detect non-HTML target from url_path</span></span>
<span id="cb12-255">  clean_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"[?#].*$"</span>, <span class="st" style="color: #20794D;">""</span>, url_path)</span>
<span id="cb12-256">  is_non_html <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">grepl</span>(</span>
<span id="cb12-257">    <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.(r|sh|bash|yml|yaml|json|csv|tsv|txt|md|qmd|rmd)$"</span>,</span>
<span id="cb12-258">    clean_path,</span>
<span id="cb12-259">    <span class="at" style="color: #657422;">ignore.case =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb12-260">  ) <span class="sc" style="color: #5E5E5E;">||</span></span>
<span id="cb12-261">    <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"/commit-msg$"</span>, clean_path)</span>
<span id="cb12-262"></span>
<span id="cb12-263">  is_served_as_html <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"text/html"</span>, ct, <span class="at" style="color: #657422;">ignore.case =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-264"></span>
<span id="cb12-265">  issue <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">""</span></span>
<span id="cb12-266">  valid <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb12-267"></span>
<span id="cb12-268">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (is_non_html <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> is_served_as_html) {</span>
<span id="cb12-269">    valid <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb12-270">    issue <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb12-271">      <span class="st" style="color: #20794D;">"Non-HTML asset (%s) was served as '%s'"</span>,</span>
<span id="cb12-272">      <span class="fu" style="color: #4758AB;">basename</span>(clean_path),</span>
<span id="cb12-273">      ct</span>
<span id="cb12-274">    )</span>
<span id="cb12-275">  }</span>
<span id="cb12-276"></span>
<span id="cb12-277">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb12-278">    <span class="at" style="color: #657422;">valid =</span> valid,</span>
<span id="cb12-279">    <span class="at" style="color: #657422;">status_code =</span> parsed<span class="sc" style="color: #5E5E5E;">$</span>status_code,</span>
<span id="cb12-280">    <span class="at" style="color: #657422;">content_type =</span> ct,</span>
<span id="cb12-281">    <span class="at" style="color: #657422;">content_encoding =</span> ce,</span>
<span id="cb12-282">    <span class="at" style="color: #657422;">nosniff =</span> nosniff,</span>
<span id="cb12-283">    <span class="at" style="color: #657422;">issue =</span> issue</span>
<span id="cb12-284">  )</span>
<span id="cb12-285">}</span>
<span id="cb12-286"></span>
<span id="cb12-287"><span class="co" style="color: #5E5E5E;"># Standalone execution</span></span>
<span id="cb12-288"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-289">  args <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">commandArgs</span>(<span class="at" style="color: #657422;">trailingOnly =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb12-290"></span>
<span id="cb12-291">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="st" style="color: #20794D;">"--help"</span> <span class="sc" style="color: #5E5E5E;">%in%</span> args <span class="sc" style="color: #5E5E5E;">||</span> <span class="st" style="color: #20794D;">"-h"</span> <span class="sc" style="color: #5E5E5E;">%in%</span> args) {</span>
<span id="cb12-292">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Usage:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-293">    <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb12-294">      <span class="st" style="color: #20794D;">"  Rscript hosting-check.R                  # Run offline verification demo</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb12-295">    )</span>
<span id="cb12-296">    <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb12-297">      <span class="st" style="color: #20794D;">"  Rscript hosting-check.R --site &lt;dir&gt;     # Scan directory index pages for relative links</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb12-298">    )</span>
<span id="cb12-299">    <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb12-300">      <span class="st" style="color: #20794D;">"  Rscript hosting-check.R --url &lt;url&gt;      # Inspect HTTP headers for target URL</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb12-301">    )</span>
<span id="cb12-302">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="st" style="color: #20794D;">"--site"</span> <span class="sc" style="color: #5E5E5E;">%in%</span> args) {</span>
<span id="cb12-303">    site_idx <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">which</span>(args <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"--site"</span>) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L</span>
<span id="cb12-304">    site_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (site_idx <span class="sc" style="color: #5E5E5E;">&lt;=</span> <span class="fu" style="color: #4758AB;">length</span>(args)) args[site_idx] <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="st" style="color: #20794D;">"_site"</span></span>
<span id="cb12-305">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Scanning rendered directory:"</span>, site_dir, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-306">    findings <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">find_relative_directory_links</span>(site_dir)</span>
<span id="cb12-307">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">nrow</span>(findings) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb12-308">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"No relative child links found in directory index pages.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-309">    } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb12-310">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb12-311">        <span class="st" style="color: #20794D;">"Found %d relative link(s) vulnerable to trailing slash removal:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb12-312">        <span class="fu" style="color: #4758AB;">nrow</span>(findings)</span>
<span id="cb12-313">      ))</span>
<span id="cb12-314">      <span class="fu" style="color: #4758AB;">print</span>(findings)</span>
<span id="cb12-315">    }</span>
<span id="cb12-316">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="st" style="color: #20794D;">"--url"</span> <span class="sc" style="color: #5E5E5E;">%in%</span> args) {</span>
<span id="cb12-317">    url_idx <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">which</span>(args <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"--url"</span>) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L</span>
<span id="cb12-318">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (url_idx <span class="sc" style="color: #5E5E5E;">&lt;=</span> <span class="fu" style="color: #4758AB;">length</span>(args)) {</span>
<span id="cb12-319">      target_url <span class="ot" style="color: #003B4F;">&lt;-</span> args[url_idx]</span>
<span id="cb12-320">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Inspecting headers for:"</span>, target_url, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-321">      curl_args <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb12-322">        <span class="st" style="color: #20794D;">"-sI"</span>,</span>
<span id="cb12-323">        <span class="st" style="color: #20794D;">"-H"</span>,</span>
<span id="cb12-324">        <span class="st" style="color: #20794D;">"Accept-Encoding: gzip, br"</span>,</span>
<span id="cb12-325">        <span class="st" style="color: #20794D;">"-H"</span>,</span>
<span id="cb12-326">        <span class="st" style="color: #20794D;">"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"</span>,</span>
<span id="cb12-327">        <span class="st" style="color: #20794D;">"--"</span>,</span>
<span id="cb12-328">        target_url</span>
<span id="cb12-329">      )</span>
<span id="cb12-330">      raw_output <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tryCatch</span>(</span>
<span id="cb12-331">        <span class="fu" style="color: #4758AB;">system2</span>(<span class="st" style="color: #20794D;">"curl"</span>, curl_args, <span class="at" style="color: #657422;">stdout =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">stderr =</span> <span class="cn" style="color: #8f5902;">FALSE</span>),</span>
<span id="cb12-332">        <span class="at" style="color: #657422;">error =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(e) <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb12-333">      )</span>
<span id="cb12-334">      res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">check_content_type</span>(raw_output, <span class="at" style="color: #657422;">url_path =</span> target_url)</span>
<span id="cb12-335">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Status Code:     "</span>, res<span class="sc" style="color: #5E5E5E;">$</span>status_code, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-336">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Content-Type:    "</span>, res<span class="sc" style="color: #5E5E5E;">$</span>content_type, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-337">      <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb12-338">        <span class="st" style="color: #20794D;">"Content-Encoding:"</span>,</span>
<span id="cb12-339">        <span class="fu" style="color: #4758AB;">ifelse</span>(<span class="fu" style="color: #4758AB;">is.na</span>(res<span class="sc" style="color: #5E5E5E;">$</span>content_encoding), <span class="st" style="color: #20794D;">"none"</span>, res<span class="sc" style="color: #5E5E5E;">$</span>content_encoding),</span>
<span id="cb12-340">        <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb12-341">      )</span>
<span id="cb12-342">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Nosniff:         "</span>, <span class="fu" style="color: #4758AB;">ifelse</span>(res<span class="sc" style="color: #5E5E5E;">$</span>nosniff, <span class="st" style="color: #20794D;">"yes"</span>, <span class="st" style="color: #20794D;">"no"</span>), <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-343">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Valid MIME:      "</span>, <span class="fu" style="color: #4758AB;">ifelse</span>(res<span class="sc" style="color: #5E5E5E;">$</span>valid, <span class="st" style="color: #20794D;">"PASS"</span>, <span class="st" style="color: #20794D;">"FAIL"</span>), <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-344">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">nzchar</span>(res<span class="sc" style="color: #5E5E5E;">$</span>issue)) {</span>
<span id="cb12-345">        <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Issue:           "</span>, res<span class="sc" style="color: #5E5E5E;">$</span>issue, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-346">      }</span>
<span id="cb12-347">    } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb12-348">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Error: --url requires a target URL argument.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-349">    }</span>
<span id="cb12-350">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb12-351">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-352">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Running offline hosting-check demonstration</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-353">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-354"></span>
<span id="cb12-355">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Step 1: Header parsing with browser compression headers</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-356">    sample_compressed_bug <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">paste</span>(</span>
<span id="cb12-357">      <span class="st" style="color: #20794D;">"HTTP/2 200"</span>,</span>
<span id="cb12-358">      <span class="st" style="color: #20794D;">"content-type: text/html; charset=UTF-8"</span>,</span>
<span id="cb12-359">      <span class="st" style="color: #20794D;">"content-encoding: gzip"</span>,</span>
<span id="cb12-360">      <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb12-361">    )</span>
<span id="cb12-362">    res_bug <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">check_content_type</span>(</span>
<span id="cb12-363">      sample_compressed_bug,</span>
<span id="cb12-364">      <span class="at" style="color: #657422;">url_path =</span> <span class="st" style="color: #20794D;">"scripts/ars-demo.R"</span></span>
<span id="cb12-365">    )</span>
<span id="cb12-366">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Bug reproduction (unconfigured CDN response):</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-367">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Asset:   scripts/ars-demo.R</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-368">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Valid:  "</span>, res_bug<span class="sc" style="color: #5E5E5E;">$</span>valid, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-369">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Type:   "</span>, res_bug<span class="sc" style="color: #5E5E5E;">$</span>content_type, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-370">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Issue:  "</span>, res_bug<span class="sc" style="color: #5E5E5E;">$</span>issue, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-371"></span>
<span id="cb12-372">    sample_fixed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">paste</span>(</span>
<span id="cb12-373">      <span class="st" style="color: #20794D;">"HTTP/2 200"</span>,</span>
<span id="cb12-374">      <span class="st" style="color: #20794D;">"content-type: text/plain; charset=utf-8"</span>,</span>
<span id="cb12-375">      <span class="st" style="color: #20794D;">"content-encoding: gzip"</span>,</span>
<span id="cb12-376">      <span class="st" style="color: #20794D;">"x-content-type-options: nosniff"</span>,</span>
<span id="cb12-377">      <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb12-378">    )</span>
<span id="cb12-379">    res_fixed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">check_content_type</span>(</span>
<span id="cb12-380">      sample_fixed,</span>
<span id="cb12-381">      <span class="at" style="color: #657422;">url_path =</span> <span class="st" style="color: #20794D;">"scripts/ars-demo.R"</span></span>
<span id="cb12-382">    )</span>
<span id="cb12-383">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Fixed configuration (explicit headers):</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-384">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Asset:   scripts/ars-demo.R</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-385">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Valid:  "</span>, res_fixed<span class="sc" style="color: #5E5E5E;">$</span>valid, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-386">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Type:   "</span>, res_fixed<span class="sc" style="color: #5E5E5E;">$</span>content_type, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-387">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"  Nosniff:"</span>, res_fixed<span class="sc" style="color: #5E5E5E;">$</span>nosniff, <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb12-388">  }</span>
<span id="cb12-389">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Web standards and specifications</strong></p>
<ul>
<li><strong>RFC 3986 (Uniform Resource Identifier: Generic Syntax):</strong> Section 5.2.3 (“Merge Paths”), T. Berners-Lee, R. Fielding, L. Masinter, January 2005. <a href="https://www.rfc-editor.org/rfc/rfc3986">rfc-editor.org/rfc/rfc3986</a></li>
<li><strong>WHATWG URL Standard:</strong> Section 4.4, URL parsing and relative reference resolution. <a href="https://url.spec.whatwg.org/">url.spec.whatwg.org</a></li>
<li><strong>MDN Web Docs:</strong> <code>X-Content-Type-Options</code>. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options">developer.mozilla.org</a></li>
</ul>
<p><strong>Hosting documentation</strong></p>
<ul>
<li><strong>Firebase Hosting:</strong> Full configuration guide (<code>cleanUrls</code>, <code>trailingSlash</code>, <code>redirects</code>, and <code>headers</code>). <a href="https://firebase.google.com/docs/hosting/full-config">firebase.google.com/docs/hosting/full-config</a></li>
<li><strong>Netlify:</strong> <a href="https://docs.netlify.com/manage/routing/redirects/redirect-options/#trailing-slash">Pretty URLs and trailing slash behavior</a> and <a href="https://docs.netlify.com/manage/routing/headers/">custom headers</a>.</li>
<li><strong>Cloudflare Pages:</strong> <a href="https://developers.cloudflare.com/pages/configuration/serving-pages/">Serving Pages</a> and <a href="https://developers.cloudflare.com/pages/configuration/headers/">custom headers</a>.</li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>withr</strong>: <a href="https://withr.r-lib.org/">withr.r-lib.org</a></li>
</ul>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 16 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/companion-code/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 15</span><span class="site-related-card__title">Companion code: show it, link it, test it</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/index.html" class="site-link-row" title="Validate internal links across rendered documentation in CI using offline link scanners to block broken references before release."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Catch broken links before your readers do</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/series-registry-quarto/index.html" class="site-link-row" title="Model series and related posts as structured data with a YAML registry and a Pandoc Lua filter, guarded by testthat so missing references fail in CI."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Content as data: a series registry for a Quarto blog</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Quarto</category>
  <category>CI/CD</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/hosted-site-pitfalls/</guid>
  <pubDate>Sat, 26 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>QC and double programming with {diffdf}</title>
  <link>https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Unit tests compare output with a known answer (<code>expect_equal(add(2, 2), 4)</code>). A whole analysis dataset or summary table has no such oracle: nobody can hand-calculate every treatment-emergent flag, baseline value or imputed date across a study in advance.</p>
<p>Clinical reporting’s answer is <strong>independent double programming</strong>:</p>
<pre class="text"><code>Raw / SDTM Data ──┬──&gt; [Primary Programmer]   ──&gt; Production ADaM / TFL
                  │           │
                  │   Independent Cognition
                  │           │
                  └──&gt; [Validation Programmer] ──&gt; QC ADaM / TFL
                              │
                              ▼
                  [Programmatic Reconciliation] ──&gt; Clean Match</code></pre>
<p>Two programmers independently write separate code from the written Statistical Analysis Plan (SAP) and dataset specifications. Neither programmer inspects the other’s code. Both run their programs against the same source data, and an automated comparison tool reconciles the outputs record by record.</p>
<section id="what-independent-programming-catches" class="level3">
<h3 class="anchored" data-anchor-id="what-independent-programming-catches">What independent programming catches</h3>
<p>Reviewing your own code tends to confirm your own assumptions; a second, independent implementation doesn’t share them. It catches:</p>
<ol type="1">
<li><strong>Specification ambiguity</strong>: If an SAP states that baseline is the “last non-missing assessment prior to study treatment”, does an assessment on Day 1 with no recorded timestamp count as baseline? Two independent programmers will make distinct interpretations. When their outputs diverge, the comparison surfaces the ambiguous specification before regulatory filing.</li>
<li><strong>Boundary and off-by-one errors</strong>: Subtle conditional logic errors, such as using <code>AGE &lt;= 65</code> instead of <code>AGE &lt; 65</code>, or computing study day without accounting for the absence of Day 0 in CDISC standards.</li>
<li><strong>Filtering and language quirks</strong>: How missing values behave under filtering. In SAS, a missing numeric value is treated as smaller than any number, so <code>where AGE &lt; 65</code> keeps missing ages. In R, <code>NA &lt; 65</code> is <code>NA</code>: <code>dplyr::filter()</code> drops those rows, while <code>df[df$AGE &lt; 65, ]</code> returns a row of <code>NA</code>s for each one. Independent implementations uncover these divergent assumptions.</li>
<li><strong>Transcription errors</strong>: Miskeyed dictionary codes, cutoff values, or visit numbers.</li>
</ol>
</section>
<section id="the-limits-of-double-programming" class="level3">
<h3 class="anchored" data-anchor-id="the-limits-of-double-programming">The limits of double programming</h3>
<p>Double programming is valuable, but it is not infallible. In a well-known 1986 experiment, Knight and Leveson had many programmers implement the same specification independently and found that their failures were correlated: independent programmers tend to trip over the same hard cases.</p>
<p>If the written specification contains an error—such as an incorrect formula or wrong population cutoff—both programmers will implement that error. The comparison will report no differences, creating false confidence. Double programming verifies conformance to interpretation, not clinical validity.</p>
<p>It also costs a second implementation for every output, so many teams use <strong>risk-based QC levels</strong>, spending the most effort where an error would matter most. A typical (illustrative) scheme:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>QC Level</th>
<th>Methodology</th>
<th>Scope</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Level 1: Self-Check &amp; Log Review</strong></td>
<td>Primary programmer verifies execution logs (no warnings, errors, or unexpected conversions) and runs automated linters.</td>
<td>Exploratory tables, internal review dashboards, preliminary slides.</td>
</tr>
<tr class="even">
<td><strong>Level 2: Independent Code Review</strong></td>
<td>A second programmer inspects the code against the SAP and performs spot checks on intermediate datasets.</td>
<td>Secondary safety listings, standard demographic tables where the underlying ADSL dataset is double-programmed.</td>
</tr>
<tr class="odd">
<td><strong>Level 3: Independent Double Programming</strong></td>
<td>Two independent programs and automated tabular diffing.</td>
<td>Primary and key secondary efficacy endpoints, core safety ADaM datasets (<code>ADSL</code>, <code>ADAE</code>), pivotal Clinical Study Report summary tables.</td>
</tr>
</tbody>
</table>
</div>
</section>
</section>
<section id="the-web-analogue" class="level2">
<h2 class="anchored" data-anchor-id="the-web-analogue">The web analogue</h2>
<p>Web teams use <strong>golden-file</strong> (snapshot) tests: generate an output file and diff it against an approved reference.</p>
<p>A text or byte diff (<code>git diff</code>, <code>diff</code>, checksums) is the wrong tool for data frames:</p>
<ul>
<li><strong>Row and column order</strong>: the same records in a different order are the same data, but not the same bytes.</li>
<li><strong>Floating-point noise</strong>: summing in a different order can change a value in the 16th digit.</li>
<li><strong>Attributes</strong>: labels, factor levels and data frame classes (<code>tbl_df</code> versus <code>data.frame</code>) don’t show up in a text diff at all.</li>
</ul>
<p>What’s needed is a comparator that matches records by key and variables by name, compares numbers within a tolerance, checks attributes, and points to the exact cells that differ.</p>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In legacy workflows, tabular reconciliation was performed in SAS using <code>PROC COMPARE</code>. In the modern R clinical ecosystem, the primary tool for semantic data frame comparison is <a href="https://cran.r-project.org/package=diffdf"><code>{diffdf}</code></a>.</p>
<p><code>{diffdf}</code> compares two data frames and reports differences in columns, classes, attributes (such as variable labels) and values.</p>
<section id="the-core-function-diffdf" class="level3">
<h3 class="anchored" data-anchor-id="the-core-function-diffdf">The core function: <code>diffdf()</code></h3>
<p>The primary comparison function is <code>diffdf::diffdf()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">library</span>(diffdf)</span>
<span id="cb2-2"></span>
<span id="cb2-3">dm <span class="ot" style="color: #003B4F;">&lt;-</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>dm</span>
<span id="cb2-4"></span>
<span id="cb2-5"><span class="co" style="color: #5E5E5E;"># Primary derivation: pooled age group with cutoff at 65</span></span>
<span id="cb2-6">prod <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb2-7">  <span class="at" style="color: #657422;">STUDYID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>STUDYID,</span>
<span id="cb2-8">  <span class="at" style="color: #657422;">USUBJID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>USUBJID,</span>
<span id="cb2-9">  <span class="at" style="color: #657422;">AGE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>AGE,</span>
<span id="cb2-10">  <span class="at" style="color: #657422;">AGEGR1 =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(dm<span class="sc" style="color: #5E5E5E;">$</span>AGE <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span>, <span class="st" style="color: #20794D;">"&lt;65"</span>, <span class="st" style="color: #20794D;">"&gt;=65"</span>),</span>
<span id="cb2-11">  <span class="at" style="color: #657422;">TRT01A =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>ACTARM,</span>
<span id="cb2-12">  <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb2-13">)</span>
<span id="cb2-14"><span class="fu" style="color: #4758AB;">attr</span>(prod<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Pooled Age Group 1"</span></span>
<span id="cb2-15"></span>
<span id="cb2-16"><span class="co" style="color: #5E5E5E;"># Validation derivation: planted boundary error (&lt;= 65 instead of &lt; 65)</span></span>
<span id="cb2-17">qc_buggy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb2-18">  <span class="at" style="color: #657422;">STUDYID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>STUDYID,</span>
<span id="cb2-19">  <span class="at" style="color: #657422;">USUBJID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>USUBJID,</span>
<span id="cb2-20">  <span class="at" style="color: #657422;">AGE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>AGE,</span>
<span id="cb2-21">  <span class="at" style="color: #657422;">AGEGR1 =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(dm<span class="sc" style="color: #5E5E5E;">$</span>AGE <span class="sc" style="color: #5E5E5E;">&lt;=</span> <span class="dv" style="color: #AD0000;">65</span>, <span class="st" style="color: #20794D;">"&lt;65"</span>, <span class="st" style="color: #20794D;">"&gt;=65"</span>),</span>
<span id="cb2-22">  <span class="at" style="color: #657422;">TRT01A =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>ACTARM,</span>
<span id="cb2-23">  <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb2-24">)</span>
<span id="cb2-25"><span class="fu" style="color: #4758AB;">attr</span>(qc_buggy<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Pooled Age Group 1"</span></span></code></pre></div></div>
<p>To compare the datasets, provide the two data frames and define the unique record identifier using <code>keys</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">diff_res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">diffdf</span>(</span>
<span id="cb3-2">  <span class="at" style="color: #657422;">base =</span> prod,</span>
<span id="cb3-3">  <span class="at" style="color: #657422;">compare =</span> qc_buggy,</span>
<span id="cb3-4">  <span class="at" style="color: #657422;">keys =</span> <span class="st" style="color: #20794D;">"USUBJID"</span>,</span>
<span id="cb3-5">  <span class="at" style="color: #657422;">suppress_warnings =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb3-6">)</span>
<span id="cb3-7"></span>
<span id="cb3-8"><span class="fu" style="color: #4758AB;">diffdf_has_issues</span>(diff_res)</span></code></pre></div></div>
<p>Running <code>diffdf_has_issues(diff_res)</code> returns <code>TRUE</code>. If warnings are not suppressed, <code>diffdf()</code> also emits a warning summarizing the findings.</p>
</section>
<section id="key-arguments-in-diffdf" class="level3">
<h3 class="anchored" data-anchor-id="key-arguments-in-diffdf">Key arguments in <code>diffdf()</code></h3>
<p>The function provides explicit parameters to control how strictly differences are evaluated:</p>
<ul>
<li><strong><code>keys</code></strong> (default <code>NULL</code>): A character vector naming the variables that uniquely identify each observation (for example, <code>"USUBJID"</code> in ADSL, or <code>c("USUBJID", "PARAMCD", "AVISITN")</code> in BDS datasets). If <code>keys</code> is omitted, <code>diffdf()</code> falls back to comparing by row index. If keys contain duplicate values in either dataset, <code>diffdf()</code> stops with an informative error.</li>
<li><strong><code>tolerance</code></strong> (default <code>sqrt(.Machine$double.eps)</code> ≈ <code>1.49e-08</code>): The numeric comparison threshold. Two numbers count as equal if their absolute difference is within <code>tolerance</code> (divided by <code>scale</code> first, if you set one).</li>
<li><strong><code>scale</code></strong> (default <code>NULL</code>): an optional divisor, for relative rather than absolute differences.</li>
<li><strong><code>strict_numeric</code></strong> (default <code>TRUE</code>): If <code>TRUE</code>, an <code>integer</code> column compared with a <code>double</code> one is reported as a class difference (in <code>VarClassDiffs</code>). If <code>FALSE</code>, integers are cast to double for comparison. Key variables are never cast.</li>
<li><strong><code>strict_factor</code></strong> (default <code>TRUE</code>): If <code>TRUE</code>, comparing a <code>factor</code> to a <code>character</code> column is flagged as a class discrepancy. If <code>FALSE</code>, factors are cast to characters for value comparison.</li>
<li><strong><code>check_column_order</code></strong> (default <code>FALSE</code>): When set to <code>TRUE</code>, verifies that matching columns appear in the exact same positional sequence.</li>
<li><strong><code>check_df_class</code></strong> (default <code>FALSE</code>): When set to <code>TRUE</code>, flags differences between data frame class tags (such as a tibble versus a base <code>data.frame</code>).</li>
<li><strong><code>suppress_warnings</code></strong> (default <code>FALSE</code>): when <code>TRUE</code>, <code>diffdf()</code> doesn’t also emit a warning when it finds differences (the report is unchanged).</li>
</ul>
</section>
<section id="reading-the-report-and-isolating-issue-rows" class="level3">
<h3 class="anchored" data-anchor-id="reading-the-report-and-isolating-issue-rows">Reading the report and isolating issue rows</h3>
<p>Printing <code>diff_res</code> outputs a structured comparison report:</p>
<pre class="text"><code>Differences found between the objects!

Summary of BASE and COMPARE
  ====================================
    PROPERTY      BASE        COMP    
  ------------------------------------
      Name        prod      qc_buggy  
     Class     data.frame  data.frame 
    Rows(#)       306         306     
   Columns(#)      5           5      
  ------------------------------------

Not all Values Compared Equal
  =============================
   Variable  No of Differences 
  -----------------------------
    AGEGR1           4         
  -----------------------------

  ======================================
   VARIABLE    USUBJID    BASE  COMPARE 
  --------------------------------------
    AGEGR1   01-707-1206  &gt;=65    &lt;65   
    AGEGR1   01-709-1309  &gt;=65    &lt;65   
    AGEGR1   01-715-1107  &gt;=65    &lt;65   
    AGEGR1   01-715-1319  &gt;=65    &lt;65   
  --------------------------------------</code></pre>
<p>The report identifies that four subjects differed in <code>AGEGR1</code>.</p>
<p>To programmatically inspect the problem rows in the original data, use <code>diffdf::diffdf_issuerows()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">issue_rows <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">diffdf_issuerows</span>(prod, diff_res, <span class="at" style="color: #657422;">vars =</span> <span class="st" style="color: #20794D;">"AGEGR1"</span>)</span>
<span id="cb5-2">issue_rows[, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"USUBJID"</span>, <span class="st" style="color: #20794D;">"AGE"</span>, <span class="st" style="color: #20794D;">"AGEGR1"</span>, <span class="st" style="color: #20794D;">"TRT01A"</span>)]</span></code></pre></div></div>
<pre class="text"><code>      USUBJID AGE AGEGR1               TRT01A
1 01-707-1206  65   &gt;=65              Placebo
2 01-709-1309  65   &gt;=65 Xanomeline High Dose
3 01-715-1107  65   &gt;=65  Xanomeline Low Dose
4 01-715-1319  65   &gt;=65 Xanomeline High Dose</code></pre>
<p>Every differing row has <code>AGE == 65</code>. The QC programmer implemented <code>&lt;= 65</code>, whereas the production derivation implemented <code>&lt; 65</code>.</p>
<p>Once the programmers review the specification and correct the QC derivation, the comparison runs clean:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">qc_clean <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb7-2">  <span class="at" style="color: #657422;">STUDYID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>STUDYID,</span>
<span id="cb7-3">  <span class="at" style="color: #657422;">USUBJID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>USUBJID,</span>
<span id="cb7-4">  <span class="at" style="color: #657422;">AGE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>AGE,</span>
<span id="cb7-5">  <span class="at" style="color: #657422;">AGEGR1 =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(dm<span class="sc" style="color: #5E5E5E;">$</span>AGE <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span>, <span class="st" style="color: #20794D;">"&lt;65"</span>, <span class="st" style="color: #20794D;">"&gt;=65"</span>),</span>
<span id="cb7-6">  <span class="at" style="color: #657422;">TRT01A =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>ACTARM,</span>
<span id="cb7-7">  <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb7-8">)</span>
<span id="cb7-9"><span class="fu" style="color: #4758AB;">attr</span>(qc_clean<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Pooled Age Group 1"</span></span>
<span id="cb7-10"></span>
<span id="cb7-11">diff_clean <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">diffdf</span>(</span>
<span id="cb7-12">  <span class="at" style="color: #657422;">base =</span> prod,</span>
<span id="cb7-13">  <span class="at" style="color: #657422;">compare =</span> qc_clean,</span>
<span id="cb7-14">  <span class="at" style="color: #657422;">keys =</span> <span class="st" style="color: #20794D;">"USUBJID"</span>,</span>
<span id="cb7-15">  <span class="at" style="color: #657422;">suppress_warnings =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb7-16">)</span>
<span id="cb7-17"></span>
<span id="cb7-18"><span class="fu" style="color: #4758AB;">diffdf_has_issues</span>(diff_clean)</span></code></pre></div></div>
<p><code>diffdf_has_issues(diff_clean)</code> returns <code>FALSE</code>, and printing <code>diff_clean</code> outputs <code>No issues were found!</code>.</p>
<p>The companion script <a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/scripts/qc-demo.R">scripts/qc-demo.R</a> runs the same two rounds. Its datasets also carry <code>SEX</code> and <code>RACE</code>, so its printed summary shows seven columns. Note that <code>dm</code> holds all 306 subjects, including screen failures; the ARD example below uses the 254-subject safety population from ADSL.</p>
</section>
<section id="what-to-agree-before-qc-starts" class="level3">
<h3 class="anchored" data-anchor-id="what-to-agree-before-qc-starts">What to agree before QC starts</h3>
<p>Agree these before either programmer writes code, so the comparison finds logic differences rather than formatting ones:</p>
<ol type="1">
<li><strong>Frozen specification version</strong>: Lock the exact commit or version of the SAP, mock table shells, and dataset specifications.</li>
<li><strong>Primary keys</strong>: Agree on the natural record identifiers for each dataset domain. Without keys, <code>diffdf()</code> must fall back to row indices, meaning a single extra row will cascade into differences across the entire dataset.</li>
<li><strong>Calculation precision vs display rounding</strong>: Keep derived variables unrounded as double-precision numbers in analysis datasets. Reserve rounding for the display layer. Base R’s <code>round()</code> sends a 5 to the even digit (IEC 60559: <code>round(0.5)</code> is 0, <code>round(2.5)</code> is 2), while SAS <code>ROUND</code> rounds halves away from zero, so agree on explicit rounding helpers when the two programs use different languages.</li>
<li><strong>Tolerance parameters</strong>: For continuous statistical outputs, agree on a numerical tolerance (for example <code>1e-6</code>) to absorb floating-point representation differences.</li>
</ol>
</section>
<section id="comparing-analysis-results-data-as-data" class="level3">
<h3 class="anchored" data-anchor-id="comparing-analysis-results-data-as-data">Comparing Analysis Results Data as data</h3>
<p>Earlier in this series, <a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html">Analysis Results Data in R with {cards} and {cardx}</a> explored how to decouple statistical calculations from layout rendering using <code>{cards}</code>.</p>
<p>Diffing rendered RTF or PDF tables as text produces false alarms from layout. Compare the Analysis Results Data (ARD) behind them instead:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="fu" style="color: #4758AB;">library</span>(cards)</span>
<span id="cb8-2"></span>
<span id="cb8-3">adsl_sub <span class="ot" style="color: #003B4F;">&lt;-</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl[pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl<span class="sc" style="color: #5E5E5E;">$</span>SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>, ]</span>
<span id="cb8-4"></span>
<span id="cb8-5">ard_primary <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_continuous</span>(adsl_sub, <span class="at" style="color: #657422;">variables =</span> <span class="st" style="color: #20794D;">"AGE"</span>, <span class="at" style="color: #657422;">by =</span> <span class="st" style="color: #20794D;">"TRT01A"</span>)</span>
<span id="cb8-6">ard_qc <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_continuous</span>(adsl_sub, <span class="at" style="color: #657422;">variables =</span> <span class="st" style="color: #20794D;">"AGE"</span>, <span class="at" style="color: #657422;">by =</span> <span class="st" style="color: #20794D;">"TRT01A"</span>)</span>
<span id="cb8-7"></span>
<span id="cb8-8"><span class="co" style="color: #5E5E5E;"># Flatten list-columns into atomic vectors for diffdf</span></span>
<span id="cb8-9">flatten_ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(ard) {</span>
<span id="cb8-10">  df <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as.data.frame</span>(ard)</span>
<span id="cb8-11">  <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb8-12">    <span class="at" style="color: #657422;">variable =</span> df<span class="sc" style="color: #5E5E5E;">$</span>variable,</span>
<span id="cb8-13">    <span class="at" style="color: #657422;">stat_name =</span> df<span class="sc" style="color: #5E5E5E;">$</span>stat_name,</span>
<span id="cb8-14">    <span class="at" style="color: #657422;">arm =</span> <span class="fu" style="color: #4758AB;">vapply</span>(df<span class="sc" style="color: #5E5E5E;">$</span>group1_level, as.character, <span class="fu" style="color: #4758AB;">character</span>(<span class="dv" style="color: #AD0000;">1</span>)),</span>
<span id="cb8-15">    <span class="at" style="color: #657422;">stat =</span> <span class="fu" style="color: #4758AB;">vapply</span>(df<span class="sc" style="color: #5E5E5E;">$</span>stat, as.numeric, <span class="fu" style="color: #4758AB;">numeric</span>(<span class="dv" style="color: #AD0000;">1</span>)),</span>
<span id="cb8-16">    <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb8-17">  )</span>
<span id="cb8-18">}</span>
<span id="cb8-19"></span>
<span id="cb8-20">ard_p_flat <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">flatten_ard</span>(ard_primary)</span>
<span id="cb8-21">ard_q_flat <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">flatten_ard</span>(ard_qc)</span>
<span id="cb8-22"></span>
<span id="cb8-23">ard_diff <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">diffdf</span>(</span>
<span id="cb8-24">  <span class="at" style="color: #657422;">base =</span> ard_p_flat,</span>
<span id="cb8-25">  <span class="at" style="color: #657422;">compare =</span> ard_q_flat,</span>
<span id="cb8-26">  <span class="at" style="color: #657422;">keys =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"variable"</span>, <span class="st" style="color: #20794D;">"stat_name"</span>, <span class="st" style="color: #20794D;">"arm"</span>),</span>
<span id="cb8-27">  <span class="at" style="color: #657422;">tolerance =</span> <span class="fl" style="color: #AD0000;">1e-6</span>,</span>
<span id="cb8-28">  <span class="at" style="color: #657422;">suppress_warnings =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb8-29">)</span>
<span id="cb8-30"></span>
<span id="cb8-31"><span class="fu" style="color: #4758AB;">diffdf_has_issues</span>(ard_diff)</span></code></pre></div></div>
<p><code>{cards}</code> objects store values in list-columns (<code>stat</code>, <code>group1_level</code>). Because <code>diffdf()</code> natively supports atomic vectors (<code>numeric</code>, <code>character</code>, <code>logical</code>), list-columns should be flattened or formatted before running <code>diffdf()</code>. Alternatively, deep object comparison tools such as <code>waldo::compare()</code> can compare nested list structures directly.</p>
<p>Once the underlying ARD compares with no differences, presentation engines (<a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html"><code>{rtables}</code></a>, <code>{tfrmt}</code>, or <code>{gt}</code>) can render the numbers into CSR documents without recalculating metrics.</p>
</section>
<section id="documenting-qc-findings" class="level3">
<h3 class="anchored" data-anchor-id="documenting-qc-findings">Documenting QC findings</h3>
<p>Keep QC reviewable:</p>
<ul>
<li><strong>Run logs and diff records</strong>: Save the text output of <code>diffdf()</code> alongside the QC program execution logs in the study directory or analysis pipeline artifact repository.</li>
<li><strong>Issue tracking</strong>: When a discrepancy occurs, document whether the root cause was a primary programming defect, a validation defect, or a specification ambiguity requiring SAP clarification.</li>
<li><strong>Traceability</strong>: keep the QC programs and the commits they ran against with the study records, so anyone can re-run a comparison later.</li>
</ul>
</section>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/scripts/qc-demo.R">View <code>qc-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/scripts/qc-demo.R" download="qc-demo.R">Download</a></p>
<p>Compares independent primary and QC derivations of ADSL variables using <code>{diffdf}</code>, demonstrating both an issue-flagged run with a planted defect and a clean comparison. Requires <code>{diffdf}</code> and <code>{pharmaversesdtm}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>qc-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="co" style="color: #5E5E5E;"># qc-demo.R</span></span>
<span id="cb9-2"><span class="co" style="color: #5E5E5E;"># Independent double-programming demo comparing two derivations with {diffdf}.</span></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;"># Run with:</span></span>
<span id="cb9-5"><span class="co" style="color: #5E5E5E;">#   Rscript qc-demo.R</span></span>
<span id="cb9-6"></span>
<span id="cb9-7"><span class="fu" style="color: #4758AB;">suppressPackageStartupMessages</span>({</span>
<span id="cb9-8">  <span class="fu" style="color: #4758AB;">library</span>(diffdf)</span>
<span id="cb9-9">})</span>
<span id="cb9-10"></span>
<span id="cb9-11"><span class="co" style="color: #5E5E5E;"># Production derivation of a minimal ADSL-like dataset from SDTM DM.</span></span>
<span id="cb9-12">derive_adsl_prod <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">dm =</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>dm) {</span>
<span id="cb9-13">  df <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb9-14">    <span class="at" style="color: #657422;">STUDYID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>STUDYID,</span>
<span id="cb9-15">    <span class="at" style="color: #657422;">USUBJID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>USUBJID,</span>
<span id="cb9-16">    <span class="at" style="color: #657422;">AGE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>AGE,</span>
<span id="cb9-17">    <span class="at" style="color: #657422;">AGEGR1 =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(dm<span class="sc" style="color: #5E5E5E;">$</span>AGE <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span>, <span class="st" style="color: #20794D;">"&lt;65"</span>, <span class="st" style="color: #20794D;">"&gt;=65"</span>),</span>
<span id="cb9-18">    <span class="at" style="color: #657422;">SEX =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>SEX,</span>
<span id="cb9-19">    <span class="at" style="color: #657422;">RACE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>RACE,</span>
<span id="cb9-20">    <span class="at" style="color: #657422;">TRT01A =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>ACTARM,</span>
<span id="cb9-21">    <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb9-22">  )</span>
<span id="cb9-23">  <span class="fu" style="color: #4758AB;">attr</span>(df<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Pooled Age Group 1"</span></span>
<span id="cb9-24">  <span class="fu" style="color: #4758AB;">attr</span>(df<span class="sc" style="color: #5E5E5E;">$</span>TRT01A, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Actual Treatment Arm"</span></span>
<span id="cb9-25">  df</span>
<span id="cb9-26">}</span>
<span id="cb9-27"></span>
<span id="cb9-28"><span class="co" style="color: #5E5E5E;"># QC derivation with a planted boundary discrepancy (&lt;= 65 vs &lt; 65).</span></span>
<span id="cb9-29">derive_adsl_qc_buggy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">dm =</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>dm) {</span>
<span id="cb9-30">  df <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb9-31">    <span class="at" style="color: #657422;">STUDYID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>STUDYID,</span>
<span id="cb9-32">    <span class="at" style="color: #657422;">USUBJID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>USUBJID,</span>
<span id="cb9-33">    <span class="at" style="color: #657422;">AGE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>AGE,</span>
<span id="cb9-34">    <span class="at" style="color: #657422;">AGEGR1 =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(dm<span class="sc" style="color: #5E5E5E;">$</span>AGE <span class="sc" style="color: #5E5E5E;">&lt;=</span> <span class="dv" style="color: #AD0000;">65</span>, <span class="st" style="color: #20794D;">"&lt;65"</span>, <span class="st" style="color: #20794D;">"&gt;=65"</span>),</span>
<span id="cb9-35">    <span class="at" style="color: #657422;">SEX =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>SEX,</span>
<span id="cb9-36">    <span class="at" style="color: #657422;">RACE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>RACE,</span>
<span id="cb9-37">    <span class="at" style="color: #657422;">TRT01A =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>ACTARM,</span>
<span id="cb9-38">    <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb9-39">  )</span>
<span id="cb9-40">  <span class="fu" style="color: #4758AB;">attr</span>(df<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Pooled Age Group 1"</span></span>
<span id="cb9-41">  <span class="fu" style="color: #4758AB;">attr</span>(df<span class="sc" style="color: #5E5E5E;">$</span>TRT01A, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Actual Treatment Arm"</span></span>
<span id="cb9-42">  df</span>
<span id="cb9-43">}</span>
<span id="cb9-44"></span>
<span id="cb9-45"><span class="co" style="color: #5E5E5E;"># Fixed QC derivation resolving the discrepancy to match the specification.</span></span>
<span id="cb9-46">derive_adsl_qc_clean <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">dm =</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>dm) {</span>
<span id="cb9-47">  df <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb9-48">    <span class="at" style="color: #657422;">STUDYID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>STUDYID,</span>
<span id="cb9-49">    <span class="at" style="color: #657422;">USUBJID =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>USUBJID,</span>
<span id="cb9-50">    <span class="at" style="color: #657422;">AGE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>AGE,</span>
<span id="cb9-51">    <span class="at" style="color: #657422;">AGEGR1 =</span> <span class="fu" style="color: #4758AB;">ifelse</span>(dm<span class="sc" style="color: #5E5E5E;">$</span>AGE <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span>, <span class="st" style="color: #20794D;">"&lt;65"</span>, <span class="st" style="color: #20794D;">"&gt;=65"</span>),</span>
<span id="cb9-52">    <span class="at" style="color: #657422;">SEX =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>SEX,</span>
<span id="cb9-53">    <span class="at" style="color: #657422;">RACE =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>RACE,</span>
<span id="cb9-54">    <span class="at" style="color: #657422;">TRT01A =</span> dm<span class="sc" style="color: #5E5E5E;">$</span>ACTARM,</span>
<span id="cb9-55">    <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb9-56">  )</span>
<span id="cb9-57">  <span class="fu" style="color: #4758AB;">attr</span>(df<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Pooled Age Group 1"</span></span>
<span id="cb9-58">  <span class="fu" style="color: #4758AB;">attr</span>(df<span class="sc" style="color: #5E5E5E;">$</span>TRT01A, <span class="st" style="color: #20794D;">"label"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"Actual Treatment Arm"</span></span>
<span id="cb9-59">  df</span>
<span id="cb9-60">}</span>
<span id="cb9-61"></span>
<span id="cb9-62"><span class="co" style="color: #5E5E5E;"># Reconcile primary and QC datasets using diffdf keyed by USUBJID.</span></span>
<span id="cb9-63">compare_adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb9-64">  base,</span>
<span id="cb9-65">  compare,</span>
<span id="cb9-66">  <span class="at" style="color: #657422;">keys =</span> <span class="st" style="color: #20794D;">"USUBJID"</span>,</span>
<span id="cb9-67">  <span class="at" style="color: #657422;">tolerance =</span> <span class="fu" style="color: #4758AB;">sqrt</span>(.Machine<span class="sc" style="color: #5E5E5E;">$</span>double.eps)</span>
<span id="cb9-68">) {</span>
<span id="cb9-69">  <span class="fu" style="color: #4758AB;">diffdf</span>(</span>
<span id="cb9-70">    <span class="at" style="color: #657422;">base =</span> base,</span>
<span id="cb9-71">    <span class="at" style="color: #657422;">compare =</span> compare,</span>
<span id="cb9-72">    <span class="at" style="color: #657422;">keys =</span> keys,</span>
<span id="cb9-73">    <span class="at" style="color: #657422;">suppress_warnings =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb9-74">    <span class="at" style="color: #657422;">tolerance =</span> tolerance</span>
<span id="cb9-75">  )</span>
<span id="cb9-76">}</span>
<span id="cb9-77"></span>
<span id="cb9-78"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb9-79">  dm <span class="ot" style="color: #003B4F;">&lt;-</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>dm</span>
<span id="cb9-80">  prod <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">derive_adsl_prod</span>(dm)</span>
<span id="cb9-81">  qc_buggy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">derive_adsl_qc_buggy</span>(dm)</span>
<span id="cb9-82">  qc_clean <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">derive_adsl_qc_clean</span>(dm)</span>
<span id="cb9-83"></span>
<span id="cb9-84">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=== Round 1: Primary vs QC with Planted Boundary Bug ===</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb9-85">  diff_round1 <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">compare_adsl</span>(prod, qc_buggy)</span>
<span id="cb9-86">  <span class="fu" style="color: #4758AB;">print</span>(diff_round1)</span>
<span id="cb9-87">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Has issues: %s</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">"</span>, <span class="fu" style="color: #4758AB;">diffdf_has_issues</span>(diff_round1)))</span>
<span id="cb9-88"></span>
<span id="cb9-89">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Issue rows subset from production dataset:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb9-90">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">diffdf_issuerows</span>(prod, diff_round1, <span class="at" style="color: #657422;">vars =</span> <span class="st" style="color: #20794D;">"AGEGR1"</span>))</span>
<span id="cb9-91">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb9-92"></span>
<span id="cb9-93">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=== Round 2: Primary vs Fixed QC ===</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb9-94">  diff_round2 <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">compare_adsl</span>(prod, qc_clean)</span>
<span id="cb9-95">  <span class="fu" style="color: #4758AB;">print</span>(diff_round2)</span>
<span id="cb9-96">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Has issues: %s</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, <span class="fu" style="color: #4758AB;">diffdf_has_issues</span>(diff_round2)))</span>
<span id="cb9-97">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>diffdf</strong>: <a href="https://cran.r-project.org/package=diffdf">CRAN</a></li>
<li><strong>cards</strong>: <a href="https://pharmaverse.github.io/cards/">pharmaverse.github.io/cards</a></li>
<li><strong>pharmaversesdtm</strong>: <a href="https://pharmaverse.github.io/pharmaversesdtm/">pharmaverse.github.io/pharmaversesdtm</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
<li><strong>waldo</strong>: <a href="https://waldo.r-lib.org/">waldo.r-lib.org</a></li>
</ul>
<section id="further-reading" class="level3">
<h3 class="anchored">Further reading</h3>
<p>References worth reading alongside this post (official documents, linked for context rather than quoted line by line):</p>
<ul>
<li><strong>Knight and Leveson, “An experimental evaluation of the assumption of independence in multiversion programming” (IEEE Transactions on Software Engineering, 1986)</strong>: <a href="https://doi.org/10.1109/TSE.1986.6312924">doi.org/10.1109/TSE.1986.6312924</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-series-nav__series">Pharma series · part 6 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 5</span><span class="site-related-card__title">Validation-ready R packages</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/r-submissions-pkglite/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 7</span><span class="site-related-card__title">R in regulatory submissions and {pkglite}</span></a>
</div>
</div>
</div>
<section id="also-in" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="also-in">Also in</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-link-row" title="Move from unit tests to snapshots, fixtures, property-based checks and Shiny app tests. The parts show how to make those checks repeatable in R projects."><span class="is-card__eyebrow site-link-row__label">Series · 7 parts</span><span class="site-link-row__title">Testing series</span></a></li>
</ul>
</div>
</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/property-based-testing/index.html" class="site-link-row" title="Define general invariants, generate varied test inputs with quickcheck, and use shrinking to pinpoint edge cases in R functions and clinical derivations."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Property-based testing in R</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html" class="site-link-row" title="Capture complex console output, rtables layouts, and plots with testthat snapshots and vdiffr to catch regressions without fragile manual assertions."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Snapshot tests for R output, tables and plots</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html" class="site-link-row" title="Set up testthat 3rd edition, structure unit tests with expectations, run them locally and in CI, and build reproducible verification suites."><span class="is-card__eyebrow site-link-row__label">Builds on</span><span class="site-link-row__title">testthat essentials</span></a></li>
</ul>
</div>
</section>
</div>

</section>
</section>

 ]]></description>
  <category>Pharma</category>
  <category>R</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/</guid>
  <pubDate>Sat, 26 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>R in regulatory submissions and {pkglite}</title>
  <link>https://insightsurge-dev.web.app/posts/r-submissions-pkglite/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Earlier in this series, we traced how clinical trial teams engineer <a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/index.html">the clinical reporting pipeline in R</a>: raw data flows into SDTM tabulations, derives into ADaM analysis datasets, calculates into <a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html">Analysis Results Data</a>, and renders into <a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html">tables, figures, and listings</a> reconciled through <a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/index.html">independent double programming</a>.</p>
<p>Eventually, this analytical pipeline must leave your local environment and enter the health authority review portal. In the United States, regulatory filings to the Food and Drug Administration (FDA) Center for Drug Evaluation and Research (CDER) are governed by Section 745A(a) of the Federal Food, Drug, and Cosmetic Act, which mandates electronic filings under the Electronic Common Technical Document (eCTD) standard.</p>
<p>Statistical reviewers at health authorities do not accept summary reports on faith. Under the FDA’s <em>Study Data Technical Conformance Guide</em>, reviewers receive the statistical programs used to generate primary efficacy and safety results so they can inspect derivations and independently replicate analysis tables.</p>
<p>Here clinical software engineering encounters a strict transport boundary. Within an eCTD filing, clinical study reports and analysis code reside under Module 5:</p>
<pre class="text"><code>m5/datasets/&lt;study-id&gt;/analysis/adam/programs/</code></pre>
<p>Only certain file types are accepted in these folders, and for years package archives such as <code>.tar.gz</code> were not among them.</p>
<p>A standalone, thousand-line R script is rarely how mature engineering teams organise clinical analyses. Robust reporting pipelines rely on structured R packages that bundle shared derivation algorithms, dataset validation rules, and documentation. But how can a sponsor deliver a full R package hierarchy through an electronic gateway that historically accepted only plain text files?</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In cloud and web engineering, shipping a reproducible build to an external environment is an established pattern:</p>
<ul>
<li><strong>Lockfiles</strong> (<code>package-lock.json</code>, <code>poetry.lock</code>, <code>Cargo.lock</code>) capture cryptographic content hashes and exact transitive dependency versions.</li>
<li><strong>Software Bills of Materials (SBOMs)</strong> provide a complete manifest of every runtime library and dependency.</li>
<li><strong>Container images</strong> (OCI / Docker) package the system libraries and runtimes an application needs (containers share the host’s kernel).</li>
<li><strong>Artefact registries</strong> distribute versioned build artefacts as immutable packages.</li>
</ul>
<p>The objective in clinical submissions is identical: transfer an isolated, self-contained analytical bundle to an external reviewer so they can reproduce identical results.</p>
<p>A regulatory reviewer’s environment is not a cloud deployment: the file types a submission may contain are restricted, and a reviewer should be able to read the code before running it. Plain text meets both needs.</p>
</section>
<section id="what-the-r-consortium-submission-pilots-tested" class="level2">
<h2 class="anchored" data-anchor-id="what-the-r-consortium-submission-pilots-tested">What the R Consortium submission pilots tested</h2>
<p>The R Consortium’s <a href="https://rconsortium.github.io/submissions-wg/">R Submissions Working Group</a> has run a series of pilot submissions to the FDA, each testing one more piece of an R-based submission. Their submission packages, including the FDA’s responses, are public on GitHub (for example <a href="https://github.com/RConsortium/submissions-pilot1-to-fda">Pilot 1</a>).</p>
<ul>
<li><strong>Pilot 1 (submitted November 2021, revised February 2022, final FDA response March 2022):</strong> four TLFs from simulated CDISC pilot data. The sponsor’s own helper package was delivered as a single text file, <code>r0pkg.txt</code>, packed with <code>{pkglite}</code>.</li>
<li><strong>Pilot 2 (2022–2024):</strong> a Shiny app showing the Pilot 1 TLFs with basic filtering, bundled as a package and delivered as <code>r1pkg.txt</code>. The FDA’s summary letter is dated 27 September 2023.</li>
<li><strong>Pilot 3 (2023–2024):</strong> ADaM datasets derived in R, plus the TLFs. The <code>renv.lock</code> file went in as <code>renv-lock.txt</code>, and a helper package as a <code>.zip</code> file (<code>pilot3utils_0.0.2.zip</code>).</li>
<li><strong>Pilot 4 (2024–2025):</strong> the Shiny app again, using WebAssembly (webR) and containers; the app’s files were delivered as a <code>{pkglite}</code> text file (<code>pilot4_webR_pkglite.txt</code>).</li>
</ul>
<section id="the-august-2025-file-format-update" class="level3">
<h3 class="anchored" data-anchor-id="the-august-2025-file-format-update">The August 2025 file-format update</h3>
<p>In August 2025, a revision of the FDA’s eCTD Technical Conformance Guide (Section 9.3) added file types for delivering R packages (<code>.rds</code>, <code>.rdb</code>, <code>.rdx</code>, <code>.rdata</code>/<code>.rda</code>, <code>.md</code>, <code>.rd</code>) and widened the use of <code>.zip</code> and <code>.html</code>, so a non-public package can now go in as a <code>.zip</code> file. The <a href="https://r-consortium.org/posts/expanded-fda-ectd-file-format-support-for-r-packages/">R Consortium’s announcement</a> credits the pilots’ collaboration with FDA reviewers. Plain text is still useful: anyone can read and diff it before running anything.</p>
</section>
</section>
<section id="the-r-way-serializing-packages-with-pkglite" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-serializing-packages-with-pkglite">The R way: serializing packages with {pkglite}</h2>
<p>The <a href="https://cran.r-project.org/package=pkglite"><code>{pkglite}</code></a> package (<a href="https://doi.org/10.1177/17407745221123244">Zhao et al., 2023</a>) provides a grammar and file standard for converting R packages into plain-text files and restoring them.</p>
<p>The packed output follows the Debian Control File (DCF) standard—the same key-value syntax used in Debian package management, R <code>DESCRIPTION</code> files, and <code>read.dcf()</code>. Each file in the package is serialised into a distinct block separated by a blank line:</p>
<pre class="text"><code>Package: submissionpkg
File: R/derive_study_day.R
Format: text
Content:
  #' Derive study day from reference date (no day 0 in clinical trials)
  #' @param trt_dt Treatment date
  #' @param ref_dt Reference date (e.g. TRTSDTM)
  #' @return Integer study day
  #' @export
  derive_study_day &lt;- function(trt_dt, ref_dt) {
    diff_days &lt;- as.integer(trt_dt - ref_dt)
    ifelse(diff_days &gt;= 0L, diff_days + 1L, diff_days)
  }</code></pre>
<p>Text files are indented by two spaces and stored verbatim. Binary files (such as <code>.rda</code> datasets) are stored as hexadecimal, following the RTF format convention (the package’s format vignette), so the whole file stays ASCII; <code>verify_ascii()</code> checks it.</p>
<section id="packing-a-package" class="level3">
<h3 class="anchored" data-anchor-id="packing-a-package">Packing a package</h3>
<p>The <code>{pkglite}</code> workflow uses three core verbs: <code>collate()</code>, <code>pack()</code>, and <code>unpack()</code>.</p>
<p>First, let us construct a minimal submission utility package in a temporary directory:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;">library</span>(pkglite)</span>
<span id="cb3-2"></span>
<span id="cb3-3">pkg_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"submissionpkg"</span>)</span>
<span id="cb3-4"><span class="fu" style="color: #4758AB;">dir.create</span>(pkg_dir, <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb3-5"><span class="fu" style="color: #4758AB;">dir.create</span>(<span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"R"</span>), <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb3-6"></span>
<span id="cb3-7"><span class="fu" style="color: #4758AB;">writeLines</span>(</span>
<span id="cb3-8">  <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb3-9">    <span class="st" style="color: #20794D;">"Package: submissionpkg"</span>,</span>
<span id="cb3-10">    <span class="st" style="color: #20794D;">"Title: Submission Utility Package"</span>,</span>
<span id="cb3-11">    <span class="st" style="color: #20794D;">"Version: 0.1.0"</span>,</span>
<span id="cb3-12">    <span class="st" style="color: #20794D;">"Description: Helper utilities for clinical trial analysis."</span>,</span>
<span id="cb3-13">    <span class="st" style="color: #20794D;">"License: Apache License (&gt;= 2)"</span>,</span>
<span id="cb3-14">    <span class="st" style="color: #20794D;">"Encoding: UTF-8"</span></span>
<span id="cb3-15">  ),</span>
<span id="cb3-16">  <span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"DESCRIPTION"</span>)</span>
<span id="cb3-17">)</span>
<span id="cb3-18"></span>
<span id="cb3-19"><span class="fu" style="color: #4758AB;">writeLines</span>(<span class="st" style="color: #20794D;">"export(derive_study_day)"</span>, <span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"NAMESPACE"</span>))</span>
<span id="cb3-20"></span>
<span id="cb3-21"><span class="fu" style="color: #4758AB;">writeLines</span>(</span>
<span id="cb3-22">  <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb3-23">    <span class="st" style="color: #20794D;">"#' Derive study day from reference date (no day 0 in clinical trials)"</span>,</span>
<span id="cb3-24">    <span class="st" style="color: #20794D;">"#' @param trt_dt Treatment date"</span>,</span>
<span id="cb3-25">    <span class="st" style="color: #20794D;">"#' @param ref_dt Reference date (e.g. TRTSDTM)"</span>,</span>
<span id="cb3-26">    <span class="st" style="color: #20794D;">"#' @return Integer study day"</span>,</span>
<span id="cb3-27">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb3-28">    <span class="st" style="color: #20794D;">"derive_study_day &lt;- function(trt_dt, ref_dt) {"</span>,</span>
<span id="cb3-29">    <span class="st" style="color: #20794D;">"  diff_days &lt;- as.integer(trt_dt - ref_dt)"</span>,</span>
<span id="cb3-30">    <span class="st" style="color: #20794D;">"  ifelse(diff_days &gt;= 0L, diff_days + 1L, diff_days)"</span>,</span>
<span id="cb3-31">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb3-32">  ),</span>
<span id="cb3-33">  <span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"derive_study_day.R"</span>)</span>
<span id="cb3-34">)</span></code></pre></div></div>
<p>We evaluate the file scope with <code>pkglite::file_ectd()</code> and pack the collection into a text file:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># Collate the files that the eCTD file specification selects</span></span>
<span id="cb4-2">fc <span class="ot" style="color: #003B4F;">&lt;-</span> pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">collate</span>(pkg_dir, pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">file_ectd</span>())</span>
<span id="cb4-3">fc<span class="sc" style="color: #5E5E5E;">$</span>df[, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"path_rel"</span>, <span class="st" style="color: #20794D;">"format"</span>)]</span>
<span id="cb4-4"></span>
<span id="cb4-5"><span class="co" style="color: #5E5E5E;"># Pack into a single plain text file</span></span>
<span id="cb4-6">txt_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"submissionpkg.txt"</span>)</span>
<span id="cb4-7">pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pack</span>(fc, <span class="at" style="color: #657422;">output =</span> txt_file, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb4-8"></span>
<span id="cb4-9"><span class="co" style="color: #5E5E5E;"># Verify ASCII compliance for eCTD gateway submission</span></span>
<span id="cb4-10">is_clean_ascii <span class="ot" style="color: #003B4F;">&lt;-</span> pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">verify_ascii</span>(txt_file, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb4-11">is_clean_ascii</span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># Inspect the top of the generated DCF file</span></span>
<span id="cb5-2"><span class="fu" style="color: #4758AB;">head</span>(<span class="fu" style="color: #4758AB;">readLines</span>(txt_file), <span class="at" style="color: #657422;">n =</span> <span class="dv" style="color: #AD0000;">12</span>L)</span></code></pre></div></div>
<p><code>pkglite::file_ectd()</code> is the file specification {pkglite} provides for eCTD submissions (its help: “a combination of file specifications for eCTD submissions”); it selects a narrower set of files than <code>pkglite::file_default()</code>.</p>
</section>
<section id="unpacking-on-the-reviewer-side" class="level3">
<h3 class="anchored" data-anchor-id="unpacking-on-the-reviewer-side">Unpacking on the reviewer side</h3>
<p>On the reviewer’s workstation, restoring the complete package directory tree requires a single call:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">restored_root <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"review_workspace"</span>)</span>
<span id="cb6-2">pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">unpack</span>(<span class="at" style="color: #657422;">input =</span> txt_file, <span class="at" style="color: #657422;">output =</span> restored_root, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb6-3"></span>
<span id="cb6-4"><span class="co" style="color: #5E5E5E;"># Verify the restored directory structure</span></span>
<span id="cb6-5"><span class="fu" style="color: #4758AB;">list.files</span>(<span class="fu" style="color: #4758AB;">file.path</span>(restored_root, <span class="st" style="color: #20794D;">"submissionpkg"</span>), <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span></code></pre></div></div>
<p>To install the packages after unpacking them, <code>unpack()</code> takes <code>install = TRUE</code> (as the package’s vignette shows):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="co" style="color: #5E5E5E;"># Unpack and install the package into the reviewer's active library</span></span>
<span id="cb7-2">pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">unpack</span>(</span>
<span id="cb7-3">  <span class="at" style="color: #657422;">input =</span> <span class="st" style="color: #20794D;">"submissionpkg.txt"</span>,</span>
<span id="cb7-4">  <span class="at" style="color: #657422;">output =</span> <span class="st" style="color: #20794D;">"review_workspace"</span>,</span>
<span id="cb7-5">  <span class="at" style="color: #657422;">install =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb7-6">)</span></code></pre></div></div>
</section>
</section>
<section id="reproducibility-is-a-three-tier-discipline" class="level2">
<h2 class="anchored" data-anchor-id="reproducibility-is-a-three-tier-discipline">Reproducibility is a three-tier discipline</h2>
<p>Packaging code into plain text solves file transfer across regulated gateways, but transport is only the first tier of clinical reproducibility:</p>
<pre class="text"><code>┌────────────────────────────────────────────────────────┐
│ Tier 3: Execution Runtime                              │
│ Pinned R version, OS libraries and compilers           │
├────────────────────────────────────────────────────────┤
│ Tier 2: Dependency Lockfile                            │
│ renv.lock (sent as renv-lock.txt in Pilot 3)           │
├────────────────────────────────────────────────────────┤
│ Tier 1: Source Packaging                               │
│ Proprietary functions &amp; data bundled via pkglite (.txt)│
└────────────────────────────────────────────────────────┘</code></pre>
<ol type="1">
<li><strong>Source package tier:</strong> <code>{pkglite}</code> serialises and restores the exact directory structure, code files, and internal data objects.</li>
<li><strong>Dependency tier:</strong> An <code>renv.lock</code> file records the exact versions and sources of the open-source packages (such as <code>{admiral}</code>, <code>{rtables}</code>, and <code>{cards}</code>). In submissions, this is submitted alongside the code as <code>renv-lock.txt</code> and restored with <code>renv::restore()</code>.</li>
<li><strong>Execution runtime tier:</strong> The R version and relevant system details, documented for the reviewer (for example in the Analysis Data Reviewer’s Guide, as the pilots did).</li>
</ol>
<p>If any of these three tiers is missing, code that runs cleanly on a sponsor’s laptop will fail when an external reviewer attempts replication.</p>
</section>
<section id="honest-gxp-framing" class="level2">
<h2 class="anchored" data-anchor-id="honest-gxp-framing">Honest GxP framing</h2>
<p>No tool is “regulatory approved”: the FDA reviews a sponsor’s submission and its evidence, not programming languages or packages.</p>
<p>Using <code>{pkglite}</code> does not make a clinical submission valid by itself. What it provides is a transparent, inspectable packaging protocol that respects health authority gateway file specifications. What makes code reviewable is the combination: readable packaging, a pinned environment, clear reviewer documentation and tests.</p>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/r-submissions-pkglite/scripts/pkglite-demo.R">View <code>pkglite-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/r-submissions-pkglite/scripts/pkglite-demo.R" download="pkglite-demo.R">Download</a></p>
<p>Builds a throwaway package in a temporary directory, serialises it with <code>{pkglite}</code> into a <code>.txt</code> file, restores it to a new location, and verifies every file byte for byte. Requires <code>{pkglite}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>pkglite-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="co" style="color: #5E5E5E;"># Builds a tiny throwaway package, packs it with pkglite into a plain-text</span></span>
<span id="cb9-2"><span class="co" style="color: #5E5E5E;"># file (.txt), restores it to an unpacked directory, and verifies file</span></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;"># trees and byte-level contents.</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb9-5"><span class="co" style="color: #5E5E5E;">#   Rscript pkglite-demo.R</span></span>
<span id="cb9-6"></span>
<span id="cb9-7">create_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(pkg_dir) {</span>
<span id="cb9-8">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(pkg_dir)) {</span>
<span id="cb9-9">    <span class="fu" style="color: #4758AB;">dir.create</span>(pkg_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb9-10">  }</span>
<span id="cb9-11">  <span class="fu" style="color: #4758AB;">dir.create</span>(<span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"R"</span>), <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-12">  <span class="fu" style="color: #4758AB;">dir.create</span>(<span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"data"</span>), <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-13"></span>
<span id="cb9-14">  desc_content <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-15">    <span class="st" style="color: #20794D;">"Package: tinypkg"</span>,</span>
<span id="cb9-16">    <span class="st" style="color: #20794D;">"Title: Minimal Demo Package for pkglite"</span>,</span>
<span id="cb9-17">    <span class="st" style="color: #20794D;">"Version: 0.1.0"</span>,</span>
<span id="cb9-18">    <span class="st" style="color: #20794D;">"Description: Minimal package for packing and unpacking with pkglite."</span>,</span>
<span id="cb9-19">    <span class="st" style="color: #20794D;">"License: Apache License (&gt;= 2)"</span>,</span>
<span id="cb9-20">    <span class="st" style="color: #20794D;">"Encoding: UTF-8"</span></span>
<span id="cb9-21">  )</span>
<span id="cb9-22">  <span class="fu" style="color: #4758AB;">writeLines</span>(desc_content, <span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"DESCRIPTION"</span>))</span>
<span id="cb9-23"></span>
<span id="cb9-24">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="st" style="color: #20794D;">"export(add_one)"</span>, <span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"NAMESPACE"</span>))</span>
<span id="cb9-25"></span>
<span id="cb9-26">  r_content <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-27">    <span class="st" style="color: #20794D;">"#' Add one to a numeric value"</span>,</span>
<span id="cb9-28">    <span class="st" style="color: #20794D;">"#' @param x Numeric input"</span>,</span>
<span id="cb9-29">    <span class="st" style="color: #20794D;">"#' @return x + 1L"</span>,</span>
<span id="cb9-30">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb9-31">    <span class="st" style="color: #20794D;">"add_one &lt;- function(x) {"</span>,</span>
<span id="cb9-32">    <span class="st" style="color: #20794D;">"  x + 1L"</span>,</span>
<span id="cb9-33">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb9-34">  )</span>
<span id="cb9-35">  <span class="fu" style="color: #4758AB;">writeLines</span>(r_content, <span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"add_one.R"</span>))</span>
<span id="cb9-36"></span>
<span id="cb9-37">  toy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb9-38">    <span class="at" style="color: #657422;">subjid =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"01"</span>, <span class="st" style="color: #20794D;">"02"</span>),</span>
<span id="cb9-39">    <span class="at" style="color: #657422;">val =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">10</span>L, <span class="dv" style="color: #AD0000;">20</span>L),</span>
<span id="cb9-40">    <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb9-41">  )</span>
<span id="cb9-42">  <span class="fu" style="color: #4758AB;">save</span>(toy, <span class="at" style="color: #657422;">file =</span> <span class="fu" style="color: #4758AB;">file.path</span>(pkg_dir, <span class="st" style="color: #20794D;">"data"</span>, <span class="st" style="color: #20794D;">"toy.rda"</span>))</span>
<span id="cb9-43"></span>
<span id="cb9-44">  <span class="fu" style="color: #4758AB;">invisible</span>(pkg_dir)</span>
<span id="cb9-45">}</span>
<span id="cb9-46"></span>
<span id="cb9-47">pack_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb9-48">  pkg_dir,</span>
<span id="cb9-49">  <span class="at" style="color: #657422;">txt_path =</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"tinypkg.txt"</span>),</span>
<span id="cb9-50">  <span class="at" style="color: #657422;">spec =</span> pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">file_default</span>()</span>
<span id="cb9-51">) {</span>
<span id="cb9-52">  fc <span class="ot" style="color: #003B4F;">&lt;-</span> pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">collate</span>(pkg_dir, spec)</span>
<span id="cb9-53">  pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pack</span>(fc, <span class="at" style="color: #657422;">output =</span> txt_path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb9-54">  <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">txt_path =</span> txt_path, <span class="at" style="color: #657422;">file_collection =</span> fc)</span>
<span id="cb9-55">}</span>
<span id="cb9-56"></span>
<span id="cb9-57">unpack_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(txt_path, out_dir) {</span>
<span id="cb9-58">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(out_dir)) {</span>
<span id="cb9-59">    <span class="fu" style="color: #4758AB;">dir.create</span>(out_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb9-60">  }</span>
<span id="cb9-61">  pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">unpack</span>(<span class="at" style="color: #657422;">input =</span> txt_path, <span class="at" style="color: #657422;">output =</span> out_dir, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb9-62">  <span class="fu" style="color: #4758AB;">file.path</span>(out_dir, <span class="st" style="color: #20794D;">"tinypkg"</span>)</span>
<span id="cb9-63">}</span>
<span id="cb9-64"></span>
<span id="cb9-65">compare_packages <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(orig_dir, restored_dir, rel_paths) {</span>
<span id="cb9-66">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">lapply</span>(rel_paths, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(rel_path) {</span>
<span id="cb9-67">    orig_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(orig_dir, rel_path)</span>
<span id="cb9-68">    restored_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(restored_dir, rel_path)</span>
<span id="cb9-69"></span>
<span id="cb9-70">    exists_orig <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.exists</span>(orig_file)</span>
<span id="cb9-71">    exists_restored <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.exists</span>(restored_file)</span>
<span id="cb9-72"></span>
<span id="cb9-73">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>exists_orig <span class="sc" style="color: #5E5E5E;">||</span> <span class="sc" style="color: #5E5E5E;">!</span>exists_restored) {</span>
<span id="cb9-74">      <span class="fu" style="color: #4758AB;">return</span>(<span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb9-75">        <span class="at" style="color: #657422;">file =</span> rel_path,</span>
<span id="cb9-76">        <span class="at" style="color: #657422;">exists_orig =</span> exists_orig,</span>
<span id="cb9-77">        <span class="at" style="color: #657422;">exists_restored =</span> exists_restored,</span>
<span id="cb9-78">        <span class="at" style="color: #657422;">byte_identical =</span> <span class="cn" style="color: #8f5902;">FALSE</span>,</span>
<span id="cb9-79">        <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb9-80">      ))</span>
<span id="cb9-81">    }</span>
<span id="cb9-82"></span>
<span id="cb9-83">    orig_bytes <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readBin</span>(orig_file, <span class="st" style="color: #20794D;">"raw"</span>, <span class="at" style="color: #657422;">n =</span> <span class="fu" style="color: #4758AB;">file.info</span>(orig_file)<span class="sc" style="color: #5E5E5E;">$</span>size)</span>
<span id="cb9-84">    restored_bytes <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readBin</span>(</span>
<span id="cb9-85">      restored_file,</span>
<span id="cb9-86">      <span class="st" style="color: #20794D;">"raw"</span>,</span>
<span id="cb9-87">      <span class="at" style="color: #657422;">n =</span> <span class="fu" style="color: #4758AB;">file.info</span>(restored_file)<span class="sc" style="color: #5E5E5E;">$</span>size</span>
<span id="cb9-88">    )</span>
<span id="cb9-89"></span>
<span id="cb9-90">    <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb9-91">      <span class="at" style="color: #657422;">file =</span> rel_path,</span>
<span id="cb9-92">      <span class="at" style="color: #657422;">exists_orig =</span> exists_orig,</span>
<span id="cb9-93">      <span class="at" style="color: #657422;">exists_restored =</span> exists_restored,</span>
<span id="cb9-94">      <span class="at" style="color: #657422;">byte_identical =</span> <span class="fu" style="color: #4758AB;">identical</span>(orig_bytes, restored_bytes),</span>
<span id="cb9-95">      <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb9-96">    )</span>
<span id="cb9-97">  })</span>
<span id="cb9-98"></span>
<span id="cb9-99">  <span class="fu" style="color: #4758AB;">do.call</span>(rbind, results)</span>
<span id="cb9-100">}</span>
<span id="cb9-101"></span>
<span id="cb9-102"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb9-103">  demo_root <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"pkglite-demo-run"</span>)</span>
<span id="cb9-104">  pkg_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_root, <span class="st" style="color: #20794D;">"tinypkg"</span>)</span>
<span id="cb9-105">  unpack_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_root, <span class="st" style="color: #20794D;">"restored"</span>)</span>
<span id="cb9-106">  txt_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_root, <span class="st" style="color: #20794D;">"tinypkg.txt"</span>)</span>
<span id="cb9-107"></span>
<span id="cb9-108">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Creating throwaway package..."</span>)</span>
<span id="cb9-109">  <span class="fu" style="color: #4758AB;">create_demo_package</span>(pkg_dir)</span>
<span id="cb9-110"></span>
<span id="cb9-111">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Packing package into plain text with pkglite..."</span>)</span>
<span id="cb9-112">  pack_res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">pack_demo_package</span>(pkg_dir, <span class="at" style="color: #657422;">txt_path =</span> txt_path)</span>
<span id="cb9-113"></span>
<span id="cb9-114">  is_ascii <span class="ot" style="color: #003B4F;">&lt;-</span> pkglite<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">verify_ascii</span>(txt_path, <span class="at" style="color: #657422;">quiet =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb9-115">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"ASCII verification: "</span>, <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (is_ascii) <span class="st" style="color: #20794D;">"PASS"</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="st" style="color: #20794D;">"FAIL"</span>)</span>
<span id="cb9-116"></span>
<span id="cb9-117">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Restoring package to new directory..."</span>)</span>
<span id="cb9-118">  restored_pkg <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">unpack_demo_package</span>(txt_path, unpack_dir)</span>
<span id="cb9-119"></span>
<span id="cb9-120">  rel_paths <span class="ot" style="color: #003B4F;">&lt;-</span> pack_res<span class="sc" style="color: #5E5E5E;">$</span>file_collection<span class="sc" style="color: #5E5E5E;">$</span>df<span class="sc" style="color: #5E5E5E;">$</span>path_rel</span>
<span id="cb9-121">  comparison <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">compare_packages</span>(pkg_dir, restored_pkg, rel_paths)</span>
<span id="cb9-122"></span>
<span id="cb9-123">  <span class="fu" style="color: #4758AB;">print</span>(comparison)</span>
<span id="cb9-124">  all_match <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">all</span>(comparison<span class="sc" style="color: #5E5E5E;">$</span>byte_identical)</span>
<span id="cb9-125">  <span class="fu" style="color: #4758AB;">message</span>(</span>
<span id="cb9-126">    <span class="st" style="color: #20794D;">"Round trip status: "</span>,</span>
<span id="cb9-127">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (all_match) <span class="st" style="color: #20794D;">"ALL FILES MATCH EXACTLY"</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="st" style="color: #20794D;">"DISCREPANCIES FOUND"</span></span>
<span id="cb9-128">  )</span>
<span id="cb9-129">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>pkglite</strong>: <a href="https://cran.r-project.org/package=pkglite">CRAN</a></li>
</ul>
<p><strong>Standards and organisations</strong></p>
<ul>
<li><strong>R Consortium R Submissions Working Group</strong>: <a href="https://rconsortium.github.io/submissions-wg/">rconsortium.github.io/submissions-wg</a></li>
<li><strong>Pilot 1 submission repository</strong>: <a href="https://github.com/RConsortium/submissions-pilot1-to-fda">github.com/RConsortium/submissions-pilot1-to-fda</a></li>
<li><strong>Pilot 2 submission repository</strong>: <a href="https://github.com/RConsortium/submissions-pilot2-to-fda">github.com/RConsortium/submissions-pilot2-to-fda</a></li>
<li><strong>Pilot 3 submission repository</strong>: <a href="https://github.com/RConsortium/submissions-pilot3-adam-to-fda">github.com/RConsortium/submissions-pilot3-adam-to-fda</a></li>
<li><strong>Pilot 4 submission repository</strong>: <a href="https://github.com/RConsortium/submissions-pilot4-webR-to-fda">github.com/RConsortium/submissions-pilot4-webR-to-fda</a></li>
<li><strong>R Consortium announcement of the August 2025 FDA eCTD file-format update</strong>: <a href="https://r-consortium.org/posts/expanded-fda-ectd-file-format-support-for-r-packages/">r-consortium.org</a></li>
</ul>
<section id="further-reading" class="level3">
<h3 class="anchored">Further reading</h3>
<p>References worth reading alongside this post (official documents, linked for context rather than quoted line by line):</p>
<ul>
<li><strong>FDA, Electronic Common Technical Document (eCTD)</strong>, including the requirement for electronic submissions: <a href="https://www.fda.gov/drugs/electronic-regulatory-submission-and-review/electronic-common-technical-document-ectd">fda.gov</a></li>
<li><strong>FDA, <em>Study Data Technical Conformance Guide</em></strong>: <a href="https://www.fda.gov/regulatory-information/search-fda-guidance-documents/study-data-technical-conformance-guide-technical-specifications-document">fda.gov</a></li>
<li><strong>FDA, <em>eCTD Technical Conformance Guide</em> (PDF; Section 9.3 covers file formats)</strong>: <a href="https://www.fda.gov/media/93818/download">fda.gov</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-series-nav__series">Pharma series · part 7 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 6</span><span class="site-related-card__title">QC and double programming with {diffdf}</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html" class="site-link-row" title="Adopt semantic versioning, readable changelogs, and annotated git tags to support change control."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Releases &amp; changelogs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="site-link-row" title="Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Coverage and tests as evidence</span></a></li>
</ul>
</div>
</section>
</div>

</section>
</section>

 ]]></description>
  <category>Pharma</category>
  <category>R packages</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/r-submissions-pkglite/</guid>
  <pubDate>Sat, 26 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Validation-ready R packages</title>
  <link>https://insightsurge-dev.web.app/posts/validation-ready-r-packages/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>When statistical programmers assemble an R clinical reporting pipeline—such as the pipelines described in our posts on <a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/index.html">the clinical reporting pipeline</a>, <a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html">generating TFLs</a>, <a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html">Analysis Results Data with {cards}</a>, and <a href="https://insightsurge-dev.web.app/posts/cdisc-ars-siera/index.html">the CDISC Analysis Results Standard and {siera}</a>—they depend on a deep tree of open-source packages.</p>
<p>Introducing a new package inevitably prompts a familiar gatekeeping query: <em>“Is this package validated?”</em></p>
<p>In regulated environments, that question creates two failure modes:</p>
<ul>
<li><strong>The blanket ban</strong>: Teams restrict environments to base R and legacy tools, refusing modern packages without an external compliance stamp. Programmers then write bespoke derivation scripts that re-introduce the very errors modern packages prevent.</li>
<li><strong>The passive rubber-stamp</strong>: Teams assume that because a package is on CRAN, it is automatically acceptable for primary clinical endpoints.</li>
</ul>
<p>Both approaches stem from a fundamental misunderstanding: <strong>“validated package” is a misnomer</strong>.</p>
<p>An R package cannot be validated in the abstract. Under regulatory standards—including the US FDA’s <em>General Principles of Software Validation</em> (2002) and GAMP 5—software validation establishes objective evidence that software conforms to user needs and <strong>intended uses</strong> within a qualified infrastructure. A function might be suitable for exploratory visualisation, yet require rigorous verification if used to derive a primary study endpoint.</p>
<p>CRAN technical checks verify that packages build, execute examples, and pass basic checks across platforms. CRAN does not evaluate statistical accuracy or suitability for regulatory reporting.</p>
<p>Teams need an engineered, risk-based approach to determine whether an open-source package is <strong>validation-ready</strong> and fit for its intended use.</p>
</section>
<section id="the-web-analogue-dependency-vetting-and-scorecards" class="level2">
<h2 class="anchored" data-anchor-id="the-web-analogue-dependency-vetting-and-scorecards">The web analogue: dependency vetting and scorecards</h2>
<p>Modern web engineering and DevSecOps encountered this challenge years ago. A typical web service depends on many third-party libraries across deep dependency trees. Manually inspecting every line of source code is impossible.</p>
<p>Instead of binary trust or manual reviews, modern software engineering relies on <strong>automated heuristic risk scoring</strong> and <strong>transparent supply chain metadata</strong>:</p>
<ul>
<li><strong>OpenSSF Scorecard</strong> (<a href="https://scorecard.dev">scorecard.dev</a>): An open-source tool from the Open Source Security Foundation (OpenSSF). It evaluates Git repositories against automated heuristic checks—active maintenance, code review requirements, branch protection, CI test execution, and pinned dependencies—returning an objective score from 0 to 10.</li>
<li><strong>Software Bill of Materials (SBOM)</strong>: Machine-readable manifests (CycloneDX, SPDX) document dependency trees, cryptographic hashes, and licences, paired with vulnerability scanners (<code>npm audit</code>, <code>pip-audit</code>) to detect security defects.</li>
<li><strong>Curated internal registries</strong>: Enterprise organisations route dependencies through internal artifact repositories after automated policy checks rather than allowing direct production downloads.</li>
</ul>
<p>This engineering pattern replaces subjective intuition with reproducible, automated metrics.</p>
</section>
<section id="the-r-validation-hub-framework" class="level2">
<h2 class="anchored" data-anchor-id="the-r-validation-hub-framework">The R Validation Hub framework</h2>
<p>The <strong>R Validation Hub</strong> (<a href="https://pharmar.org/">pharmar.org</a>), which describes itself as an R Consortium-funded ISC working group, set out a risk-based approach in its white paper, <a href="https://pharmar.org/white-paper/"><em>“A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure”</em></a>. In short:</p>
<section id="core-packages-and-contributed-packages" class="level3">
<h3 class="anchored" data-anchor-id="core-packages-and-contributed-packages">1. Core packages and contributed packages</h3>
<p>The white paper separates two kinds of package:</p>
<ul>
<li><strong>Base and recommended (“core”) packages</strong>: developed by the R Foundation and shipped with the basic R installation.</li>
<li><strong>Contributed packages</strong>: “developed by anyone, and may differ in accuracy”, so they are where assessment effort goes.</li>
</ul>
</section>
<section id="four-criteria-for-contributed-packages" class="level3">
<h3 class="anchored" data-anchor-id="four-criteria-for-contributed-packages">2. Four criteria for contributed packages</h3>
<p>For contributed packages, the white paper looks at:</p>
<ul>
<li><strong>Purpose</strong>: does the package do statistical work, or not?</li>
<li><strong>Maintenance good practice</strong>: signs of a software development life cycle (versioning, NEWS, bug reporting, documentation).</li>
<li><strong>Community usage</strong>: how widely the package is used and exposed to scrutiny.</li>
<li><strong>Testing</strong>: unit tests and test coverage.</li>
</ul>
<p>Separately from those metrics, the consequence of an error depends on <strong>intended use</strong>: a package that computes a primary efficacy analysis deserves more scrutiny than one that formats a table caption.</p>
</section>
<section id="intended-for-use-versus-imports" class="level3">
<h3 class="anchored" data-anchor-id="intended-for-use-versus-imports">3. “Intended for Use” versus “Imports”</h3>
<p>The white paper distinguishes packages that analysts load directly (<strong>“Intended for Use”</strong>) from the dependencies they bring in (<strong>“Imports”</strong>), and says accuracy only needs to be verified for the Intended for Use packages; the imports are exercised through them.</p>
</section>
</section>
<section id="quantifying-package-risk-with-riskmetric" class="level2">
<h2 class="anchored" data-anchor-id="quantifying-package-risk-with-riskmetric">Quantifying package risk with {riskmetric}</h2>
<p>To gather these metrics automatically, the R Validation Hub developed <a href="https://pharmar.github.io/riskmetric/">{riskmetric}</a>.</p>
<p>The package workflow operates across three main stages:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;">library</span>(riskmetric)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">library</span>(dplyr)</span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="co" style="color: #5E5E5E;"># 1. Create package references</span></span>
<span id="cb1-5">pkgs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"glue"</span>, <span class="st" style="color: #20794D;">"cards"</span>, <span class="st" style="color: #20794D;">"riskmetric"</span>)</span>
<span id="cb1-6">refs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">pkg_ref</span>(pkgs, <span class="at" style="color: #657422;">source =</span> <span class="st" style="color: #20794D;">"pkg_install"</span>)</span></code></pre></div></div>
<p>The <code>pkg_ref()</code> function inspects local libraries or remote repositories without altering package files. Setting <code>source = "pkg_install"</code> targets the currently installed package in the active library.</p>
<section id="the-assessment-catalog" class="level3">
<h3 class="anchored" data-anchor-id="the-assessment-catalog">The assessment catalog</h3>
<p>Running <code>pkg_assess()</code> executes assessment functions that gather objective metadata:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># Define offline assessments that require no external network calls</span></span>
<span id="cb2-2">offline_assessments <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb2-3">  <span class="at" style="color: #657422;">has_news =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_news,</span>
<span id="cb2-4">  <span class="at" style="color: #657422;">news_current =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_news_current,</span>
<span id="cb2-5">  <span class="at" style="color: #657422;">has_vignettes =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_vignettes,</span>
<span id="cb2-6">  <span class="at" style="color: #657422;">export_help =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_export_help,</span>
<span id="cb2-7">  <span class="at" style="color: #657422;">has_website =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_website,</span>
<span id="cb2-8">  <span class="at" style="color: #657422;">has_maintainer =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_maintainer,</span>
<span id="cb2-9">  <span class="at" style="color: #657422;">has_source_control =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_source_control,</span>
<span id="cb2-10">  <span class="at" style="color: #657422;">has_bug_reports_url =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_bug_reports_url,</span>
<span id="cb2-11">  <span class="at" style="color: #657422;">has_examples =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_examples,</span>
<span id="cb2-12">  <span class="at" style="color: #657422;">dependencies =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_dependencies,</span>
<span id="cb2-13">  <span class="at" style="color: #657422;">license =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_license</span>
<span id="cb2-14">)</span>
<span id="cb2-15"></span>
<span id="cb2-16">assessed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">pkg_assess</span>(refs, <span class="at" style="color: #657422;">assessments =</span> offline_assessments)</span></code></pre></div></div>
<p>In <code>{riskmetric}</code> 0.2.7, nineteen assessment functions evaluate different facets of package quality:</p>
<ul>
<li><strong>Local installation metrics (offline)</strong>: <code>assess_has_news</code>, <code>assess_news_current</code>, <code>assess_has_vignettes</code>, <code>assess_export_help</code> (documentation proportion), <code>assess_has_examples</code>, <code>assess_has_maintainer</code>, <code>assess_has_website</code>, <code>assess_has_source_control</code>, <code>assess_has_bug_reports_url</code>, <code>assess_dependencies</code> (dependency footprint), <code>assess_size_codebase</code>, <code>assess_exported_namespace</code>, and <code>assess_license</code>.</li>
<li><strong>Remote network metrics</strong>: <code>assess_downloads_1yr</code> (queries CRAN download logs), <code>assess_last_30_bugs_status</code> (queries GitHub/GitLab issue resolution ratios), <code>assess_remote_checks</code> (queries CRAN check farm results), and <code>assess_reverse_dependencies</code>.</li>
<li><strong>Source-dependent metrics</strong>: <code>assess_covr_coverage</code> (requires package source code to run <code>covr::package_coverage()</code>) and <code>assess_r_cmd_check</code> (results from running <code>R CMD check</code>).</li>
</ul>
<p>The demo below uses only offline metrics that work on an installed package. It leaves out <code>assess_size_codebase</code> and <code>assess_exported_namespace</code>, which attach the package’s namespace (a side effect on the search path) and can fail to score on binary installs.</p>
</section>
<section id="the-scoring-engine" class="level3">
<h3 class="anchored" data-anchor-id="the-scoring-engine">The scoring engine</h3>
<p>Calling <code>pkg_score()</code> maps raw assessment data into standardised numeric scores between 0 and 1:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">scored <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">pkg_score</span>(assessed)</span></code></pre></div></div>
<p>Understanding how <code>{riskmetric}</code> scores packages is essential:</p>
<ol type="1">
<li><strong>Individual metric scores</strong>: Each assessment is evaluated by a specialised <code>metric_score</code> S3 method. These methods measure quality (where 1 indicates high quality and 0 indicates low quality). For example, <code>export_help</code> calculates the proportion of documented exported objects, and <code>dependencies</code> applies a logistic penalty to large dependency footprints. The <code>license</code> assessment returns <code>NA_real_</code> by design, because license acceptability reflects organisational legal policy rather than a mathematical score.</li>
<li><strong>Aggregate risk score</strong>: The <code>summarize_scores()</code> function standardises non-negative weights across metrics, calculates the weighted quality score, and returns overall package risk as <strong>Risk = 1 − Quality</strong>.</li>
</ol>
<p>In <code>{riskmetric}</code>, <strong>0 represents lowest risk</strong> (highest quality) and <strong>1 represents highest risk</strong>.</p>
<p>We can classify packages into transparent risk categories based on a documented threshold rule:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">classify_risk <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(score, <span class="at" style="color: #657422;">low_threshold =</span> <span class="fl" style="color: #AD0000;">0.25</span>, <span class="at" style="color: #657422;">medium_threshold =</span> <span class="fl" style="color: #AD0000;">0.50</span>) {</span>
<span id="cb4-2">  <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb4-3">    <span class="fu" style="color: #4758AB;">is.na</span>(score),</span>
<span id="cb4-4">    <span class="st" style="color: #20794D;">"Unassessed"</span>,</span>
<span id="cb4-5">    <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb4-6">      score <span class="sc" style="color: #5E5E5E;">&lt;=</span> low_threshold,</span>
<span id="cb4-7">      <span class="st" style="color: #20794D;">"Low Risk"</span>,</span>
<span id="cb4-8">      <span class="fu" style="color: #4758AB;">ifelse</span>(score <span class="sc" style="color: #5E5E5E;">&lt;=</span> medium_threshold, <span class="st" style="color: #20794D;">"Medium Risk"</span>, <span class="st" style="color: #20794D;">"High Risk"</span>)</span>
<span id="cb4-9">    )</span>
<span id="cb4-10">  )</span>
<span id="cb4-11">}</span>
<span id="cb4-12"></span>
<span id="cb4-13">summary_table <span class="ot" style="color: #003B4F;">&lt;-</span> scored <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb4-14">  <span class="fu" style="color: #4758AB;">mutate</span>(<span class="at" style="color: #657422;">decision =</span> <span class="fu" style="color: #4758AB;">classify_risk</span>(pkg_score)) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb4-15">  <span class="fu" style="color: #4758AB;">select</span>(</span>
<span id="cb4-16">    package,</span>
<span id="cb4-17">    version,</span>
<span id="cb4-18">    pkg_score,</span>
<span id="cb4-19">    decision,</span>
<span id="cb4-20">    has_news,</span>
<span id="cb4-21">    news_current,</span>
<span id="cb4-22">    export_help,</span>
<span id="cb4-23">    has_vignettes,</span>
<span id="cb4-24">    dependencies,</span>
<span id="cb4-25">    license</span>
<span id="cb4-26">  )</span>
<span id="cb4-27"></span>
<span id="cb4-28"><span class="fu" style="color: #4758AB;">as.data.frame</span>(summary_table)</span></code></pre></div></div>
<p>Running this offline against our local environment yields:</p>
<ul>
<li><code>{glue}</code> (score ~ 0.107): <strong>Low Risk</strong>, driven by comprehensive documentation, low dependencies, and active maintainership.</li>
<li><code>{cards}</code> (score ~ 0.272): <strong>Medium Risk</strong>, driven by its larger dependency footprint despite complete function documentation.</li>
<li><code>{riskmetric}</code> (score ~ 0.273): <strong>Medium Risk</strong>, reflecting its dependency footprint and the absence of a current version entry in its NEWS file.</li>
</ul>
</section>
</section>
<section id="governance-and-triage-with-riskassessment" class="level2">
<h2 class="anchored" data-anchor-id="governance-and-triage-with-riskassessment">Governance and triage with {riskassessment}</h2>
<p>While <code>{riskmetric}</code> provides the programmatic engine, organisations require a collaborative interface for team reviews, sign-offs, and audits. The R Validation Hub developed <a href="https://pharmar.github.io/riskassessment/">{riskassessment}</a>, an open-source Shiny application designed specifically for this workflow.</p>
<p>According to its documentation, the app lets reviewers:</p>
<ul>
<li>look at <code>{riskmetric}</code> output without writing R code;</li>
<li>add comments on individual metrics and give each package an overall assessment (low, medium or high risk);</li>
<li>download a static report with the package’s risk, metric outputs and the reviewer’s summary and comments;</li>
<li>store assessments in a database for later viewing.</li>
</ul>
<p>An admin user can manage users, change the metric weights used in the risk score, and define decision categories and automation rules based on risk scores. The app has several predefined roles beyond admin (see its “User Roles and Privileges” documentation).</p>
</section>
<section id="what-evidence-a-regulated-team-keeps" class="level2">
<h2 class="anchored" data-anchor-id="what-evidence-a-regulated-team-keeps">What evidence a regulated team keeps</h2>
<p>A risk-based approach does not eliminate documentation; it replaces unstructured speculation with auditable engineering artifacts. For any package used in clinical reporting, a regulated team retains five pieces of evidence:</p>
<ol type="1">
<li><strong>The assessment report</strong>: The static report generated by <code>{riskmetric}</code> or <code>{riskassessment}</code> capturing metric scores, reviewer comments, and the final risk classification.</li>
<li><strong>The pinned environment lockfile</strong>: An immutable <code>renv.lock</code> recording exact package versions, a hash for each package, and repository sources (such as a dated Posit Package Manager snapshot), as covered in our post on <a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html">dependencies, runtime pinning and vetting</a>.</li>
<li><strong>Execution environment qualification</strong>: A container image (Docker/OCI) or controlled server image verifying that system compilers, OS libraries, and BLAS/LAPACK runtimes match the tested environment.</li>
<li><strong>Installation and test runs in the target environment</strong>: CI runs showing that every declared package loads and that your own tests (and, where useful, the packages’ tests) pass in the environment you will use.</li>
<li><strong>Documented intended use</strong>: A written statement in the project specification explaining what role the package plays in the reporting pipeline and confirming its fitness for that designated purpose.</li>
</ol>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/scripts/riskmetric-demo.R">View <code>riskmetric-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/scripts/riskmetric-demo.R" download="riskmetric-demo.R">Download</a></p>
<p>A modular, runnable implementation of this offline assessment workflow. It inspects installed packages in the local library, applies offline quality metrics, computes composite risk scores, and outputs a formatted decision table. Requires <code>{riskmetric}</code> and <code>{dplyr}</code>.</p>
<p>The script’s paired test file verifies that package references are generated correctly, that scores fall within the valid [0, 1] range, and that classification rules execute without requiring external network connectivity.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>riskmetric-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># Assess installed R packages offline with {riskmetric}</span></span>
<span id="cb5-2"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb5-3"><span class="co" style="color: #5E5E5E;"># Runs local, network-free risk assessments against installed packages in the</span></span>
<span id="cb5-4"><span class="co" style="color: #5E5E5E;"># active library, scores quality metrics, and classifies packages into</span></span>
<span id="cb5-5"><span class="co" style="color: #5E5E5E;"># risk categories based on a documented threshold rule.</span></span>
<span id="cb5-6"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb5-7"><span class="co" style="color: #5E5E5E;"># Run with:</span></span>
<span id="cb5-8"><span class="co" style="color: #5E5E5E;">#   Rscript riskmetric-demo.R</span></span>
<span id="cb5-9"></span>
<span id="cb5-10"><span class="fu" style="color: #4758AB;">suppressPackageStartupMessages</span>({</span>
<span id="cb5-11">  <span class="fu" style="color: #4758AB;">library</span>(riskmetric)</span>
<span id="cb5-12">  <span class="fu" style="color: #4758AB;">library</span>(dplyr)</span>
<span id="cb5-13">})</span>
<span id="cb5-14"></span>
<span id="cb5-15"><span class="co" style="color: #5E5E5E;">#' Return a list of assessment functions that execute offline</span></span>
<span id="cb5-16"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-17"><span class="co" style="color: #5E5E5E;">#' Selects assessments from {riskmetric} that inspect local installation</span></span>
<span id="cb5-18"><span class="co" style="color: #5E5E5E;">#' directories and DESCRIPTION metadata without querying remote APIs (such as</span></span>
<span id="cb5-19"><span class="co" style="color: #5E5E5E;">#' CRAN check servers, GitHub issue trackers, or download logs).</span></span>
<span id="cb5-20"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-21"><span class="co" style="color: #5E5E5E;">#' @return A named list of assessment functions.</span></span>
<span id="cb5-22">offline_assessments <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb5-23">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb5-24">    <span class="at" style="color: #657422;">has_news =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_news,</span>
<span id="cb5-25">    <span class="at" style="color: #657422;">news_current =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_news_current,</span>
<span id="cb5-26">    <span class="at" style="color: #657422;">has_vignettes =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_vignettes,</span>
<span id="cb5-27">    <span class="at" style="color: #657422;">export_help =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_export_help,</span>
<span id="cb5-28">    <span class="at" style="color: #657422;">has_website =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_website,</span>
<span id="cb5-29">    <span class="at" style="color: #657422;">has_maintainer =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_maintainer,</span>
<span id="cb5-30">    <span class="at" style="color: #657422;">has_source_control =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_source_control,</span>
<span id="cb5-31">    <span class="at" style="color: #657422;">has_bug_reports_url =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_bug_reports_url,</span>
<span id="cb5-32">    <span class="at" style="color: #657422;">has_examples =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_has_examples,</span>
<span id="cb5-33">    <span class="at" style="color: #657422;">dependencies =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_dependencies,</span>
<span id="cb5-34">    <span class="at" style="color: #657422;">license =</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span>assess_license</span>
<span id="cb5-35">  )</span>
<span id="cb5-36">}</span>
<span id="cb5-37"></span>
<span id="cb5-38"><span class="co" style="color: #5E5E5E;">#' Assess installed packages without network access</span></span>
<span id="cb5-39"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-40"><span class="co" style="color: #5E5E5E;">#' @param pkgs Character vector of installed package names.</span></span>
<span id="cb5-41"><span class="co" style="color: #5E5E5E;">#' @param assessments Named list of assessment functions. Defaults to</span></span>
<span id="cb5-42"><span class="co" style="color: #5E5E5E;">#'   offline assessments.</span></span>
<span id="cb5-43"><span class="co" style="color: #5E5E5E;">#' @param lib_loc Optional library path. Defaults to `.libPaths()[1]`.</span></span>
<span id="cb5-44"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-45"><span class="co" style="color: #5E5E5E;">#' @return A tibble of scored assessments with package metadata and</span></span>
<span id="cb5-46"><span class="co" style="color: #5E5E5E;">#'   an aggregate `pkg_score` column.</span></span>
<span id="cb5-47">assess_installed_packages <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb5-48">  pkgs,</span>
<span id="cb5-49">  <span class="at" style="color: #657422;">assessments =</span> <span class="fu" style="color: #4758AB;">offline_assessments</span>(),</span>
<span id="cb5-50">  <span class="at" style="color: #657422;">lib_loc =</span> <span class="cn" style="color: #8f5902;">NULL</span></span>
<span id="cb5-51">) {</span>
<span id="cb5-52">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(pkgs) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb5-53">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"At least one package name must be provided."</span>)</span>
<span id="cb5-54">  }</span>
<span id="cb5-55"></span>
<span id="cb5-56">  refs <span class="ot" style="color: #003B4F;">&lt;-</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pkg_ref</span>(</span>
<span id="cb5-57">    pkgs,</span>
<span id="cb5-58">    <span class="at" style="color: #657422;">source =</span> <span class="st" style="color: #20794D;">"pkg_install"</span>,</span>
<span id="cb5-59">    <span class="at" style="color: #657422;">lib.loc =</span> lib_loc</span>
<span id="cb5-60">  )</span>
<span id="cb5-61"></span>
<span id="cb5-62">  assessed <span class="ot" style="color: #003B4F;">&lt;-</span> riskmetric<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pkg_assess</span>(refs, <span class="at" style="color: #657422;">assessments =</span> assessments)</span>
<span id="cb5-63">  riskmetric<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pkg_score</span>(assessed)</span>
<span id="cb5-64">}</span>
<span id="cb5-65"></span>
<span id="cb5-66"><span class="co" style="color: #5E5E5E;">#' Classify a numeric risk score against organizational thresholds</span></span>
<span id="cb5-67"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-68"><span class="co" style="color: #5E5E5E;">#' In {riskmetric}, risk ranges from 0 (lowest risk / highest quality)</span></span>
<span id="cb5-69"><span class="co" style="color: #5E5E5E;">#' to 1 (highest risk / lowest quality).</span></span>
<span id="cb5-70"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-71"><span class="co" style="color: #5E5E5E;">#' @param score Numeric risk score in [0, 1] or NA.</span></span>
<span id="cb5-72"><span class="co" style="color: #5E5E5E;">#' @param low_threshold Numeric upper bound for low risk (inclusive).</span></span>
<span id="cb5-73"><span class="co" style="color: #5E5E5E;">#' @param medium_threshold Numeric upper bound for medium risk (inclusive).</span></span>
<span id="cb5-74"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-75"><span class="co" style="color: #5E5E5E;">#' @return A character vector of risk categories: "Low Risk", "Medium Risk",</span></span>
<span id="cb5-76"><span class="co" style="color: #5E5E5E;">#'   "High Risk", or "Unassessed".</span></span>
<span id="cb5-77">classify_risk <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb5-78">  score,</span>
<span id="cb5-79">  <span class="at" style="color: #657422;">low_threshold =</span> <span class="fl" style="color: #AD0000;">0.25</span>,</span>
<span id="cb5-80">  <span class="at" style="color: #657422;">medium_threshold =</span> <span class="fl" style="color: #AD0000;">0.50</span></span>
<span id="cb5-81">) {</span>
<span id="cb5-82">  <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb5-83">    <span class="fu" style="color: #4758AB;">is.na</span>(score),</span>
<span id="cb5-84">    <span class="st" style="color: #20794D;">"Unassessed"</span>,</span>
<span id="cb5-85">    <span class="fu" style="color: #4758AB;">ifelse</span>(</span>
<span id="cb5-86">      score <span class="sc" style="color: #5E5E5E;">&lt;=</span> low_threshold,</span>
<span id="cb5-87">      <span class="st" style="color: #20794D;">"Low Risk"</span>,</span>
<span id="cb5-88">      <span class="fu" style="color: #4758AB;">ifelse</span>(score <span class="sc" style="color: #5E5E5E;">&lt;=</span> medium_threshold, <span class="st" style="color: #20794D;">"Medium Risk"</span>, <span class="st" style="color: #20794D;">"High Risk"</span>)</span>
<span id="cb5-89">    )</span>
<span id="cb5-90">  )</span>
<span id="cb5-91">}</span>
<span id="cb5-92"></span>
<span id="cb5-93"><span class="co" style="color: #5E5E5E;">#' Summarise scored packages into a decision table</span></span>
<span id="cb5-94"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-95"><span class="co" style="color: #5E5E5E;">#' @param scored_tbl Tibble returned by `assess_installed_packages()`.</span></span>
<span id="cb5-96"><span class="co" style="color: #5E5E5E;">#' @param low_threshold Numeric upper bound for low risk.</span></span>
<span id="cb5-97"><span class="co" style="color: #5E5E5E;">#' @param medium_threshold Numeric upper bound for medium risk.</span></span>
<span id="cb5-98"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-99"><span class="co" style="color: #5E5E5E;">#' @return A tibble with package identity, risk score, decision category,</span></span>
<span id="cb5-100"><span class="co" style="color: #5E5E5E;">#'   and selected individual metric scores.</span></span>
<span id="cb5-101">summarise_package_risks <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb5-102">  scored_tbl,</span>
<span id="cb5-103">  <span class="at" style="color: #657422;">low_threshold =</span> <span class="fl" style="color: #AD0000;">0.25</span>,</span>
<span id="cb5-104">  <span class="at" style="color: #657422;">medium_threshold =</span> <span class="fl" style="color: #AD0000;">0.50</span></span>
<span id="cb5-105">) {</span>
<span id="cb5-106">  scored_tbl <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb5-107">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mutate</span>(</span>
<span id="cb5-108">      <span class="at" style="color: #657422;">decision =</span> <span class="fu" style="color: #4758AB;">classify_risk</span>(</span>
<span id="cb5-109">        .data<span class="sc" style="color: #5E5E5E;">$</span>pkg_score,</span>
<span id="cb5-110">        <span class="at" style="color: #657422;">low_threshold =</span> low_threshold,</span>
<span id="cb5-111">        <span class="at" style="color: #657422;">medium_threshold =</span> medium_threshold</span>
<span id="cb5-112">      )</span>
<span id="cb5-113">    ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb5-114">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">select</span>(</span>
<span id="cb5-115">      <span class="st" style="color: #20794D;">"package"</span>,</span>
<span id="cb5-116">      <span class="st" style="color: #20794D;">"version"</span>,</span>
<span id="cb5-117">      <span class="st" style="color: #20794D;">"pkg_score"</span>,</span>
<span id="cb5-118">      <span class="st" style="color: #20794D;">"decision"</span>,</span>
<span id="cb5-119">      <span class="st" style="color: #20794D;">"has_news"</span>,</span>
<span id="cb5-120">      <span class="st" style="color: #20794D;">"news_current"</span>,</span>
<span id="cb5-121">      <span class="st" style="color: #20794D;">"export_help"</span>,</span>
<span id="cb5-122">      <span class="st" style="color: #20794D;">"has_vignettes"</span>,</span>
<span id="cb5-123">      <span class="st" style="color: #20794D;">"dependencies"</span>,</span>
<span id="cb5-124">      <span class="st" style="color: #20794D;">"license"</span></span>
<span id="cb5-125">    )</span>
<span id="cb5-126">}</span>
<span id="cb5-127"></span>
<span id="cb5-128"><span class="co" style="color: #5E5E5E;">#' Run the complete offline risk assessment demonstration</span></span>
<span id="cb5-129"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-130"><span class="co" style="color: #5E5E5E;">#' @param pkgs Character vector of installed packages to evaluate.</span></span>
<span id="cb5-131"><span class="co" style="color: #5E5E5E;">#'   Defaults to three packages from the local library: glue, cards, riskmetric.</span></span>
<span id="cb5-132"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb5-133"><span class="co" style="color: #5E5E5E;">#' @return A tibble containing the scored assessment and decision table.</span></span>
<span id="cb5-134">run_riskmetric_demo <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">pkgs =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"glue"</span>, <span class="st" style="color: #20794D;">"cards"</span>, <span class="st" style="color: #20794D;">"riskmetric"</span>)) {</span>
<span id="cb5-135">  scored <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">assess_installed_packages</span>(pkgs)</span>
<span id="cb5-136">  <span class="fu" style="color: #4758AB;">summarise_package_risks</span>(scored)</span>
<span id="cb5-137">}</span>
<span id="cb5-138"></span>
<span id="cb5-139"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb5-140">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Assessing installed packages offline with {riskmetric}..."</span>)</span>
<span id="cb5-141">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_riskmetric_demo</span>()</span>
<span id="cb5-142">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">as.data.frame</span>(results))</span>
<span id="cb5-143">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards and organisations</strong></p>
<ul>
<li><strong>R Validation Hub</strong>: <a href="https://pharmar.org/">pharmar.org</a></li>
<li><strong>R Validation Hub white paper</strong> (<em>A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure</em>, Nicholls, Bargo &amp; Sims, 2020): <a href="https://pharmar.org/white-paper/">pharmar.org/white-paper</a></li>
<li><strong>GAMP 5 (2nd Edition)</strong>: <a href="https://ispe.org/publications/guidance-documents/gamp-5-guide-2nd-edition">ispe.org</a></li>
<li><strong>OpenSSF Scorecard</strong>: <a href="https://scorecard.dev">scorecard.dev</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>riskmetric</strong>: <a href="https://pharmar.github.io/riskmetric/">pharmar.github.io/riskmetric</a></li>
<li><strong>riskassessment</strong>: <a href="https://pharmar.github.io/riskassessment/">pharmar.github.io/riskassessment</a></li>
<li><strong>dplyr</strong>: <a href="https://dplyr.tidyverse.org/">dplyr.tidyverse.org</a></li>
</ul>
<section id="further-reading" class="level3">
<h3 class="anchored">Further reading</h3>
<p>References worth reading alongside this post (official documents, linked for context rather than quoted line by line):</p>
<ul>
<li><strong>FDA, <em>General Principles of Software Validation</em> (guidance, 2002)</strong>: <a href="https://www.fda.gov/regulatory-information/search-fda-guidance-documents/general-principles-software-validation">fda.gov</a></li>
<li><strong>FDA, <em>Statistical Software Clarifying Statement</em> (6 May 2015, PDF)</strong>: <a href="https://www.fda.gov/media/161196/download">fda.gov</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-series-nav__series">Pharma series · part 5 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/cdisc-ars-siera/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 4</span><span class="site-related-card__title">The CDISC Analysis Results Standard and {siera}</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 6</span><span class="site-related-card__title">QC and double programming with {diffdf}</span></a>
</div>
</div>
</div>
<section id="also-in" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="also-in">Also in</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/series/package-dev.html" class="site-link-row" title="Turn scripts into a package, then document, check, share and evolve it. The later parts cover object systems and compiled code."><span class="is-card__eyebrow site-link-row__label">Series · 4 parts</span><span class="site-link-row__title">R package development series</span></a></li>
</ul>
</div>
</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html" class="site-link-row" title="Manage dependencies through lockfiles, runtime pinning, and package vetting for reproducible R environments."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Dependency updates, runtime pinning &amp; package vetting</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="site-link-row" title="Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices."><span class="is-card__eyebrow site-link-row__label">Builds on</span><span class="site-link-row__title">Coverage and tests as evidence</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html" class="site-link-row" title="Adopt semantic versioning, readable changelogs, and annotated git tags to support change control."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Releases &amp; changelogs</span></a></li>
</ul>
</div>
</section>
</div>

</section>
</section>

 ]]></description>
  <category>Pharma</category>
  <category>R packages</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/validation-ready-r-packages/</guid>
  <pubDate>Sat, 26 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>ADRs &amp; evidence: record decisions, verify docs</title>
  <link>https://insightsurge-dev.web.app/posts/adrs-and-evidence/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="architecture-decision-records" class="level2">
<h2 class="anchored" data-anchor-id="architecture-decision-records">Architecture Decision Records</h2>
<p>Six months from now someone will ask <em>“why didn’t we use Astro?”</em> or <em>“why is there no JSON key for deploys?”</em>. An <strong>ADR</strong> is a short file that answers that question permanently.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb1-1"><span class="fu" style="color: #4758AB;"># ADR-0003: Secrets management</span></span>
<span id="cb1-2"><span class="ss" style="color: #20794D;">- </span>**Status:** Accepted</span>
<span id="cb1-3"><span class="ss" style="color: #20794D;">- </span>**Date:** 2026-09-26</span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;">## Context      (what forced a decision; constraints)</span></span>
<span id="cb1-6"><span class="fu" style="color: #4758AB;">## Decision     (what we chose, specifically)</span></span>
<span id="cb1-7"><span class="fu" style="color: #4758AB;">## Alternatives (what we rejected, and why)</span></span>
<span id="cb1-8"><span class="fu" style="color: #4758AB;">## Consequences (what gets easier or harder, and what to watch)</span></span></code></pre></div></div>
<p>Rules that keep ADRs useful:</p>
<ul>
<li><strong>One decision per file</strong>, numbered: <code>docs/adr/0001-stack-and-hosting.md</code>.</li>
<li><strong>Immutable once accepted.</strong> To change your mind, write a new ADR that <em>supersedes</em> the old one, and mark the old one <em>Superseded by ADR-00NN</em>. The history of your thinking is the point.</li>
<li><strong>Short.</strong> One page. Link out for detail.</li>
<li><strong>Reviewed in a PR</strong> like code, so the decision has an approver and a date.</li>
</ul>
<p>Our website started with five: stack and hosting, visual direction (pending), secrets, handoffs, and identity isolation.</p>
</section>
<section id="the-r-gxp-angle" class="level2">
<h2 class="anchored" data-anchor-id="the-r-gxp-angle">The R / GxP angle</h2>
<p>Validation packages already contain design rationale, but it’s usually written once, at the end. ADRs capture it <strong>when the decision is made</strong>, next to the code, with the review trail. They map to:</p>
<div class="table-responsive">
<table class="caption-top table">
<thead>
<tr class="header">
<th>Validation artefact</th>
<th>ADR equivalent</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Design specification rationale</td>
<td>Decision + Alternatives</td>
</tr>
<tr class="even">
<td>Risk assessment inputs</td>
<td>Context + Consequences</td>
</tr>
<tr class="odd">
<td>Change control record</td>
<td>The PR that added or superseded the ADR</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Where to put them in an R package:</strong> not in <code>docs/</code>. That’s where <strong>pkgdown</strong> writes the site by default, so the two collide. Use <code>adr/</code> (or <code>design/adr/</code>) at the root with a README index, and <code>usethis::use_build_ignore("adr")</code> so they stay out of the tarball.</p>
</section>
<section id="evidence-verify-documentation-before-you-trust-it" class="level2">
<h2 class="anchored" data-anchor-id="evidence-verify-documentation-before-you-trust-it">Evidence: verify documentation before you trust it</h2>
<p>Decisions are only as good as the facts under them. Setting up this project, we hit several cases where the obvious source was wrong or incomplete:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Claim</th>
<th>What we found</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>“Firebase App Hosting supports Next.js up to 15.2” (support table)</td>
<td>The table was stale. Firebase’s blog and the Next.js docs showed 16.2+ supported via the adapter API</td>
</tr>
<tr class="even">
<td>“Blank issues disabled means nobody can open one”</td>
<td>GitHub’s own page says both things; the detailed note says maintainers still see a blank option</td>
</tr>
<tr class="odd">
<td>“<code>~/.Renviron</code> and a project <code>.Renviron</code> combine”</td>
<td>Tested with two files: the project one <strong>replaces</strong> the home one</td>
</tr>
<tr class="even">
<td>“<code>gh</code> uses <code>GITHUB_PAT</code>”</td>
<td>Tested: <code>GITHUB_PAT_GITHUB_COM</code> wins over <code>GITHUB_PAT</code>, which wins over the credential helper</td>
</tr>
<tr class="odd">
<td>“<code>usethis::git_vaccinate()</code> protects <code>.Renviron</code>”</td>
<td>Read the list it writes: it doesn’t</td>
</tr>
<tr class="even">
<td>“Setting <code>.Last &lt;- function() NULL</code> stops history saving”</td>
<td>A draft claim that was wrong. Caught in review and removed</td>
</tr>
</tbody>
</table>
</div>
<p>Habits:</p>
<ol type="1">
<li><strong>Prefer running it to reading about it.</strong> Ten seconds with <code>Rscript -e</code> beats any blog post.</li>
<li><strong>Primary sources over summaries.</strong> Official docs, source code, <code>NEWS.md</code>, and the package’s own help.</li>
<li><strong>When sources disagree, record both</strong> and what you did about it, in the ADR’s Context.</li>
<li><strong>Date your evidence.</strong> “Checked 2026-09-26” tells a future reader when to re-check.</li>
<li><strong>Treat AI-written claims like any other secondary source</strong>, including your own assistant’s. Verify, or mark them <em>unverified</em>.</li>
</ol>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<ul>
<li><strong>Architecture Decision Records</strong>: <a href="https://adr.github.io/">adr.github.io</a></li>
<li><strong>pkgdown</strong> (the reason ADRs shouldn’t live in <code>docs/</code> in an R package): <a href="https://pkgdown.r-lib.org/">pkgdown.r-lib.org</a></li>
<li><strong>usethis</strong> (<code>use_build_ignore()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
<li><strong>“Blank issues disabled” still lets write-access users open a blank issue</strong>: <a href="https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository">GitHub Docs: Configuring issue templates for your repository</a></li>
<li><strong><code>gh</code>/<code>usethis</code> GitHub token lookup order (<code>GITHUB_PAT_GITHUB_COM</code> before <code>GITHUB_PAT</code> before the credential helper)</strong>: <a href="https://gh.r-lib.org/">gh.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 12 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/test-your-guardrails/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 11</span><span class="site-related-card__title">Test your guardrails: probe PRs</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/repo-hygiene-files/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 13</span><span class="site-related-card__title">Repo hygiene files</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="site-link-row" title="Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Coverage and tests as evidence</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/two-model-workflow/index.html" class="site-link-row" title="Structure dual-model AI workflows with clear task ownership, written briefs, and human verification to maintain engineering rigor."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">One owner, two models: delegating to a second AI and verifying it</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/index.html" class="site-link-row" title="The mascot package is now on CRAN: add mood-driven characters to Shiny apps and Quarto pages, with visible status text, speech bubbles, click menus and reduced-motion support."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">mascot is on CRAN: live, mood-driven mascots for Shiny and Quarto</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>GxP</category>
  <category>Best practices</category>
  <category>R packages</category>
  <guid>https://insightsurge-dev.web.app/posts/adrs-and-evidence/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Analysis Results Data in R with {cards} and {cardx}</title>
  <link>https://insightsurge-dev.web.app/posts/analysis-results-data-cards/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>In traditional clinical reporting workflows, statistical calculations are trapped inside presentation scripts. A single program reads an ADaM dataset, subsets the population, computes descriptive metrics, concatenates them into formatted strings like <code>"75.2 (8.6)"</code>, and writes pagination control codes for an RTF document.</p>
<p>This coupling creates three recurring engineering bottlenecks:</p>
<ul>
<li><strong>Calculations cannot be re-used</strong>: A statistic computed for a baseline demographic table cannot be ingested by an executive slide deck, a patient profile listing, or an interactive Shiny safety dashboard. Each deliverable recalculates the metric independently, creating opportunities for divergent filtering or rounding.</li>
<li><strong>Cross-table reconciliation requires manual archaeology</strong>: When the safety population count in Table 14.1.1 differs from the denominator in Table 14.3.1, programmers must trace through nested formatting macros to locate where derivation logic diverged.</li>
<li><strong>Quality control diffs layout instead of data</strong>: In independent double-programming, verification often relies on comparing rendered RTF files. Programmers end up investigating false positives caused by line wrapping, font sizes, or cell margins rather than focusing on numerical differences.</li>
</ul>
<p>When numbers are computed inside display code, they cease to exist as data.</p>
</section>
<section id="the-web-analogue" class="level2">
<h2 class="anchored" data-anchor-id="the-web-analogue">The web analogue</h2>
<p>Web development encountered this challenge when server-rendered pages embedded SQL queries directly inside HTML markup. Altering a visual component broke database queries, and sharing data across platforms required scraping HTML.</p>
<p>Modern web architectures resolved this by establishing strict data contracts:</p>
<pre class="text"><code>Database Layer ──&gt; [API Contract] ──&gt; Structured Data ──&gt; [Component Engine] ──&gt; Presentation
  (ADaM Data)        (cards / cardx)     (Typed ARD / JSON)    (tbl_ard_summary/tfrmt)   (RTF / HTML)</code></pre>
<p>In a decoupled web system:</p>
<ul>
<li>The backend service exposes a typed API returning structured JSON. It provides raw numeric values and metadata, without styling, fonts, or page breaks.</li>
<li>Multiple clients consume the exact same payload: a web application, a mobile client, a dashboard, and a scheduled email alert.</li>
<li>Client teams update CSS and layout templates without touching backend logic.</li>
</ul>
<p>Analysis Results Data (ARD) applies this exact pattern to clinical reporting. An ARD is an intermediate, typed dataset containing the calculated results of statistical analyses. Presentation engines consume the ARD to build formatted tables, but the calculations exist independently as auditable data.</p>
</section>
<section id="the-ard-shape-one-row-per-statistic" class="level2">
<h2 class="anchored" data-anchor-id="the-ard-shape-one-row-per-statistic">The ARD shape: one row per statistic</h2>
<p>In R, <a href="https://pharmaverse.github.io/cards/"><code>{cards}</code></a> defines the standard data structure for Analysis Results Data. Rather than storing results in wide, ad-hoc tables, a <code>{cards}</code> object (an S3 data frame of class <code>"card"</code>) stores results in a tidy structure where <strong>every row represents exactly one calculated statistic</strong>.</p>
<p>Here is what an ARD looks like when summarizing a continuous variable:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">library</span>(cards)</span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">library</span>(cardx)</span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;">library</span>(gtsummary)</span>
<span id="cb2-4"></span>
<span id="cb2-5">adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb2-6">adae_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adae, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb2-7"></span>
<span id="cb2-8">ard_age <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_continuous</span>(adsl_saf, <span class="at" style="color: #657422;">variables =</span> AGE)</span>
<span id="cb2-9"><span class="fu" style="color: #4758AB;">names</span>(ard_age)</span></code></pre></div></div>
<p><code>ard_age</code> has the core columns: <code>variable</code>, <code>context</code>, <code>stat_name</code>, <code>stat_label</code>, <code>stat</code>, <code>fmt_fun</code>, <code>warning</code> and <code>error</code>. Grouped ARDs add <code>group1</code>/<code>group1_level</code> (and <code>group2</code>, … for nesting), and categorical ones add <code>variable_level</code>:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Column</th>
<th>Type</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>variable</code></td>
<td><code>character</code></td>
<td>The variable being analyzed (for example <code>"AGE"</code>).</td>
</tr>
<tr class="even">
<td><code>variable_level</code></td>
<td><code>list</code></td>
<td>The level of a categorical variable (for example <code>"F"</code>); not present for continuous summaries.</td>
</tr>
<tr class="odd">
<td><code>group1</code>, <code>group1_level</code></td>
<td><code>character</code>, <code>list</code></td>
<td>Grouping variable name and value (for example <code>TRT01A</code> and <code>"Placebo"</code>). Repeated as <code>group2</code>, <code>group3</code> for nested stratifications.</td>
</tr>
<tr class="even">
<td><code>context</code></td>
<td><code>character</code></td>
<td>The analytical context generating the row (such as <code>"continuous"</code>, <code>"categorical"</code>, <code>"dichotomous"</code>, or <code>"stats_t_test"</code>).</td>
</tr>
<tr class="odd">
<td><code>stat_name</code></td>
<td><code>character</code></td>
<td>The machine-readable identifier for the statistic (such as <code>"mean"</code>, <code>"sd"</code>, <code>"median"</code>, <code>"p25"</code>, <code>"n"</code>, <code>"p"</code>).</td>
</tr>
<tr class="even">
<td><code>stat_label</code></td>
<td><code>character</code></td>
<td>The human-readable label for display (such as <code>"Mean"</code>, <code>"SD"</code>, <code>"Median"</code>, <code>"Q1"</code>, <code>"n"</code>, <code>"%"</code>).</td>
</tr>
<tr class="odd">
<td><code>stat</code></td>
<td><code>list</code></td>
<td>The unrounded calculated statistic value. Stored in a list-column to hold diverse types (scalars, vectors, or test estimates).</td>
</tr>
<tr class="even">
<td><code>fmt_fun</code></td>
<td><code>list</code></td>
<td>The formatting rule, represented as an integer specifying decimal places or a custom function.</td>
</tr>
<tr class="odd">
<td><code>warning</code></td>
<td><code>list</code></td>
<td>Warning condition objects captured during calculation, or <code>NULL</code>.</td>
</tr>
<tr class="even">
<td><code>error</code></td>
<td><code>list</code></td>
<td>Error condition objects captured during calculation, or <code>NULL</code>.</td>
</tr>
</tbody>
</table>
</div>
<section id="resilient-computation-with-warning-and-error" class="level3">
<h3 class="anchored" data-anchor-id="resilient-computation-with-warning-and-error">Resilient computation with <code>warning</code> and <code>error</code></h3>
<p>A notable engineering feature of <code>{cards}</code> is how it handles calculation issues. In traditional monolithic scripts, an unhandled warning is buried in console logs, and an unexpected error crashes the entire reporting run.</p>
<p>In <code>{cards}</code>, every statistic calculation is wrapped in condition handlers. If a calculation produces a warning or error, <code>{cards}</code> records the condition object directly into the <code>warning</code> or <code>error</code> list-columns, assigns <code>NULL</code> to <code>stat</code> in the case of errors, and continues processing the remaining variables. You can audit all captured conditions across an ARD at any point:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">print_ard_conditions</span>(ard_age)</span></code></pre></div></div>
<p>This turns diagnostic evaluation into an inspectable data operation.</p>
</section>
</section>
<section id="building-ards-with-cards" class="level2">
<h2 class="anchored" data-anchor-id="building-ards-with-cards">Building ARDs with {cards}</h2>
<p>The <code>{cards}</code> package provides composable functions to build ARDs across clinical data types.</p>
<section id="univariate-building-blocks" class="level3">
<h3 class="anchored" data-anchor-id="univariate-building-blocks">Univariate building blocks</h3>
<p>You can generate individual summaries for continuous, categorical, and dichotomous variables:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># Continuous summary: N, mean, sd, median, p25, p75, min, max</span></span>
<span id="cb4-2">ard_cont <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_continuous</span>(adsl_saf, <span class="at" style="color: #657422;">variables =</span> AGE)</span>
<span id="cb4-3"></span>
<span id="cb4-4"><span class="co" style="color: #5E5E5E;"># Categorical tabulation: counts (n), denominators (N), and proportions (p)</span></span>
<span id="cb4-5">ard_cat <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_categorical</span>(adsl_saf, <span class="at" style="color: #657422;">variables =</span> SEX)</span>
<span id="cb4-6"></span>
<span id="cb4-7"><span class="co" style="color: #5E5E5E;"># Dichotomous summary: counts and rates for a single target level</span></span>
<span id="cb4-8">ard_dich <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_dichotomous</span>(</span>
<span id="cb4-9">  adsl_saf,</span>
<span id="cb4-10">  <span class="at" style="color: #657422;">variables =</span> SEX,</span>
<span id="cb4-11">  <span class="at" style="color: #657422;">value =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">SEX =</span> <span class="st" style="color: #20794D;">"F"</span>)</span>
<span id="cb4-12">)</span></code></pre></div></div>
</section>
<section id="stacking-tables-with-ard_stack" class="level3">
<h3 class="anchored" data-anchor-id="stacking-tables-with-ard_stack">Stacking tables with <code>ard_stack()</code></h3>
<p>In production reporting, tables combine multiple variables stratified by treatment arms, along with overall population summaries and total counts. Rather than calling individual functions and joining them by hand, <code>ard_stack()</code> compiles a complete study table ARD in a single pass:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">ard_demo <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_stack</span>(</span>
<span id="cb5-2">  <span class="at" style="color: #657422;">data =</span> adsl_saf,</span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;">ard_continuous</span>(<span class="at" style="color: #657422;">variables =</span> AGE),</span>
<span id="cb5-4">  <span class="fu" style="color: #4758AB;">ard_categorical</span>(<span class="at" style="color: #657422;">variables =</span> SEX),</span>
<span id="cb5-5">  <span class="at" style="color: #657422;">.by =</span> TRT01A,</span>
<span id="cb5-6">  <span class="at" style="color: #657422;">.overall =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb5-7">  <span class="at" style="color: #657422;">.total_n =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb5-8">  <span class="at" style="color: #657422;">.attributes =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb5-9">)</span>
<span id="cb5-10"></span>
<span id="cb5-11"><span class="fu" style="color: #4758AB;">unique</span>(ard_demo<span class="sc" style="color: #5E5E5E;">$</span>context)</span></code></pre></div></div>
<p>The arguments to <code>ard_stack()</code> configure the clinical layout:</p>
<ul>
<li><code>.by</code>: The stratification variable (<code>TRT01A</code>), generating separate statistics for each treatment arm.</li>
<li><code>.overall = TRUE</code>: Re-runs the calculations without stratification, adding an overall column.</li>
<li><code>.total_n = TRUE</code>: Appends population counts from <code>ard_total_n()</code>.</li>
<li><code>.attributes = TRUE</code>: Extracts column labels from the input data frame via <code>ard_attributes()</code>, preserving CDISC variable labels for the display layer.</li>
</ul>
</section>
<section id="hierarchical-adverse-events-ard_stack_hierarchical" class="level3">
<h3 class="anchored" data-anchor-id="hierarchical-adverse-events-ard_stack_hierarchical">Hierarchical adverse events: <code>ard_stack_hierarchical()</code></h3>
<p>Adverse event tables require calculating nested participant incidences: first at the System Organ Class (SOC) level, and then for each Preferred Term (PT) within that SOC. A participant experiencing multiple occurrences of the same event should only be counted once in the numerator.</p>
<p><code>{cards}</code> handles this with <code>ard_stack_hierarchical()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">ard_ae <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_stack_hierarchical</span>(</span>
<span id="cb6-2">  <span class="at" style="color: #657422;">data =</span> adae_saf,</span>
<span id="cb6-3">  <span class="at" style="color: #657422;">variables =</span> <span class="fu" style="color: #4758AB;">c</span>(AEBODSYS, AEDECOD),</span>
<span id="cb6-4">  <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb6-5">  <span class="at" style="color: #657422;">denominator =</span> adsl_saf,</span>
<span id="cb6-6">  <span class="at" style="color: #657422;">id =</span> USUBJID</span>
<span id="cb6-7">)</span></code></pre></div></div>
<p>By providing <code>denominator = adsl_saf</code> and <code>id = USUBJID</code>, <code>ard_stack_hierarchical()</code> dedupes adverse events per participant within each hierarchical level (<code>AEBODSYS</code> and <code>AEDECOD</code>) and divides by the safety population count for each treatment arm.</p>
</section>
</section>
<section id="statistical-testing-with-cardx" class="level2">
<h2 class="anchored" data-anchor-id="statistical-testing-with-cardx">Statistical testing with {cardx}</h2>
<p>Descriptive statistics cover baseline demographics, but regulatory tables and exploratory reports frequently require inferential statistics: p-values, confidence intervals, and hypothesis tests.</p>
<p><a href="https://insightsengineering.github.io/cardx/"><code>{cardx}</code></a> extends <code>{cards}</code> by wrapping common statistical tests into ARD-generating functions:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="co" style="color: #5E5E5E;"># Pearson's chi-squared test across treatment arms</span></span>
<span id="cb7-2">ard_chisq <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_stats_chisq_test</span>(</span>
<span id="cb7-3">  adsl_saf,</span>
<span id="cb7-4">  <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb7-5">  <span class="at" style="color: #657422;">variables =</span> SEX</span>
<span id="cb7-6">)</span>
<span id="cb7-7"></span>
<span id="cb7-8"><span class="co" style="color: #5E5E5E;"># Two-sample Welch t-test comparing two specific arms</span></span>
<span id="cb7-9">adsl_2arms <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(adsl_saf, TRT01A <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"Placebo"</span>, <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>))</span>
<span id="cb7-10">ard_ttest <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_stats_t_test</span>(</span>
<span id="cb7-11">  adsl_2arms,</span>
<span id="cb7-12">  <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb7-13">  <span class="at" style="color: #657422;">variables =</span> AGE</span>
<span id="cb7-14">)</span></code></pre></div></div>
<p>Because <code>{cardx}</code> functions return standard <code>"card"</code> data frames, they bind directly with descriptive ARDs using <code>cards::bind_ard()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">ard_combined <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">bind_ard</span>(ard_demo, ard_chisq)</span></code></pre></div></div>
<p>The combined ARD contains both descriptive summaries and inferential test statistics, stored with their respective <code>context</code>, <code>stat_name</code>, and calculated <code>stat</code> values.</p>
</section>
<section id="working-with-an-ard" class="level2">
<h2 class="anchored" data-anchor-id="working-with-an-ard">Working with an ARD</h2>
<p>Once generated, an ARD can be formatted, filtered, extracted, or reshaped for downstream use.</p>
<section id="applying-formatting-functions" class="level3">
<h3 class="anchored" data-anchor-id="applying-formatting-functions">Applying formatting functions</h3>
<p>The <code>stat</code> column stores unrounded raw numbers. To prepare an ARD for tabular display, <code>apply_fmt_fun()</code> evaluates the formatting rule in <code>fmt_fun</code> and creates a <code>stat_fmt</code> column containing formatted character strings:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">ard_formatted <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">apply_fmt_fun</span>(ard_demo)</span></code></pre></div></div>
<p>If study requirements demand custom decimal precision (such as reporting means to two decimal places instead of one), you can update the formatting rules using <code>update_ard_fmt_fun()</code> prior to formatting:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">ard_custom <span class="ot" style="color: #003B4F;">&lt;-</span> ard_demo <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb10-2">  <span class="fu" style="color: #4758AB;">update_ard_fmt_fun</span>(<span class="at" style="color: #657422;">stat_names =</span> <span class="st" style="color: #20794D;">"mean"</span>, <span class="at" style="color: #657422;">fmt_fun =</span> <span class="dv" style="color: #AD0000;">2</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb10-3">  <span class="fu" style="color: #4758AB;">apply_fmt_fun</span>()</span></code></pre></div></div>
</section>
<section id="filtering-and-extracting-statistics" class="level3">
<h3 class="anchored" data-anchor-id="filtering-and-extracting-statistics">Filtering and extracting statistics</h3>
<p>Because an ARD is an S3 data frame, you can filter rows using standard <code>dplyr::filter()</code> without stripping the <code>"card"</code> class:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">ard_filtered <span class="ot" style="color: #003B4F;">&lt;-</span> ard_demo <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb11-2">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">filter</span>(stat_name <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"mean"</span>, <span class="st" style="color: #20794D;">"sd"</span>, <span class="st" style="color: #20794D;">"n"</span>, <span class="st" style="color: #20794D;">"p"</span>))</span></code></pre></div></div>
<p>To extract specific values into a named list—for example when inserting verified numbers into a narrative clinical report—use <code>get_ard_statistics()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">mean_age <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">get_ard_statistics</span>(</span>
<span id="cb12-2">  ard_demo,</span>
<span id="cb12-3">  variable <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="st" style="color: #20794D;">"AGE"</span>,</span>
<span id="cb12-4">  stat_name <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="st" style="color: #20794D;">"mean"</span></span>
<span id="cb12-5">)</span></code></pre></div></div>
</section>
<section id="reshaping-for-review" class="level3">
<h3 class="anchored" data-anchor-id="reshaping-for-review">Reshaping for review</h3>
<p>While the one-row-per-statistic structure is ideal for computation and storage, human reviewers often prefer inspecting a flattened table. You can unflatten grouping levels and unnest statistics using <code>tfrmt::shuffle_card()</code> (which supersedes the deprecated <code>cards::shuffle_ard()</code>):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">ard_flat <span class="ot" style="color: #003B4F;">&lt;-</span> tfrmt<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">shuffle_card</span>(ard_demo, <span class="at" style="color: #657422;">by =</span> <span class="st" style="color: #20794D;">"TRT01A"</span>)</span></code></pre></div></div>
<p>This returns a rectangular tibble where each treatment arm forms a column and statistics are unnested for straightforward visual scanning.</p>
</section>
</section>
<section id="quality-control-comparing-ards-as-data" class="level2">
<h2 class="anchored" data-anchor-id="quality-control-comparing-ards-as-data">Quality control: comparing ARDs as data</h2>
<p>Double-programming is the cornerstone of clinical quality control. In legacy workflows, comparing two programmers’ outputs involves comparing RTF or PDF documents. Differences in column widths, font metrics, or line wraps introduce noise that obscures genuine calculation discrepancies.</p>
<p>In an ARD-first workflow, the primary programmer and the validation programmer each produce an independent ARD. Quality control becomes a direct data comparison:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="co" style="color: #5E5E5E;"># Programmer 1 (Primary)</span></span>
<span id="cb14-2">ard_p1 <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_stack</span>(</span>
<span id="cb14-3">  <span class="at" style="color: #657422;">data =</span> adsl_saf,</span>
<span id="cb14-4">  <span class="fu" style="color: #4758AB;">ard_continuous</span>(<span class="at" style="color: #657422;">variables =</span> AGE),</span>
<span id="cb14-5">  <span class="fu" style="color: #4758AB;">ard_categorical</span>(<span class="at" style="color: #657422;">variables =</span> SEX),</span>
<span id="cb14-6">  <span class="at" style="color: #657422;">.by =</span> TRT01A</span>
<span id="cb14-7">)</span>
<span id="cb14-8"></span>
<span id="cb14-9"><span class="co" style="color: #5E5E5E;"># Programmer 2 (Validation, with a discrepancy in Placebo mean age)</span></span>
<span id="cb14-10">ard_p2 <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_stack</span>(</span>
<span id="cb14-11">  <span class="at" style="color: #657422;">data =</span> adsl_saf,</span>
<span id="cb14-12">  <span class="fu" style="color: #4758AB;">ard_continuous</span>(<span class="at" style="color: #657422;">variables =</span> AGE),</span>
<span id="cb14-13">  <span class="fu" style="color: #4758AB;">ard_categorical</span>(<span class="at" style="color: #657422;">variables =</span> SEX),</span>
<span id="cb14-14">  <span class="at" style="color: #657422;">.by =</span> TRT01A</span>
<span id="cb14-15">)</span>
<span id="cb14-16">ard_p2<span class="sc" style="color: #5E5E5E;">$</span>stat[[<span class="dv" style="color: #AD0000;">2</span>]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fl" style="color: #AD0000;">74.0</span></span>
<span id="cb14-17"></span>
<span id="cb14-18"><span class="co" style="color: #5E5E5E;"># Compare as data</span></span>
<span id="cb14-19">waldo<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">compare</span>(ard_p1, ard_p2)</span></code></pre></div></div>
<p><code>waldo::compare()</code> inspects the underlying list-columns element by element, immediately pinpointing that element <code>[[2]]</code> of the <code>stat</code> column differs (<code>75.2</code> versus <code>74.0</code>). It ignores cosmetic layout differences and flags only divergent data.</p>
<p>For teams that prefer structured difference tables, <code>diffdf::diffdf()</code> can compare flattened data frames produced after unnesting or running <code>apply_fmt_fun()</code>.</p>
</section>
<section id="rendering-one-ard-several-ways" class="level2">
<h2 class="anchored" data-anchor-id="rendering-one-ard-several-ways">Rendering one ARD several ways</h2>
<p>Because the ARD represents verified data rather than presentation code, you can render it across different outputs without recomputing statistics:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">tbl_rendered <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tbl_ard_summary</span>(</span>
<span id="cb15-2">  <span class="at" style="color: #657422;">cards =</span> ard_demo,</span>
<span id="cb15-3">  <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb15-4">  <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">list</span>(AGE <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"Age (Years)"</span>, SEX <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"Sex"</span>)</span>
<span id="cb15-5">)</span></code></pre></div></div>
<p><code>gtsummary::tbl_ard_summary()</code> consumes the pre-computed ARD directly. You can convert the resulting object to a <code>{gt}</code> table with <code>gtsummary::as_gt()</code>, export it to RTF with <code>gt::gtsave()</code>, or render it to HTML.</p>
<p>Similarly, <a href="https://cran.r-project.org/package=tfrmt"><code>{tfrmt}</code></a> consumes pre-aggregated ARD tables and applies an external formatting shell, mapping columns, labels, and footnote plans without altering the calculated numbers.</p>
</section>
<section id="connection-to-the-cdisc-analysis-results-standard-ars" class="level2">
<h2 class="anchored" data-anchor-id="connection-to-the-cdisc-analysis-results-standard-ars">Connection to the CDISC Analysis Results Standard (ARS)</h2>
<p>Analysis Results Data in R aligns closely with wider industry efforts to standardize clinical analysis deliverables. The CDISC Analysis Results Standard (ARS) defines a machine-readable, vendor-neutral metadata model for describing planned analyses, their execution rules, and their final results.</p>
<p>It is important not to overclaim what <code>{cards}</code> does: <code>{cards}</code> provides an R-native tabular implementation of Analysis Results Data (a tidy data frame of class <code>"card"</code>), not a full CDISC ARS serializer. However, by decoupling statistical calculation from display and structuring every metric into standard columns (<code>variable</code>, <code>context</code>, <code>stat_name</code>, <code>stat</code>), <code>{cards}</code> prepares your clinical reporting pipeline for metadata-driven automation. The next post in this series explores the CDISC Analysis Results Standard (ARS) in detail.</p>
<p>The accompanying script <a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/scripts/ard-demo.R">scripts/ard-demo.R</a> builds a demographics ARD and an adverse-event ARD (by system organ class and preferred term) from {pharmaverseadam} with {cards}, adds a treatment comparison with {cardx}, and shows how comparing two ARDs catches a planted discrepancy.</p>
<div class="callout callout-style-simple callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Coming up in the Pharma series
</div>
</div>
<div class="callout-body-container callout-body">
<p>The next post explores the CDISC Analysis Results Standard (ARS) in depth, covering machine-readable analysis definitions and regulatory results metadata.</p>
</div>
</div>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/scripts/ard-demo.R">View <code>ard-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/scripts/ard-demo.R" download="ard-demo.R">Download</a></p>
<p>Builds a demographics ARD and an adverse-event ARD with <code>{cards}</code>, adds a treatment comparison with <code>{cardx}</code>, and uses <code>{waldo}</code> to catch a planted discrepancy between independent runs. Requires <code>{cards}</code>, <code>{cardx}</code>, <code>{pharmaverseadam}</code>, and <code>{waldo}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>ard-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="co" style="color: #5E5E5E;"># Analysis Results Data (ARD) with {cards} and {cardx}: a demographics ARD, an</span></span>
<span id="cb16-2"><span class="co" style="color: #5E5E5E;"># adverse-event ARD by system organ class and preferred term, a t-test, and a</span></span>
<span id="cb16-3"><span class="co" style="color: #5E5E5E;"># QC comparison that catches a planted discrepancy.</span></span>
<span id="cb16-4"><span class="co" style="color: #5E5E5E;"># Data: {pharmaverseadam} (example data, not real patients).</span></span>
<span id="cb16-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb16-6"><span class="co" style="color: #5E5E5E;">#   Rscript ard-demo.R</span></span>
<span id="cb16-7"></span>
<span id="cb16-8">safety_adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb16-9">  <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb16-10">}</span>
<span id="cb16-11"></span>
<span id="cb16-12">safety_adae <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb16-13">  <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adae, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb16-14">}</span>
<span id="cb16-15"></span>
<span id="cb16-16"><span class="co" style="color: #5E5E5E;"># Demographics: age and sex by actual treatment, plus an overall column.</span></span>
<span id="cb16-17">demog_ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(adsl) {</span>
<span id="cb16-18">  cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_stack</span>(</span>
<span id="cb16-19">    adsl,</span>
<span id="cb16-20">    cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_continuous</span>(<span class="at" style="color: #657422;">variables =</span> AGE),</span>
<span id="cb16-21">    cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_categorical</span>(<span class="at" style="color: #657422;">variables =</span> SEX),</span>
<span id="cb16-22">    <span class="at" style="color: #657422;">.by =</span> TRT01A,</span>
<span id="cb16-23">    <span class="at" style="color: #657422;">.overall =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb16-24">  )</span>
<span id="cb16-25">}</span>
<span id="cb16-26"></span>
<span id="cb16-27"><span class="co" style="color: #5E5E5E;"># Adverse events: subjects counted once per SOC and per PT, with the safety</span></span>
<span id="cb16-28"><span class="co" style="color: #5E5E5E;"># population as the denominator.</span></span>
<span id="cb16-29">ae_ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(adae, adsl) {</span>
<span id="cb16-30">  cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_stack_hierarchical</span>(</span>
<span id="cb16-31">    adae,</span>
<span id="cb16-32">    <span class="at" style="color: #657422;">variables =</span> <span class="fu" style="color: #4758AB;">c</span>(AEBODSYS, AEDECOD),</span>
<span id="cb16-33">    <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb16-34">    <span class="at" style="color: #657422;">denominator =</span> adsl,</span>
<span id="cb16-35">    <span class="at" style="color: #657422;">id =</span> USUBJID</span>
<span id="cb16-36">  )</span>
<span id="cb16-37">}</span>
<span id="cb16-38"></span>
<span id="cb16-39"><span class="co" style="color: #5E5E5E;"># A treatment comparison: Welch two-sample t-test of age, two arms.</span></span>
<span id="cb16-40">age_ttest_ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(adsl, <span class="at" style="color: #657422;">arms =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"Placebo"</span>, <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)) {</span>
<span id="cb16-41">  cardx<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_stats_t_test</span>(</span>
<span id="cb16-42">    adsl[adsl<span class="sc" style="color: #5E5E5E;">$</span>TRT01A <span class="sc" style="color: #5E5E5E;">%in%</span> arms, ],</span>
<span id="cb16-43">    <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb16-44">    <span class="at" style="color: #657422;">variables =</span> AGE</span>
<span id="cb16-45">  )</span>
<span id="cb16-46">}</span>
<span id="cb16-47"></span>
<span id="cb16-48"><span class="co" style="color: #5E5E5E;"># QC: an independent programmer's ARD, compared as data. waldo::compare()</span></span>
<span id="cb16-49"><span class="co" style="color: #5E5E5E;"># returns an empty result when the two agree.</span></span>
<span id="cb16-50">compare_ards <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(primary, qc) {</span>
<span id="cb16-51">  waldo<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">compare</span>(primary, qc, <span class="at" style="color: #657422;">x_arg =</span> <span class="st" style="color: #20794D;">"primary"</span>, <span class="at" style="color: #657422;">y_arg =</span> <span class="st" style="color: #20794D;">"qc"</span>)</span>
<span id="cb16-52">}</span>
<span id="cb16-53"></span>
<span id="cb16-54"><span class="co" style="color: #5E5E5E;"># For the demo: the QC programmer's Placebo mean age is slightly off.</span></span>
<span id="cb16-55">plant_discrepancy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(ard) {</span>
<span id="cb16-56">  row <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">which</span>(</span>
<span id="cb16-57">    ard<span class="sc" style="color: #5E5E5E;">$</span>variable <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"AGE"</span> <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb16-58">      ard<span class="sc" style="color: #5E5E5E;">$</span>stat_name <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"mean"</span> <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb16-59">      <span class="fu" style="color: #4758AB;">vapply</span>(ard<span class="sc" style="color: #5E5E5E;">$</span>group1_level, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) <span class="fu" style="color: #4758AB;">identical</span>(x, <span class="st" style="color: #20794D;">"Placebo"</span>), <span class="fu" style="color: #4758AB;">logical</span>(<span class="dv" style="color: #AD0000;">1</span>))</span>
<span id="cb16-60">  )</span>
<span id="cb16-61">  ard<span class="sc" style="color: #5E5E5E;">$</span>stat[[row]] <span class="ot" style="color: #003B4F;">&lt;-</span> ard<span class="sc" style="color: #5E5E5E;">$</span>stat[[row]] <span class="sc" style="color: #5E5E5E;">+</span> <span class="fl" style="color: #AD0000;">0.5</span></span>
<span id="cb16-62">  ard</span>
<span id="cb16-63">}</span>
<span id="cb16-64"></span>
<span id="cb16-65"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb16-66"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb16-67">  adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">safety_adsl</span>()</span>
<span id="cb16-68">  demog <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">demog_ard</span>(adsl)</span>
<span id="cb16-69">  <span class="fu" style="color: #4758AB;">print</span>(demog[demog<span class="sc" style="color: #5E5E5E;">$</span>stat_name <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"N"</span>, <span class="st" style="color: #20794D;">"mean"</span>, <span class="st" style="color: #20794D;">"n"</span>, <span class="st" style="color: #20794D;">"p"</span>), ])</span>
<span id="cb16-70">  ae <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ae_ard</span>(<span class="fu" style="color: #4758AB;">safety_adae</span>(), adsl)</span>
<span id="cb16-71">  <span class="fu" style="color: #4758AB;">message</span>(<span class="fu" style="color: #4758AB;">nrow</span>(ae), <span class="st" style="color: #20794D;">" rows in the adverse-event ARD"</span>)</span>
<span id="cb16-72">  tt <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">age_ttest_ard</span>(adsl)</span>
<span id="cb16-73">  <span class="fu" style="color: #4758AB;">print</span>(tt[tt<span class="sc" style="color: #5E5E5E;">$</span>stat_name <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"estimate"</span>, <span class="st" style="color: #20794D;">"p.value"</span>), <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"stat_name"</span>, <span class="st" style="color: #20794D;">"stat"</span>)])</span>
<span id="cb16-74">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"QC, independent re-run:"</span>)</span>
<span id="cb16-75">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">compare_ards</span>(demog, <span class="fu" style="color: #4758AB;">demog_ard</span>(adsl)))</span>
<span id="cb16-76">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"QC, with a planted discrepancy:"</span>)</span>
<span id="cb16-77">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">compare_ards</span>(demog, <span class="fu" style="color: #4758AB;">plant_discrepancy</span>(<span class="fu" style="color: #4758AB;">demog_ard</span>(adsl))))</span>
<span id="cb16-78">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards</strong></p>
<ul>
<li><strong>CDISC Analysis Results Standard</strong>: <a href="https://www.cdisc.org/standards/foundational/analysis-results-standard">cdisc.org/standards/foundational/analysis-results-standard</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>cards</strong>: <a href="https://pharmaverse.github.io/cards/">pharmaverse.github.io/cards</a></li>
<li><strong>cardx</strong>: <a href="https://insightsengineering.github.io/cardx/">insightsengineering.github.io/cardx</a></li>
<li><strong>gtsummary</strong>: <a href="https://www.danieldsjoberg.com/gtsummary/">danieldsjoberg.com/gtsummary</a></li>
<li><strong>tfrmt</strong>: <a href="https://cran.r-project.org/package=tfrmt">CRAN</a></li>
<li><strong>waldo</strong>: <a href="https://waldo.r-lib.org/">waldo.r-lib.org</a></li>
<li><strong>diffdf</strong>: <a href="https://cran.r-project.org/package=diffdf">CRAN</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
<li><strong>gt</strong>: <a href="https://gt.rstudio.com">gt.rstudio.com</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-series-nav__series">Pharma series · part 3 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 2</span><span class="site-related-card__title">Generating tables, figures and listings in R</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/cdisc-ars-siera/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 4</span><span class="site-related-card__title">The CDISC Analysis Results Standard and {siera}</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html" class="site-link-row" title="Capture complex console output, rtables layouts, and plots with testthat snapshots and vdiffr to catch regressions without fragile manual assertions."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Snapshot tests for R output, tables and plots</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/property-based-testing/index.html" class="site-link-row" title="Define general invariants, generate varied test inputs with quickcheck, and use shrinking to pinpoint edge cases in R functions and clinical derivations."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Property-based testing in R</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/index.html" class="site-link-row" title="Declare external packages in DESCRIPTION Imports and Suggests, call functions through pkg::fun() or @importFrom, and guard optional dependencies cleanly."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Dependencies: DESCRIPTION and NAMESPACE</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Pharma</category>
  <category>R</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/analysis-results-data-cards/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Building this blog: from numbered topics to a living Quarto publication</title>
  <link>https://insightsurge-dev.web.app/posts/building-this-blog/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Technical documentation often begins as a structured, numbered curriculum. As engineering work evolves, that format hits predictable constraints:</p>
<ol type="1">
<li><strong>Rigidity of numbered sequences.</strong> In a linear numbered list (<code>topics/01-...</code>, <code>topics/02-...</code>), inserting new articles breaks sequential numbering, while adding topical posts outside the core sequence feels unnatural.</li>
<li><strong>Broken incoming links.</strong> Moving from numbered directory paths (<code>/topics/01-identity-isolation/</code>) to semantic slugs (<code>/posts/identity-isolation/</code>) breaks bookmarks, search indexing, and existing cross-references unless backwards compatibility is explicitly maintained.</li>
<li><strong>The staleness trap.</strong> Most engineering blogs treat articles as immutable point-in-time snapshots. When a tool releases a breaking change or a security guardrail evolves, authoring a completely new post scatters information, leaving readers stranded on outdated guidance.</li>
<li><strong>Draft clutter and companion metadata.</strong> Authors often want companion artifacts alongside articles—such as executive summaries, newsletter drafts, or test scripts—without having static site generators compile them into public web pages.</li>
</ol>
<p>To address these challenges, we transformed this site from a 14-topic repository into a full Quarto blog and portfolio, preserving existing URLs while adopting living-document standards and automated verification.</p>
</section>
<section id="site-architecture-and-explicit-rendering-_quarto.yml" class="level2">
<h2 class="anchored" data-anchor-id="site-architecture-and-explicit-rendering-_quarto.yml">Site architecture and explicit rendering (<code>_quarto.yml</code>)</h2>
<p>The site configuration in <code>_quarto.yml</code> establishes a clear project structure:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="fu" style="color: #4758AB;">project</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> website</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">render</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="co" style="color: #5E5E5E;">              # explicit: companions next to posts are never rendered</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> index.qmd</span><span class="co" style="color: #5E5E5E;">        # landing page = About (Quarto `about:` template)</span></span>
<span id="cb1-5"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> blog.qmd</span></span>
<span id="cb1-6"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> series/*.qmd</span></span>
<span id="cb1-7"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> glossary.qmd</span></span>
<span id="cb1-8"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> posts/*/index.qmd</span></span>
<span id="cb1-9"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">resources</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-10"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"templates/**"</span></span>
<span id="cb1-11"></span>
<span id="cb1-12"><span class="fu" style="color: #4758AB;">website</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-13"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Your Name"</span></span>
<span id="cb1-14"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">site-url</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> https://example.web.app</span><span class="co" style="color: #5E5E5E;">   # needed for the RSS feed</span></span>
<span id="cb1-15"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">search</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb1-16"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">navbar</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-17"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">left</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-18"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">href</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> index.qmd</span></span>
<span id="cb1-19"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">text</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> About</span></span>
<span id="cb1-20"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">href</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> blog.qmd</span></span>
<span id="cb1-21"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">text</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> R Engineering Playbook</span></span>
<span id="cb1-22"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">text</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Series</span><span class="co" style="color: #5E5E5E;">          # a dropdown: one page per series</span></span>
<span id="cb1-23"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">menu</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-24"><span class="at" style="color: #657422;">          </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">href</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> series/foundations.qmd</span></span>
<span id="cb1-25"><span class="at" style="color: #657422;">            </span><span class="fu" style="color: #4758AB;">text</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Foundations series</span></span>
<span id="cb1-26"><span class="at" style="color: #657422;">          </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">href</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> series/testing.qmd</span></span>
<span id="cb1-27"><span class="at" style="color: #657422;">            </span><span class="fu" style="color: #4758AB;">text</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Testing series</span></span>
<span id="cb1-28"><span class="at" style="color: #657422;">          </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">href</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> series/pharma.qmd</span></span>
<span id="cb1-29"><span class="at" style="color: #657422;">            </span><span class="fu" style="color: #4758AB;">text</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Pharma series</span></span></code></pre></div></div>
<section id="explicit-render-lists-keep-companion-files-out-of-the-site" class="level3">
<h3 class="anchored" data-anchor-id="explicit-render-lists-keep-companion-files-out-of-the-site">Explicit render lists keep companion files out of the site</h3>
<p>By default, Quarto crawls the repository and renders every <code>.qmd</code> and <code>.md</code> file it finds into HTML.</p>
<p>In our repository structure, every article folder inside <code>posts/&lt;slug&gt;/</code> contains companion files: <code>summary.md</code> (a 1-page executive summary) and <code>message.md</code> (a short social share post). By specifying an <strong>explicit <code>render</code> list</strong> (<code>posts/*/index.qmd</code>), Quarto compiles only the canonical <code>index.qmd</code> for each post. The companion files remain available in the repository for review and team sharing without creating orphaned HTML pages.</p>
</section>
<section id="base-url-for-rss-syndication" class="level3">
<h3 class="anchored" data-anchor-id="base-url-for-rss-syndication">Base URL for RSS syndication</h3>
<p>Declaring <code>site-url</code> provides the absolute domain required for generating standard RSS feeds (<code>feed: true</code> in <code>blog.qmd</code>), ensuring subscribers can follow updates via standard feed readers.</p>
</section>
</section>
<section id="dual-listings-blog-grid-and-series-pages" class="level2">
<h2 class="anchored" data-anchor-id="dual-listings-blog-grid-and-series-pages">Dual listings: Blog grid and series pages</h2>
<p>Readers approach documentation with different goals. Some want a chronological feed of recent technical notes, while others require a structured curriculum. We accommodate both with two dedicated listing views.</p>
<section id="the-blog-listing-blog.qmd" class="level3">
<h3 class="anchored" data-anchor-id="the-blog-listing-blog.qmd">1. The Blog listing (<code>blog.qmd</code>)</h3>
<p>The primary blog index uses a responsive grid layout with category filtering and sorting:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="pp" style="color: #AD0000;">---</span></span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"R Engineering Playbook"</span></span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;">listing</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-4"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">contents</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> posts</span></span>
<span id="cb2-5"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> grid</span></span>
<span id="cb2-6"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">grid-columns</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">3</span></span>
<span id="cb2-7"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">fields</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">date</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> categories</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> reading-time</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb2-8"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">categories</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb2-9"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">sort</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-10"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"date desc"</span></span>
<span id="cb2-11"><span class="at" style="color: #657422;">    </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"title"</span></span>
<span id="cb2-12"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">feed</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb2-13"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">page-size</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">12</span></span>
<span id="cb2-14"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">filter-ui</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb2-15"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">sort-ui</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb2-16"><span class="pp" style="color: #AD0000;">---</span></span></code></pre></div></div>
<p>Setting <code>categories: true</code> creates a sidebar that allows readers to filter posts by topic (e.g.&nbsp;“R packages”, “Agentic AI”, “GxP”).</p>
</section>
<section id="series-pages-seriesfoundations.qmd" class="level3">
<h3 class="anchored" data-anchor-id="series-pages-seriesfoundations.qmd">2. Series pages (<code>series/foundations.qmd</code>)</h3>
<p>To keep a reading order, each series gets its own page under <code>series/</code>, reachable from a <strong>Series</strong> dropdown in the navbar. A post joins a series with two front-matter fields, <code>series:</code> and <code>order:</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb3-1"><span class="fu" style="color: #4758AB;">series</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> foundations</span></span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;">order</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">1</span></span></code></pre></div></div>
<p>The series page lists the posts whose <code>series</code> matches, sorted by <code>order</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb4-1"><span class="pp" style="color: #AD0000;">---</span></span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;">title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Foundations series"</span></span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;">subtitle</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"From R development to R engineering"</span></span>
<span id="cb4-4"><span class="fu" style="color: #4758AB;">listing</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-5"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">contents</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"../posts/*/index.qmd"</span></span>
<span id="cb4-6"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">include</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">series</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> foundations</span></span>
<span id="cb4-8"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">sort</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"order"</span></span>
<span id="cb4-9"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> table</span></span>
<span id="cb4-10"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">fields</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">order</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb4-11"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">field-display-names</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-12"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">order</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"#"</span></span>
<span id="cb4-13"><span class="pp" style="color: #AD0000;">---</span></span></code></pre></div></div>
<p>A listing’s <code>include:</code> can filter on any front-matter field, not only categories (we checked this with Quarto 1.8.27 before relying on it). The table shows each series in reading order, regardless of publication dates.</p>
<p>We first used a category (“Foundations series”) for this. It worked, but every new series would have added another entry to the category filter, next to the topics readers actually filter by. A separate <code>series:</code> field keeps categories for topics and series for reading order.</p>
</section>
</section>
<section id="url-stability-aliases-preserve-existing-links" class="level2">
<h2 class="anchored" data-anchor-id="url-stability-aliases-preserve-existing-links">URL stability: aliases preserve existing links</h2>
<p>Renaming directory paths from <code>topics/01-identity-isolation/</code> to <code>posts/identity-isolation/</code> would normally create 404 errors for anyone visiting legacy URLs.</p>
<p>Quarto solves this through the <code>aliases</code> front-matter key:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb5-1"><span class="pp" style="color: #AD0000;">---</span></span>
<span id="cb5-2"><span class="fu" style="color: #4758AB;">title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Identity &amp; environment isolation"</span></span>
<span id="cb5-3"><span class="fu" style="color: #4758AB;">series</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> foundations</span></span>
<span id="cb5-4"><span class="fu" style="color: #4758AB;">order</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">1</span></span>
<span id="cb5-5"><span class="fu" style="color: #4758AB;">aliases</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-6"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> /topics/01-identity-isolation/index.html</span></span>
<span id="cb5-7"><span class="fu" style="color: #4758AB;">categories</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="st" style="color: #20794D;">"R"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Git"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"Security"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb5-8"><span class="pp" style="color: #AD0000;">---</span></span></code></pre></div></div>
<p>During site compilation, Quarto inspects the <code>aliases</code> list and creates static redirect stubs at <code>_site/topics/01-identity-isolation/index.html</code>. Any request targeting the legacy path is automatically redirected to <code>/posts/identity-isolation/</code>. Verifying the build confirms that redirect files are properly generated in <code>_site/topics/*</code>.</p>
</section>
<section id="controlled-category-taxonomy" class="level2">
<h2 class="anchored" data-anchor-id="controlled-category-taxonomy">Controlled category taxonomy</h2>
<p>Uncontrolled tagging creates fragmented listing sidebars where <code>github</code>, <code>gh-actions</code>, and <code>github-actions</code> compete as near-duplicates.</p>
<p>We established a controlled taxonomy defined directly in <code>blog.qmd</code>’s front-matter header comments: - Every post receives between 2 and 4 taxonomy categories. - Non-taxonomy values are systematically removed. - Series membership is not a category: it lives in the <code>series:</code> field (see above). - Categories are a short, high-level list readers actually filter by (“R”, “Shiny”, “R packages”, “Agentic AI”, “GxP”, “Pharma”, “Git”, “CI/CD”, “Security”, “Quarto”, “Best practices”).</p>
</section>
<section id="articles-as-living-documents" class="level2">
<h2 class="anchored" data-anchor-id="articles-as-living-documents">Articles as living documents</h2>
<p>In software engineering, best practices change when runtimes update, APIs evolve, or new security vulnerabilities emerge.</p>
<p>Rather than writing fragmented follow-up posts (“Why my 2024 article was wrong”), our editorial rules establish that <strong>articles are living documents</strong>:</p>
<ol type="1">
<li><p><strong><code>date-modified</code> tracking:</strong> When an article is updated, <code>date-modified: YYYY-MM-DD</code> is added to its front matter alongside its original <code>date</code>.</p></li>
<li><p><strong>Explicit Updates callouts:</strong> The bottom of each updated article contains a standard callout recording the revision history:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb6-1">::: {.callout-note collapse="false"}</span>
<span id="cb6-2"><span class="fu" style="color: #4758AB;">## Updates</span></span>
<span id="cb6-3"><span class="ss" style="color: #20794D;">- </span>**2026-09-26:** <span class="dt" style="color: #AD0000;">&lt;</span><span class="kw" style="color: #003B4F;
font-weight: bold;">what</span><span class="ot" style="color: #003B4F;"> changed</span><span class="er" style="color: #AD0000;">,</span><span class="ot" style="color: #003B4F;"> </span><span class="er" style="color: #AD0000;">1-3</span><span class="ot" style="color: #003B4F;"> sentences</span><span class="er" style="color: #AD0000;">,</span><span class="ot" style="color: #003B4F;"> with links</span><span class="dt" style="color: #AD0000;">&gt;</span></span>
<span id="cb6-4">:::</span></code></pre></div></div></li>
<li><p><strong>In-body weaving:</strong> New facts, commands, or code samples are woven directly into the relevant body sections rather than existing solely within the changelog box.</p></li>
<li><p><strong>Post template:</strong> Each post follows base sections: <em>The problem → The web-repo way → The R way</em>. Other sections are included only when needed, with no default checklist.</p></li>
</ol>
</section>
<section id="automated-ci-gates-previews-and-link-checking" class="level2">
<h2 class="anchored" data-anchor-id="automated-ci-gates-previews-and-link-checking">Automated CI gates: previews and link checking</h2>
<p>Every pull request modifying the playbook undergoes two automated gates before merging:</p>
<ol type="1">
<li><strong>Ephemeral preview channels:</strong> Each pull request renders and deploys to an isolated Firebase Hosting channel (<code>pr-&lt;number&gt;</code>) that automatically expires 7 days after the last deploy (see <a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html">ephemeral PR previews</a>). Reviewers inspect rendered HTML rather than raw markdown diffs.</li>
<li><strong>Offline link validation:</strong> An automated CI step runs <code>lychee --offline</code> across all generated HTML files in <code>_site/</code> (see <a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/index.html">link checking rendered sites</a>), while a local Python script mirrors the check before push. Renamed topics or broken internal links fail the build instantly.</li>
</ol>
</section>
<section id="shared-branding-with-_brand.yml" class="level2">
<h2 class="anchored" data-anchor-id="shared-branding-with-_brand.yml">Shared branding with <code>_brand.yml</code></h2>
<p>Modern technical publishing requires visual coherence between documentation websites, slide decks, and data applications.</p>
<p>Quarto supports the unified <code>_brand.yml</code> standard, which defines typography, color palettes, and logos in a single configuration file readable by both Quarto and Shiny’s <code>bslib</code> package. For our initial migration, the site maintains a neutral default brand configuration, providing a clean baseline that can be customized across both web assets and Shiny applications without rewriting template markup.</p>
</section>
<section id="delegated-multi-model-authoring" class="level2">
<h2 class="anchored" data-anchor-id="delegated-multi-model-authoring">Delegated multi-model authoring</h2>
<p>Migrating an entire documentation site while updating multiple living articles was coordinated using a <strong>two-model workflow</strong> (see <a href="https://insightsurge-dev.web.app/posts/two-model-workflow/index.html">two-model AI delegation</a>):</p>
<pre class="mermaid"><code>flowchart TD
    Claude["Owner Model (Claude)"] --&gt;|"gemini-brief.md (Scope &amp; Constraints)"| Gemini["Delegate Sessions (Gemini)"]
    Gemini --&gt;|"Research / Migration / Drafts / Categories"| Workspaces["posts/** &amp; drafts/**"]
    Claude --&gt;|"Review diffs, quarto render, lychee link check"| Verification{"Verification Gate"}
    Verification --&gt;|"Pass"| Git["PR Commit &amp; Merge"]</code></pre>
<ul>
<li>An <strong>Owner model (Claude)</strong> defined the plan, maintained the project instructions (<code>CLAUDE.md</code>), reviewed every phase, and did all commits, pushes and merges. The delegates were <em>instructed</em> not to use git; that rule was enforced by the brief and by reviewing diffs, not by sandboxing.</li>
<li>Focused <strong>Delegate sessions (Gemini)</strong> operated under a shared brief (<code>gemini-brief.md</code>) with strict file ownership boundaries:
<ul>
<li>A <em>research session</em> explored Quarto listings and themes;</li>
<li>A <em>migration session</em> moved legacy topic paths and updated navigation;</li>
<li>An <em>articles session</em> drafted new technical content in <code>drafts/</code>;</li>
<li>An <em>editor/categories session</em> applied review notes, unified category metadata, and authored amendments;</li>
<li>A <em>theme/bslib session</em> harmonized styling.</li>
</ul></li>
<li>Every change concluded with a structured digest, allowing the owner to verify file diffs and execute link checks before committing.</li>
</ul>
</section>
<section id="the-r-way-patterns-for-r-teams-and-package-documentation" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-patterns-for-r-teams-and-package-documentation">The R way: patterns for R teams and package documentation</h2>
<p>The patterns powering this blog translate directly to internal tooling within R-focused organisations:</p>
<ul>
<li><strong>R package blogs &amp; vignettes:</strong> An R package team can publish deep-dive tutorials alongside reference documentation by adding a <code>posts/</code> folder and a Quarto blog listing.</li>
<li><strong>Team knowledge bases:</strong> Engineering teams running Posit Connect or internal servers can use the same <code>aliases</code> mechanism to refactor legacy wiki paths without breaking corporate bookmarks.</li>
<li><strong>Living standard operating procedures (SOPs):</strong> In regulated GxP environments, the “living documents” convention (<code>date-modified</code> plus an explicit Updates log) provides transparent revision history for internal guidance and analytical playbooks.</li>
</ul>
</section>
<section id="pitfalls-we-hit" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-we-hit">Pitfalls we hit</h2>
<ul>
<li><strong>Listings on pages in subfolders.</strong> <code>series/foundations.qmd</code> first used <code>contents: ../posts</code> and <code>contents: /posts</code>; both rendered an empty table with the warning <em>“doesn’t match any files or folders”</em>. A relative <strong>glob</strong> worked: <code>contents: "../posts/*/index.qmd"</code>.</li>
<li><strong>Dark mode and Bootstrap variables.</strong> Quarto compiles separate light and dark stylesheets but doesn’t set Bootstrap’s <code>data-bs-theme="dark"</code>, so variables like <code>--bs-tertiary-bg</code> kept their <em>light</em> values in dark mode, and our callouts and inline code turned into white boxes. The fix is to derive surfaces from the theme’s own SCSS variables (<code>--hv-surface: #{mix($body-color, $body-bg, 6%)}</code>), which are compiled per theme. We also set <code>respect-user-color-scheme: true</code> so the site follows the visitor’s OS setting.</li>
<li><strong>Outdated snippets.</strong> A post that shows your own configuration goes stale as the site evolves. Update it in place (see the living-documents rule above).</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist and updated post template documentation to base sections problem → web-repo way → R way with no default checklist.</li>
<li><strong>2026-09-26:</strong> Series moved from a category to a <code>series:</code> front-matter field, and the Testing and Pharma series pages were added. The category filter now lists topics only.</li>
<li><strong>2026-11-13:</strong> The site’s SCSS theme moved from one <code>styles.scss</code> file into a <code>brand/</code> folder, so the dark-mode pitfall no longer names that file.</li>
</ul>
</div>
</div>
</div>



</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor site-related">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/two-model-workflow/index.html" class="site-link-row" title="Structure dual-model AI workflows with clear task ownership, written briefs, and human verification to maintain engineering rigor."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">One owner, two models: delegating to a second AI and verifying it</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/index.html" class="site-link-row" title="Validate internal links across rendered documentation in CI using offline link scanners to block broken references before release."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Catch broken links before your readers do</span></a></li>
</ul>
</div>
</section>


 ]]></description>
  <category>Quarto</category>
  <category>Agentic AI</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/building-this-blog/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>CI with GitHub Actions</title>
  <link>https://insightsurge-dev.web.app/posts/ci-github-actions/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-idea" class="level2">
<h2 class="anchored" data-anchor-id="the-idea">The idea</h2>
<p>Continuous integration means every PR is built and checked <strong>on a clean machine</strong>, the same way every time, before it can merge. For an R package that’s <code>R CMD check</code>. For a Shiny app it’s tests plus a deploy check. For a Quarto site it’s a render plus a link check. “Works on my machine” stops being an argument.</p>
</section>
<section id="anatomy-of-a-workflow" class="level2">
<h2 class="anchored" data-anchor-id="anatomy-of-a-workflow">Anatomy of a workflow</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ci</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull_request</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">push</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">branches</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">main</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-8"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">contents</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read</span><span class="co" style="color: #5E5E5E;">              # least privilege: read the code, nothing else</span></span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="fu" style="color: #4758AB;">concurrency</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-11"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">group</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ci-${{ github.ref }}</span><span class="co" style="color: #5E5E5E;"> # a new push to the same PR cancels the old run</span></span>
<span id="cb1-12"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">cancel-in-progress</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb1-13"></span>
<span id="cb1-14"><span class="fu" style="color: #4758AB;">jobs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-15"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">check</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-16"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">runs-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ubuntu-26.04</span><span class="co" style="color: #5E5E5E;">     # pinned runner: avoids surprise moves when ubuntu-latest rolls</span></span>
<span id="cb1-17"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-18"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> actions/checkout@v7</span></span>
<span id="cb1-19"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> actions/setup-node@v7</span></span>
<span id="cb1-20"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-21"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">node-version-file</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> .nvmrc</span><span class="co" style="color: #5E5E5E;">   # runtime version comes from the repo</span></span>
<span id="cb1-22"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">cache</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> npm</span></span>
<span id="cb1-23"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> npm ci</span><span class="co" style="color: #5E5E5E;">                   # exact versions from the lockfile</span></span>
<span id="cb1-24"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> npx biome ci</span><span class="co" style="color: #5E5E5E;">             # lint + format</span></span>
<span id="cb1-25"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> npm run typecheck</span></span>
<span id="cb1-26"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> npm test</span></span>
<span id="cb1-27"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> npm run build</span></span></code></pre></div></div>
<p>Five habits that carry over to any language:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Habit</th>
<th>Why</th>
<th>R equivalent</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>permissions: contents: read</code></td>
<td>A compromised step can’t push or open releases</td>
<td>Same YAML</td>
</tr>
<tr class="even">
<td><code>concurrency</code> + <code>cancel-in-progress</code></td>
<td>No wasted minutes on stale pushes</td>
<td>Same YAML</td>
</tr>
<tr class="odd">
<td>Runtime version read from the repo</td>
<td>CI and laptops agree</td>
<td><code>setup-r</code> with <code>r-version: renv</code> reads <code>renv.lock</code></td>
</tr>
<tr class="even">
<td>Install from the lockfile</td>
<td>Reproducible dependencies</td>
<td><code>setup-renv</code>, or <code>setup-r-dependencies</code></td>
</tr>
<tr class="odd">
<td>Fail fast, cheapest check first</td>
<td>Quick feedback</td>
<td>lint → test → check</td>
</tr>
</tbody>
</table>
</div>
<p>When one step fails, the later steps are skipped. We saw this with a deliberate type error: <em>Typecheck: failure</em>, then <em>Unit tests: skipped</em>, <em>Build: skipped</em>.</p>
</section>
<section id="the-r-way-r-libactions" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-r-libactions">The R way: <code>r-lib/actions</code></h2>
<p><code>usethis</code> copies the maintained examples from <a href="https://github.com/r-lib/actions/tree/v2/examples"><code>r-lib/actions</code></a>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_action</span>(<span class="st" style="color: #20794D;">"check-standard"</span>)  <span class="co" style="color: #5E5E5E;"># R CMD check: macOS, Windows, Ubuntu (devel/release/oldrel-1)</span></span>
<span id="cb2-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_action</span>(<span class="st" style="color: #20794D;">"test-coverage"</span>)   <span class="co" style="color: #5E5E5E;"># covr</span></span>
<span id="cb2-3">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_action</span>(<span class="st" style="color: #20794D;">"pkgdown"</span>)         <span class="co" style="color: #5E5E5E;"># build and deploy the package site</span></span>
<span id="cb2-4">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_action</span>(<span class="st" style="color: #20794D;">"lint"</span>)            <span class="co" style="color: #5E5E5E;"># lintr (see hooks, formatting &amp; linting)</span></span>
<span id="cb2-5">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_action</span>(<span class="st" style="color: #20794D;">"shiny-deploy"</span>)    <span class="co" style="color: #5E5E5E;"># deploy a Shiny app with rsconnect</span></span></code></pre></div></div>
<p>The core of <code>check-standard</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb3-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> r-lib/actions/setup-pandoc@v2</span></span>
<span id="cb3-2"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> r-lib/actions/setup-r@v2</span></span>
<span id="cb3-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">r-version</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ matrix.config.r }}</span><span class="co" style="color: #5E5E5E;">     # or 'renv' to use the lockfile's version</span></span>
<span id="cb3-5"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> r-lib/actions/setup-r-dependencies@v2</span></span>
<span id="cb3-6"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">extra-packages</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> any::rcmdcheck</span></span>
<span id="cb3-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">needs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> check</span></span>
<span id="cb3-9"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> r-lib/actions/check-r-package@v2</span></span>
<span id="cb3-10"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-11"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">upload-snapshots</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span><span class="co" style="color: #5E5E5E;">                # testthat/shinytest2 snapshots on failure</span></span></code></pre></div></div>
<p><strong>Two cheap hardening edits</strong> to the stock example: it ships with <code>permissions: read-all</code>, which you can narrow to <code>permissions: contents: read</code>, and it has no <code>concurrency</code> block, so add one.</p>
<p><strong>Shiny apps:</strong> <code>shinytest2</code> tests live in <code>tests/testthat/</code>, so they run inside <code>R CMD check</code> (for app-in-a-package) or with <code>testthat::test_dir()</code>. Failed snapshots are uploaded as artifacts.</p>
<p><strong>Quarto sites:</strong> use <code>quarto-dev/quarto-actions/setup</code> and <code>.../render</code>, pin the Quarto version, and add a link checker. This playbook’s own <code>.github/workflows/quarto.yml</code> is a worked example. It renders, checks internal links with <code>lychee</code>, and deploys a preview per PR.</p>
</section>
<section id="pinning-how-tightly" class="level2">
<h2 class="anchored" data-anchor-id="pinning-how-tightly">Pinning: how tightly?</h2>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Style</th>
<th>Example</th>
<th>Trade-off</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Major tag</td>
<td><code>r-lib/actions/setup-r@v2</code></td>
<td>Gets fixes automatically; trusts the maintainer</td>
</tr>
<tr class="even">
<td>Exact tag</td>
<td><code>@v2.14.0</code></td>
<td>Reproducible; you must bump it</td>
</tr>
<tr class="odd">
<td>Commit SHA</td>
<td><code>@&lt;40-char sha&gt;</code></td>
<td>Immutable, best supply-chain safety; unreadable without comments</td>
</tr>
</tbody>
</table>
</div>
<p>Major tags plus <strong>Dependabot for <code>github-actions</code></strong> (<a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html">dependency updates &amp; vetting</a>) is a sensible default. Regulated production pipelines may justify SHA pinning.</p>
<p>Also pin the <strong>runner image</strong> if stability matters. <code>ubuntu-latest</code> moves over time: GitHub moves <code>ubuntu-latest</code> to Ubuntu 26.04 in a rollout that starts on 19 October 2026. On 2026-09-27, we moved the pinned runners in this repository to <code>runs-on: ubuntu-26.04</code> deliberately ahead of the rollout, rather than waiting for <code>ubuntu-latest</code> to transition underneath us.</p>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Generated files must be generated in CI.</strong> Our Next.js typecheck failed on a fresh checkout until CI ran <code>next typegen</code> first. The R version of this is an out-of-date <code>NAMESPACE</code>: run <code>devtools::document()</code> and commit the result, or check it in CI.</li>
<li><strong>Secrets in PRs from forks</strong> aren’t available (by design). Design deploy steps to skip cleanly.</li>
<li><strong>Don’t <code>continue-on-error</code> your way to green.</strong> A check that can’t fail isn’t a check.</li>
<li><strong>Watch the matrix size.</strong> Five OS/R combinations per push adds up on private repos, where Actions minutes are billed against your plan’s quota.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>GitHub Actions</strong></p>
<ul>
<li><strong><code>permissions:</code> and <code>GITHUB_TOKEN</code></strong>: <a href="https://docs.github.com/en/actions/tutorials/authenticate-with-github_token">GitHub Docs: Use <code>GITHUB_TOKEN</code> for authentication in workflows</a></li>
<li><strong><code>concurrency:</code></strong>: <a href="https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency">GitHub Docs: Control the concurrency of workflows and jobs</a></li>
<li><strong>Secrets not available to workflows from forked-repo PRs</strong>: <a href="https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets">GitHub Docs: Use secrets in GitHub Actions</a></li>
<li><strong><code>ubuntu-latest</code> moving to Ubuntu 26 (19 Oct–19 Nov 2026 rollout)</strong>: <a href="https://github.blog/changelog/2026-09-17-ubuntu-26-generally-available-and-latest-migration/">GitHub Changelog: Ubuntu 26 generally available and latest migration</a></li>
<li><strong>GitHub Actions runner images</strong> (<code>ubuntu-26.04</code> image definition): <a href="https://github.com/actions/runner-images">actions/runner-images</a></li>
<li><strong>r-lib/actions</strong> (<code>check-standard</code>, <code>setup-r</code>, <code>setup-r-dependencies</code>, <code>check-r-package</code>): <a href="https://github.com/r-lib/actions/tree/v2/examples">github.com/r-lib/actions</a></li>
<li><strong>quarto-dev/quarto-actions</strong>: <a href="https://github.com/quarto-dev/quarto-actions">github.com/quarto-dev/quarto-actions</a></li>
<li><strong>lychee</strong> (link checker): <a href="https://github.com/lycheeverse/lychee">github.com/lycheeverse/lychee</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>use_github_action()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-26:</strong> Pinned <code>runs-on: ubuntu-24.04</code> across all GitHub Actions workflows in both repositories ahead of GitHub’s scheduled <code>ubuntu-latest</code> transition to Ubuntu 26 (19 October 2026), deferring the runner upgrade until we validate it deliberately.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Moved the pinned runners from ubuntu-24.04 to ubuntu-26.04, ahead of the ubuntu-latest rollout.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 5 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 4</span><span class="site-related-card__title">Pre-commit hooks, formatting &amp; linting</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/secret-scanning/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 6</span><span class="site-related-card__title">Secret scanning with gitleaks</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="site-link-row" title="Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Coverage and tests as evidence</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/index.html" class="site-link-row" title="Drive Shiny applications end to end with shinytest2 and headless Chrome, testing real browser rendering, user input sequences, and reactive outputs."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">End-to-end Shiny tests with shinytest2</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>CI/CD</category>
  <category>R packages</category>
  <category>Shiny</category>
  <guid>https://insightsurge-dev.web.app/posts/ci-github-actions/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Catch broken links before your readers do</title>
  <link>https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Broken internal links are among the quickest ways to erode reader trust. In technical engineering documentation, clinical study reports, or package reference sites, a link resolving to a 404 page signals sloppy maintenance:</p>
<ul>
<li><strong>Slug and path refactoring.</strong> Renaming a topic from <code>topics/01-isolation/</code> to <code>posts/identity-isolation/</code> instantly breaks every incoming relative link unless every reference is updated.</li>
<li><strong>Markdown vs HTML disconnect.</strong> Authors write <code>[Read more](../foo/index.qmd)</code> or <code>[Read more](../foo/)</code>, assuming the static site generator will figure out the rendered destination. If the target file or anchor does not exist in the output directory, the error is invisible until a human clicks it.</li>
<li><strong>Manual clicking does not scale.</strong> A site with 15 articles, cross-references, navigation menus, and footers easily generates many internal hyperlinks. Nobody can verify them manually on every pull request.</li>
</ul>
<p>To maintain documentation integrity, link verification must be automated as a mandatory, blocking gate in CI (see <a href="https://insightsurge-dev.web.app/posts/test-your-guardrails/index.html">test your guardrails</a>).</p>
</section>
<section id="the-web-repo-way-lychee-in-ci" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-lychee-in-ci">The web-repo way: lychee in CI</h2>
<p>Modern documentation pipelines use automated link checkers such as <a href="https://github.com/lycheeverse/lychee">lychee</a>, a fast, asynchronous link validator written in Rust.</p>
<section id="the-ci-step" class="level3">
<h3 class="anchored" data-anchor-id="the-ci-step">The CI step</h3>
<p>In <code>.github/workflows/quarto.yml</code>, link checking executes immediately after the site renders to <code>_site/</code> and before any deployment step can run:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Check internal links</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> lycheeverse/lychee-action@v2</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">args</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> --offline --no-progress --root-dir "${{ github.workspace }}/_site" '_site/**/*.html'</span></span>
<span id="cb1-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">fail</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span></code></pre></div></div>
<p>Key arguments in this configuration: - <code>--offline</code>: Instructs lychee to ignore all external HTTP/HTTPS URLs. It checks exclusively local file paths and root-relative links (<code>/posts/...</code>). (Note that lychee does not check <code>#fragments</code> by default unless <code>--include-fragments</code> is supplied, and our local script also ignores fragments.) - <code>--root-dir</code>: Sets the root directory for absolute paths. A link written as <code>/about.html</code> is resolved against <code>${{ github.workspace }}/_site/about.html</code>. - <code>fail: true</code>: Configures the action to return an exit code of 1 if any broken link is found, immediately failing the PR build and preventing deployment.</p>
</section>
<section id="what-we-observed-in-practice" class="level3">
<h3 class="anchored" data-anchor-id="what-we-observed-in-practice">What we observed in practice</h3>
<p>On our initial CI run, lychee scanned <strong>570 internal links</strong> across the rendered HTML files and reported <strong>0 errors</strong>.</p>
<p>Because the scan runs in offline mode, it runs without sending outbound network requests. More importantly, prior to opening the PR, local checking caught an issue with <strong>directory links</strong>: relative paths pointing to a folder that had no <code>index.html</code> at all (for example, a link to this playbook’s GitHub templates folder). The fix was linking directly to a file (<a href="https://insightsurge-dev.web.app/templates/README.md"><code>templates/README.md</code></a> or <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/SKILL.md"><code>SKILL.md</code></a>).</p>
</section>
<section id="mirroring-ci-locally" class="level3">
<h3 class="anchored" data-anchor-id="mirroring-ci-locally">Mirroring CI locally</h3>
<p>In CI, lychee runs inside GitHub Actions. Locally, I mirror its offline check with a small script using base R and <a href="https://xml2.r-lib.org/">{xml2}</a>. It scans the rendered HTML files, extracts <code>href</code> and <code>src</code> attributes, strips fragments and query strings, URL-decodes path segments, and checks that every target exists on disk (requiring folders to contain an <code>index.html</code>):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># Parse HTML and extract internal links</span></span>
<span id="cb2-2">doc <span class="ot" style="color: #003B4F;">&lt;-</span> xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">read_html</span>(html_file, <span class="at" style="color: #657422;">encoding =</span> <span class="st" style="color: #20794D;">"UTF-8"</span>)</span>
<span id="cb2-3">hrefs <span class="ot" style="color: #003B4F;">&lt;-</span> xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_attr</span>(xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_find_all</span>(doc, <span class="st" style="color: #20794D;">"//*[@href]"</span>), <span class="st" style="color: #20794D;">"href"</span>)</span>
<span id="cb2-4">srcs <span class="ot" style="color: #003B4F;">&lt;-</span> xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_attr</span>(xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_find_all</span>(doc, <span class="st" style="color: #20794D;">"//*[@src]"</span>), <span class="st" style="color: #20794D;">"src"</span>)</span>
<span id="cb2-5"></span>
<span id="cb2-6"><span class="co" style="color: #5E5E5E;"># Skip external protocols, mailto, and anchor fragments</span></span>
<span id="cb2-7">skip_pattern <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"^(https?:|mailto:|#|data:|javascript:|tel:)"</span></span>
<span id="cb2-8">links <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(hrefs, srcs)</span>
<span id="cb2-9">internal_links <span class="ot" style="color: #003B4F;">&lt;-</span> links[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">grepl</span>(skip_pattern, links, <span class="at" style="color: #657422;">ignore.case =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)]</span></code></pre></div></div>
<p>Each internal link is cleaned with <code>sub("[#?].*$", "", link)</code> to drop fragments and query parameters, decoded with <code>utils::URLdecode()</code>, and resolved against either the site root (for root-relative paths starting with <code>/</code>) or the page’s parent directory (for relative paths).</p>
<p>Reading attributes with a parser matters: a regex that searches the raw HTML for <code>href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/…"</code> also counts example links shown inside code blocks. On this very page, the full script below builds a small test site whose HTML appears as text, and a regex version of the check reported three of its example links as broken; the parser-based check correctly ignores them.</p>
<p>Running the check locally gives immediate feedback before opening a pull request, without requiring a containerised CI environment. The full standalone implementation is in the companion script (<a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/scripts/check-links.R">scripts/check-links.R</a>).</p>
</section>
</section>
<section id="the-r-way-pkgdown-bookdown-and-quarto" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-pkgdown-bookdown-and-quarto">The R way: pkgdown, bookdown, and Quarto</h2>
<p>In the R ecosystem, documentation is compiled into static HTML across multiple frameworks: - <strong><code>pkgdown</code>:</strong> Builds package documentation into the <code>docs/</code> directory. - <strong><code>bookdown</code>:</strong> Compiles books or long-form documentation into <code>_book/</code>. - <strong>R Markdown websites (<code>rmarkdown::render_site()</code>):</strong> Renders to <code>_site/</code>. - <strong>Quarto sites and books:</strong> Renders to <code>_site/</code>.</p>
<p>Because lychee and our R checker operate on standard HTML files on disk, they are completely agnostic to the generator that created them. You can add the identical check to any R package repository’s GitHub Actions workflow:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb3-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Build pkgdown site</span></span>
<span id="cb3-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Rscript -e 'pkgdown::build_site()'</span></span>
<span id="cb3-3"></span>
<span id="cb3-4"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Verify package documentation links</span></span>
<span id="cb3-5"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> lycheeverse/lychee-action@v2</span></span>
<span id="cb3-6"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">args</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> --offline --no-progress --root-dir "docs" 'docs/**/*.html'</span></span>
<span id="cb3-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">fail</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span></code></pre></div></div>
<p>If a vignette links to a deleted article or page, the CI build fails with the file and the broken URL before the documentation ever deploys.</p>
</section>
<section id="separate-internal-links-from-external-links" class="level2">
<h2 class="anchored" data-anchor-id="separate-internal-links-from-external-links">Separate internal links from external links</h2>
<p>A common mistake is attempting to check external internet links inside the same pull request check.</p>
<p><strong>External link checks should never block a pull request.</strong> External web servers fail for reasons outside your control: - Temporary network timeouts and DNS glitches; - Anti-scraping firewalls returning 403 or 429 status codes; - Third-party endpoints undergoing maintenance.</p>
<p>If your PR gate checks external URLs, your team’s pull requests will randomly turn red due to third-party outages.</p>
<p>The correct architectural pattern is <strong>separation of concerns</strong>: 1. <strong>Internal links:</strong> Checked synchronously in the PR workflow with <code>--offline</code> and <code>fail: true</code>. Internal links must be fully deterministic and blocking. 2. <strong>External links:</strong> Checked asynchronously in a scheduled weekly cron workflow (e.g.&nbsp;<code>schedule: [{cron: "0 9 * * 1"}]</code>). If an external link rots, the workflow opens a GitHub issue or sends an alert without halting daily pull request merges.</p>
</section>
<section id="pitfalls-we-hit" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-we-hit">Pitfalls we hit</h2>
<ul>
<li><strong>Checking source Markdown instead of rendered HTML.</strong> Markdown files often contain shortcodes, includes, or generated relative links that only resolve after compilation. Checking the raw Markdown produces false positive errors. Always check the rendered output directory (<code>_site</code> or <code>docs</code>).</li>
<li><strong>Linking to directories without an <code>index.html</code>.</strong> A link pointing to a folder that has no <code>index.html</code> file at all (such as a templates folder) fails verification. Always link to a specific target file (e.g.&nbsp;<code>README.md</code> or <code>SKILL.md</code>).</li>
<li><strong>Tip on fragment checking.</strong> By default, lychee’s <code>--offline</code> check and our local script do not validate <code>#fragments</code>. If you want to verify in-page header anchors, pass <code>--include-fragments</code> to lychee (we have not enabled this).</li>
<li><strong>Unescaped characters in file paths.</strong> Query parameters or spaces in file names can cause path resolution to fail unless properly decoded via <code>utils::URLdecode()</code>.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/scripts/check-links.R">View <code>check-links.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/scripts/check-links.R" download="check-links.R">Download</a></p>
<p>An offline internal link checker using base R and <code>{xml2}</code>. Scans rendered HTML files for <code>href</code> and <code>src</code> attributes, resolves root-relative and relative paths, validates directory targets for <code>index.html</code>, and reports broken references. Run with <code>Rscript check-links.R _site</code> or execute without arguments to run the self-contained demonstration.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>check-links.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># Offline internal link checker for rendered Quarto, pkgdown, and static HTML sites.</span></span>
<span id="cb4-2"><span class="co" style="color: #5E5E5E;"># Scans HTML files, extracts href and src attributes, resolves root-relative and</span></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;"># relative links, and flags missing files or directory links without index.html.</span></span>
<span id="cb4-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb4-5"><span class="co" style="color: #5E5E5E;"># Usage:</span></span>
<span id="cb4-6"><span class="co" style="color: #5E5E5E;">#   Rscript check-links.R _site</span></span>
<span id="cb4-7"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb4-8"><span class="co" style="color: #5E5E5E;"># Or run without arguments to execute the built-in demonstration:</span></span>
<span id="cb4-9"><span class="co" style="color: #5E5E5E;">#   Rscript check-links.R</span></span>
<span id="cb4-10"></span>
<span id="cb4-11"><span class="co" style="color: #5E5E5E;">#' Simplify path by resolving '.' and '..' segments</span></span>
<span id="cb4-12"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb4-13"><span class="co" style="color: #5E5E5E;">#' @param path Character vector of paths to simplify.</span></span>
<span id="cb4-14"><span class="co" style="color: #5E5E5E;">#' @return Simplified path string.</span></span>
<span id="cb4-15"><span class="co" style="color: #5E5E5E;">#' @keywords internal</span></span>
<span id="cb4-16">simplify_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb4-17">  is_abs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">startsWith</span>(path, <span class="st" style="color: #20794D;">"/"</span>)</span>
<span id="cb4-18">  parts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">strsplit</span>(path, <span class="st" style="color: #20794D;">"/+"</span>)[[<span class="dv" style="color: #AD0000;">1</span>L]]</span>
<span id="cb4-19">  stack <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb4-20">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (part <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> parts) {</span>
<span id="cb4-21">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (part <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">""</span> <span class="sc" style="color: #5E5E5E;">||</span> part <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"."</span>) {</span>
<span id="cb4-22">      <span class="cf" style="color: #003B4F;
font-weight: bold;">next</span></span>
<span id="cb4-23">    }</span>
<span id="cb4-24">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (part <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">".."</span>) {</span>
<span id="cb4-25">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(stack) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> stack[<span class="fu" style="color: #4758AB;">length</span>(stack)] <span class="sc" style="color: #5E5E5E;">!=</span> <span class="st" style="color: #20794D;">".."</span>) {</span>
<span id="cb4-26">        stack <span class="ot" style="color: #003B4F;">&lt;-</span> stack[<span class="sc" style="color: #5E5E5E;">-</span><span class="fu" style="color: #4758AB;">length</span>(stack)]</span>
<span id="cb4-27">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>is_abs) {</span>
<span id="cb4-28">        stack <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(stack, part)</span>
<span id="cb4-29">      }</span>
<span id="cb4-30">    } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb4-31">      stack <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(stack, part)</span>
<span id="cb4-32">    }</span>
<span id="cb4-33">  }</span>
<span id="cb4-34">  res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">paste</span>(stack, <span class="at" style="color: #657422;">collapse =</span> <span class="st" style="color: #20794D;">"/"</span>)</span>
<span id="cb4-35">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (is_abs) <span class="fu" style="color: #4758AB;">paste0</span>(<span class="st" style="color: #20794D;">"/"</span>, res) <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> res</span>
<span id="cb4-36">}</span>
<span id="cb4-37"></span>
<span id="cb4-38"><span class="co" style="color: #5E5E5E;">#' Scan rendered HTML files for broken internal links</span></span>
<span id="cb4-39"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb4-40"><span class="co" style="color: #5E5E5E;">#' @param site_dir Root directory of the rendered static site.</span></span>
<span id="cb4-41"><span class="co" style="color: #5E5E5E;">#' @return A list containing `broken` (a data frame of broken links with columns</span></span>
<span id="cb4-42"><span class="co" style="color: #5E5E5E;">#'   `page`, `link`, and `resolved_path`) and `checked` (the total count of</span></span>
<span id="cb4-43"><span class="co" style="color: #5E5E5E;">#'   internal links checked).</span></span>
<span id="cb4-44"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb4-45">check_links <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">site_dir =</span> <span class="st" style="color: #20794D;">"_site"</span>) {</span>
<span id="cb4-46">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(site_dir)) {</span>
<span id="cb4-47">    <span class="fu" style="color: #4758AB;">stop</span>(</span>
<span id="cb4-48">      <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Site directory '%s' does not exist."</span>, site_dir),</span>
<span id="cb4-49">      <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb4-50">    )</span>
<span id="cb4-51">  }</span>
<span id="cb4-52"></span>
<span id="cb4-53">  norm_site_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">normalizePath</span>(site_dir, <span class="at" style="color: #657422;">winslash =</span> <span class="st" style="color: #20794D;">"/"</span>, <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb4-54">  html_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list.files</span>(</span>
<span id="cb4-55">    norm_site_dir,</span>
<span id="cb4-56">    <span class="at" style="color: #657422;">pattern =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.html$"</span>,</span>
<span id="cb4-57">    <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>,</span>
<span id="cb4-58">    <span class="at" style="color: #657422;">full.names =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb4-59">  )</span>
<span id="cb4-60"></span>
<span id="cb4-61">  bad_pages <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb4-62">  bad_links <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb4-63">  bad_paths <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb4-64">  n_checked <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="dv" style="color: #AD0000;">0</span>L</span>
<span id="cb4-65"></span>
<span id="cb4-66">  <span class="co" style="color: #5E5E5E;"># Skip external protocols, anchor fragments, data URIs, and scripts</span></span>
<span id="cb4-67">  skip_pattern <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="st" style="color: #20794D;">"^(https?:|mailto:|#|data:|javascript:|tel:)"</span></span>
<span id="cb4-68"></span>
<span id="cb4-69">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (html_file <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> html_files) {</span>
<span id="cb4-70">    norm_html <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">normalizePath</span>(html_file, <span class="at" style="color: #657422;">winslash =</span> <span class="st" style="color: #20794D;">"/"</span>, <span class="at" style="color: #657422;">mustWork =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb4-71">    rel_page <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">substring</span>(norm_html, <span class="fu" style="color: #4758AB;">nchar</span>(norm_site_dir) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">2</span>L)</span>
<span id="cb4-72">    html_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">dirname</span>(norm_html)</span>
<span id="cb4-73"></span>
<span id="cb4-74">    doc <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tryCatch</span>(</span>
<span id="cb4-75">      xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">read_html</span>(norm_html, <span class="at" style="color: #657422;">encoding =</span> <span class="st" style="color: #20794D;">"UTF-8"</span>),</span>
<span id="cb4-76">      <span class="at" style="color: #657422;">error =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(e) <span class="cn" style="color: #8f5902;">NULL</span></span>
<span id="cb4-77">    )</span>
<span id="cb4-78">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(doc)) {</span>
<span id="cb4-79">      <span class="cf" style="color: #003B4F;
font-weight: bold;">next</span></span>
<span id="cb4-80">    }</span>
<span id="cb4-81"></span>
<span id="cb4-82">    href_nodes <span class="ot" style="color: #003B4F;">&lt;-</span> xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_find_all</span>(doc, <span class="st" style="color: #20794D;">"//*[@href]"</span>)</span>
<span id="cb4-83">    hrefs <span class="ot" style="color: #003B4F;">&lt;-</span> xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_attr</span>(href_nodes, <span class="st" style="color: #20794D;">"href"</span>)</span>
<span id="cb4-84"></span>
<span id="cb4-85">    src_nodes <span class="ot" style="color: #003B4F;">&lt;-</span> xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_find_all</span>(doc, <span class="st" style="color: #20794D;">"//*[@src]"</span>)</span>
<span id="cb4-86">    srcs <span class="ot" style="color: #003B4F;">&lt;-</span> xml2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">xml_attr</span>(src_nodes, <span class="st" style="color: #20794D;">"src"</span>)</span>
<span id="cb4-87"></span>
<span id="cb4-88">    raw_links <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(hrefs, srcs)</span>
<span id="cb4-89">    raw_links <span class="ot" style="color: #003B4F;">&lt;-</span> raw_links[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(raw_links) <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="fu" style="color: #4758AB;">nzchar</span>(<span class="fu" style="color: #4758AB;">trimws</span>(raw_links))]</span>
<span id="cb4-90"></span>
<span id="cb4-91">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (u <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> raw_links) {</span>
<span id="cb4-92">      u_trim <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">trimws</span>(u)</span>
<span id="cb4-93">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">grepl</span>(skip_pattern, u_trim, <span class="at" style="color: #657422;">ignore.case =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)) {</span>
<span id="cb4-94">        <span class="cf" style="color: #003B4F;
font-weight: bold;">next</span></span>
<span id="cb4-95">      }</span>
<span id="cb4-96"></span>
<span id="cb4-97">      <span class="co" style="color: #5E5E5E;"># Drop #fragment and ?query</span></span>
<span id="cb4-98">      clean_u <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"[#?].*$"</span>, <span class="st" style="color: #20794D;">""</span>, u_trim)</span>
<span id="cb4-99">      p <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tryCatch</span>(</span>
<span id="cb4-100">        utils<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">URLdecode</span>(clean_u),</span>
<span id="cb4-101">        <span class="at" style="color: #657422;">error =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(e) clean_u</span>
<span id="cb4-102">      )</span>
<span id="cb4-103"></span>
<span id="cb4-104">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">nzchar</span>(p)) {</span>
<span id="cb4-105">        <span class="cf" style="color: #003B4F;
font-weight: bold;">next</span></span>
<span id="cb4-106">      }</span>
<span id="cb4-107"></span>
<span id="cb4-108">      n_checked <span class="ot" style="color: #003B4F;">&lt;-</span> n_checked <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L</span>
<span id="cb4-109"></span>
<span id="cb4-110">      <span class="co" style="color: #5E5E5E;"># Resolve root-relative vs relative path</span></span>
<span id="cb4-111">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">startsWith</span>(p, <span class="st" style="color: #20794D;">"/"</span>)) {</span>
<span id="cb4-112">        rel_p <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"^/+"</span>, <span class="st" style="color: #20794D;">""</span>, p)</span>
<span id="cb4-113">        target_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(norm_site_dir, rel_p)</span>
<span id="cb4-114">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb4-115">        target_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(html_dir, p)</span>
<span id="cb4-116">      }</span>
<span id="cb4-117"></span>
<span id="cb4-118">      norm_target <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">simplify_path</span>(target_path)</span>
<span id="cb4-119"></span>
<span id="cb4-120">      <span class="co" style="color: #5E5E5E;"># Check target existence: a folder link must contain index.html</span></span>
<span id="cb4-121">      is_valid <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">dir.exists</span>(norm_target)) {</span>
<span id="cb4-122">        idx <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(norm_target, <span class="st" style="color: #20794D;">"index.html"</span>)</span>
<span id="cb4-123">        <span class="fu" style="color: #4758AB;">file.exists</span>(idx) <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(idx)</span>
<span id="cb4-124">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb4-125">        <span class="fu" style="color: #4758AB;">file.exists</span>(norm_target)</span>
<span id="cb4-126">      }</span>
<span id="cb4-127"></span>
<span id="cb4-128">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>is_valid) {</span>
<span id="cb4-129">        bad_pages <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(bad_pages, rel_page)</span>
<span id="cb4-130">        bad_links <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(bad_links, u)</span>
<span id="cb4-131">        bad_paths <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(bad_paths, norm_target)</span>
<span id="cb4-132">      }</span>
<span id="cb4-133">    }</span>
<span id="cb4-134">  }</span>
<span id="cb4-135"></span>
<span id="cb4-136">  broken_df <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">data.frame</span>(</span>
<span id="cb4-137">    <span class="at" style="color: #657422;">page =</span> bad_pages,</span>
<span id="cb4-138">    <span class="at" style="color: #657422;">link =</span> bad_links,</span>
<span id="cb4-139">    <span class="at" style="color: #657422;">resolved_path =</span> bad_paths,</span>
<span id="cb4-140">    <span class="at" style="color: #657422;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb4-141">  )</span>
<span id="cb4-142">  <span class="fu" style="color: #4758AB;">attr</span>(broken_df, <span class="st" style="color: #20794D;">"checked"</span>) <span class="ot" style="color: #003B4F;">&lt;-</span> n_checked</span>
<span id="cb4-143"></span>
<span id="cb4-144">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb4-145">    <span class="at" style="color: #657422;">broken =</span> broken_df,</span>
<span id="cb4-146">    <span class="at" style="color: #657422;">checked =</span> n_checked</span>
<span id="cb4-147">  )</span>
<span id="cb4-148">}</span>
<span id="cb4-149"></span>
<span id="cb4-150"><span class="co" style="color: #5E5E5E;">#' Run demonstration on a temporary mock site</span></span>
<span id="cb4-151"><span class="co" style="color: #5E5E5E;">#' @return A list containing `broken` and `checked`.</span></span>
<span id="cb4-152"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb4-153">run_link_demo <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb4-154">  demo_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="fu" style="color: #4758AB;">paste0</span>(<span class="st" style="color: #20794D;">"link_demo_"</span>, <span class="fu" style="color: #4758AB;">Sys.getpid</span>()))</span>
<span id="cb4-155">  <span class="fu" style="color: #4758AB;">dir.create</span>(demo_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb4-156">  <span class="fu" style="color: #4758AB;">on.exit</span>(<span class="fu" style="color: #4758AB;">unlink</span>(demo_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>), <span class="at" style="color: #657422;">add =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb4-157"></span>
<span id="cb4-158">  <span class="co" style="color: #5E5E5E;"># 1. Target with encoded space (valid target)</span></span>
<span id="cb4-159">  <span class="fu" style="color: #4758AB;">writeLines</span>(</span>
<span id="cb4-160">    <span class="st" style="color: #20794D;">"&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;body&gt;Target with space&lt;/body&gt;&lt;/html&gt;"</span>,</span>
<span id="cb4-161">    <span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"my file.html"</span>)</span>
<span id="cb4-162">  )</span>
<span id="cb4-163"></span>
<span id="cb4-164">  <span class="co" style="color: #5E5E5E;"># 2. Folder without index.html (broken directory target)</span></span>
<span id="cb4-165">  templates_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"templates"</span>)</span>
<span id="cb4-166">  <span class="fu" style="color: #4758AB;">dir.create</span>(templates_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">showWarnings =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb4-167">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="st" style="color: #20794D;">"plain text"</span>, <span class="fu" style="color: #4758AB;">file.path</span>(templates_dir, <span class="st" style="color: #20794D;">"README.txt"</span>))</span>
<span id="cb4-168"></span>
<span id="cb4-169">  <span class="co" style="color: #5E5E5E;"># 3. Main HTML page with:</span></span>
<span id="cb4-170">  <span class="co" style="color: #5E5E5E;">#    - one broken link ("missing.html")</span></span>
<span id="cb4-171">  <span class="co" style="color: #5E5E5E;">#    - one folder link without index.html ("templates/")</span></span>
<span id="cb4-172">  <span class="co" style="color: #5E5E5E;">#    - one encoded space ("my%20file.html")</span></span>
<span id="cb4-173">  <span class="fu" style="color: #4758AB;">writeLines</span>(</span>
<span id="cb4-174">    <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb4-175">      <span class="st" style="color: #20794D;">"&lt;!DOCTYPE html&gt;"</span>,</span>
<span id="cb4-176">      <span class="st" style="color: #20794D;">"&lt;html&gt;"</span>,</span>
<span id="cb4-177">      <span class="st" style="color: #20794D;">"&lt;head&gt;&lt;title&gt;Link Checker Demo&lt;/title&gt;&lt;/head&gt;"</span>,</span>
<span id="cb4-178">      <span class="st" style="color: #20794D;">"&lt;body&gt;"</span>,</span>
<span id="cb4-179">      <span class="st" style="color: #20794D;">'  &lt;a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/missing.html"&gt;Missing Page&lt;/a&gt;'</span>,</span>
<span id="cb4-180">      <span class="st" style="color: #20794D;">'  &lt;a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/templates/"&gt;Templates Folder&lt;/a&gt;'</span>,</span>
<span id="cb4-181">      <span class="st" style="color: #20794D;">'  &lt;a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/my%20file.html"&gt;File with Space&lt;/a&gt;'</span>,</span>
<span id="cb4-182">      <span class="st" style="color: #20794D;">"&lt;/body&gt;"</span>,</span>
<span id="cb4-183">      <span class="st" style="color: #20794D;">"&lt;/html&gt;"</span></span>
<span id="cb4-184">    ),</span>
<span id="cb4-185">    <span class="fu" style="color: #4758AB;">file.path</span>(demo_dir, <span class="st" style="color: #20794D;">"index.html"</span>)</span>
<span id="cb4-186">  )</span>
<span id="cb4-187"></span>
<span id="cb4-188">  <span class="fu" style="color: #4758AB;">check_links</span>(demo_dir)</span>
<span id="cb4-189">}</span>
<span id="cb4-190"></span>
<span id="cb4-191"><span class="co" style="color: #5E5E5E;"># Run demo or check CLI directory when invoked directly as a script</span></span>
<span id="cb4-192"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb4-193">  args <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">commandArgs</span>(<span class="at" style="color: #657422;">trailingOnly =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb4-194">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(args) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb4-195">    target_dir <span class="ot" style="color: #003B4F;">&lt;-</span> args[<span class="dv" style="color: #AD0000;">1</span>L]</span>
<span id="cb4-196">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(target_dir)) {</span>
<span id="cb4-197">      <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb4-198">        <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Error: Directory '%s' does not exist.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, target_dir),</span>
<span id="cb4-199">        <span class="at" style="color: #657422;">file =</span> <span class="fu" style="color: #4758AB;">stderr</span>()</span>
<span id="cb4-200">      )</span>
<span id="cb4-201">      <span class="fu" style="color: #4758AB;">quit</span>(<span class="at" style="color: #657422;">save =</span> <span class="st" style="color: #20794D;">"no"</span>, <span class="at" style="color: #657422;">status =</span> <span class="dv" style="color: #AD0000;">1</span>L)</span>
<span id="cb4-202">    }</span>
<span id="cb4-203">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Checking internal links in '%s'...</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, target_dir))</span>
<span id="cb4-204">    report <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">check_links</span>(target_dir)</span>
<span id="cb4-205">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb4-206">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Running offline link check demonstration in temporary directory...</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb4-207">    report <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_link_demo</span>()</span>
<span id="cb4-208">  }</span>
<span id="cb4-209"></span>
<span id="cb4-210">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb4-211">    <span class="st" style="color: #20794D;">"Checked %d internal links; broken: %d</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb4-212">    report<span class="sc" style="color: #5E5E5E;">$</span>checked,</span>
<span id="cb4-213">    <span class="fu" style="color: #4758AB;">nrow</span>(report<span class="sc" style="color: #5E5E5E;">$</span>broken)</span>
<span id="cb4-214">  ))</span>
<span id="cb4-215">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">nrow</span>(report<span class="sc" style="color: #5E5E5E;">$</span>broken) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb4-216">    <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (i <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">seq_len</span>(<span class="fu" style="color: #4758AB;">min</span>(<span class="dv" style="color: #AD0000;">50</span>L, <span class="fu" style="color: #4758AB;">nrow</span>(report<span class="sc" style="color: #5E5E5E;">$</span>broken)))) {</span>
<span id="cb4-217">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb4-218">        <span class="st" style="color: #20794D;">"  [%s] %s -&gt; %s</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb4-219">        report<span class="sc" style="color: #5E5E5E;">$</span>broken<span class="sc" style="color: #5E5E5E;">$</span>page[i],</span>
<span id="cb4-220">        report<span class="sc" style="color: #5E5E5E;">$</span>broken<span class="sc" style="color: #5E5E5E;">$</span>link[i],</span>
<span id="cb4-221">        report<span class="sc" style="color: #5E5E5E;">$</span>broken<span class="sc" style="color: #5E5E5E;">$</span>resolved_path[i]</span>
<span id="cb4-222">      ))</span>
<span id="cb4-223">    }</span>
<span id="cb4-224">    <span class="fu" style="color: #4758AB;">quit</span>(<span class="at" style="color: #657422;">save =</span> <span class="st" style="color: #20794D;">"no"</span>, <span class="at" style="color: #657422;">status =</span> <span class="dv" style="color: #AD0000;">1</span>L)</span>
<span id="cb4-225">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb4-226">    <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"All internal links resolved successfully.</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb4-227">    <span class="fu" style="color: #4758AB;">quit</span>(<span class="at" style="color: #657422;">save =</span> <span class="st" style="color: #20794D;">"no"</span>, <span class="at" style="color: #657422;">status =</span> <span class="dv" style="color: #AD0000;">0</span>L)</span>
<span id="cb4-228">  }</span>
<span id="cb4-229">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Link checking and CI tools</strong></p>
<ul>
<li><strong>lychee</strong>: <a href="https://lychee.cli.rs/">lychee.cli.rs</a></li>
<li><strong>lychee-action</strong>: <a href="https://github.com/lycheeverse/lychee-action">github.com/lycheeverse/lychee-action</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>xml2</strong>: <a href="https://xml2.r-lib.org/">xml2.r-lib.org</a></li>
<li><strong>pkgdown</strong>: <a href="https://pkgdown.r-lib.org/">pkgdown.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Clarified directory link recommendations.</li>
<li><strong>2026-09-27:</strong> Replaced the Python script with an R link checker ({xml2}) and added companion code.</li>
</ul>
</div>
</div>
</div>



</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor site-related">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html" class="site-link-row" title="Run R CMD check, tests, and link validation automatically on clean GitHub Actions runners with pinned dependencies."><span class="is-card__eyebrow site-link-row__label">Builds on</span><span class="site-link-row__title">CI with GitHub Actions</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/building-this-blog/index.html" class="site-link-row" title="How we transformed a 14-part topic site into a Quarto engineering blog and portfolio using URL aliases, living-document conventions, and multi-model agentic collaboration."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Building this blog: from numbered topics to a living Quarto publication</span></a></li>
</ul>
</div>
</section>


 ]]></description>
  <category>Quarto</category>
  <category>CI/CD</category>
  <category>R packages</category>
  <guid>https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Conventional commits &amp; PR title checks</title>
  <link>https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Look at the history of most R repos and you’ll see <code>update</code>, <code>fix</code>, <code>wip</code>, <code>final version</code>, <code>final version 2</code>. The code may be excellent, but the history can’t answer basic questions:</p>
<ul>
<li>What changed for <strong>users</strong> since the last release?</li>
<li>Which change <strong>broke</strong> something?</li>
<li>Does this release need a <strong>major</strong>, minor or patch version bump?</li>
</ul>
<p>In a GxP setting the same history is also part of your change-control evidence. “fix” is not an adequate change description.</p>
</section>
<section id="the-standard-conventional-commits" class="level2">
<h2 class="anchored" data-anchor-id="the-standard-conventional-commits">The standard: Conventional Commits</h2>
<p><a href="https://www.conventionalcommits.org">Conventional Commits</a> is a tiny grammar for the first line of a commit message:</p>
<pre><code>&lt;type&gt;(&lt;optional scope&gt;)&lt;optional !&gt;: &lt;description&gt;</code></pre>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Type</th>
<th>Use it for</th>
<th>Version effect</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>feat</code></td>
<td>A new user-facing capability</td>
<td>minor</td>
</tr>
<tr class="even">
<td><code>fix</code></td>
<td>A bug fix</td>
<td>patch</td>
</tr>
<tr class="odd">
<td><code>docs</code></td>
<td>Documentation only</td>
<td>none</td>
</tr>
<tr class="even">
<td><code>test</code></td>
<td>Tests only</td>
<td>none</td>
</tr>
<tr class="odd">
<td><code>refactor</code></td>
<td>Code change with no behaviour change</td>
<td>none</td>
</tr>
<tr class="even">
<td><code>perf</code></td>
<td>Faster, same behaviour</td>
<td>patch</td>
</tr>
<tr class="odd">
<td><code>build</code>, <code>ci</code>, <code>chore</code>, <code>style</code>, <code>revert</code></td>
<td>Tooling, CI, housekeeping</td>
<td>none</td>
</tr>
<tr class="even">
<td><code>!</code> after the type, or a <code>BREAKING CHANGE:</code> footer</td>
<td>Breaks existing code</td>
<td><strong>major</strong></td>
</tr>
</tbody>
</table>
</div>
<p>R examples:</p>
<pre><code>feat(km_plot): add risk table below the curve
fix(read_adsl): keep labels when reading xpt files
docs: add vignette on ARD-based tables
feat!: require R &gt;= 4.3</code></pre>
<p>Scopes are free text. In an R package, use the <strong>function or module name</strong>, so that <code>git log --grep "(km_plot)"</code> finds every change to that function.</p>
</section>
<section id="the-key-idea-with-squash-merge-the-pr-title-is-the-commit" class="level2">
<h2 class="anchored" data-anchor-id="the-key-idea-with-squash-merge-the-pr-title-is-the-commit">The key idea: with squash-merge, the PR title <em>is</em> the commit</h2>
<p>If a repo allows only <strong>squash merges</strong> (<a href="https://insightsurge-dev.web.app/posts/git-workflow/index.html">git workflow</a>), each PR lands on <code>main</code> as <strong>one</strong> commit, and GitHub uses the <strong>PR title</strong> as that commit’s message:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="co" style="color: #5E5E5E;"># Repo setting, once (needs admin rights on the repo)</span></span>
<span id="cb3-2"><span class="ex" style="color: null;">gh</span> api <span class="at" style="color: #657422;">-X</span> PATCH repos/OWNER/REPO <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb3-3">  <span class="at" style="color: #657422;">-F</span> allow_squash_merge=true <span class="at" style="color: #657422;">-F</span> allow_merge_commit=false <span class="at" style="color: #657422;">-F</span> allow_rebase_merge=false <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb3-4">  <span class="at" style="color: #657422;">-f</span> squash_merge_commit_title=PR_TITLE <span class="at" style="color: #657422;">-f</span> squash_merge_commit_message=PR_BODY</span></code></pre></div></div>
<p>So the commits <em>on your branch</em> can stay informal (“try another approach”). What matters is the <strong>PR title</strong>, and that’s what you should check automatically.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>Two layers:</p>
<ol type="1">
<li><strong>Locally</strong>, <code>commitlint</code> runs in a <code>commit-msg</code> git hook (via <code>husky</code>) and rejects a bad message before the commit exists.</li>
<li><strong>In CI</strong>, a workflow checks the PR title on every edit:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># .github/workflows/pr-title.yml</span></span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;">on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull_request</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">types</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">opened</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> edited</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> reopened</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> synchronize</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb4-5"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-6"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull-requests</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read</span></span>
<span id="cb4-7"><span class="fu" style="color: #4758AB;">jobs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-8"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">conventional-title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-9"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">runs-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ubuntu-latest</span></span>
<span id="cb4-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-11"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> amannn/action-semantic-pull-request@v6</span></span>
<span id="cb4-12"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">env</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-13"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">GITHUB_TOKEN</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ secrets.GITHUB_TOKEN }}</span></span></code></pre></div></div>
<p>We tested this with a throwaway PR titled <code>updated the readme</code>. The check failed with <em>“No release type found in pull request title”</em>, while a PR titled <code>docs: clean PR probe</code> passed. Because the workflow also runs on <code>edited</code>, renaming a PR re-runs the check without a new commit.</p>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p><strong>The CI layer needs no Node at all.</strong> <code>pr-title.yml</code> is a hosted action, so you can drop the same file into any R package or Shiny repo: <a href="https://insightsurge-dev.web.app/templates/github/workflows/pr-title.yml"><code>templates/github/workflows/pr-title.yml</code></a>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full template: <code>pr-title.yml</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># Drop into .github/workflows/ of an R package or Shiny app repo.</span></span>
<span id="cb5-2"><span class="co" style="color: #5E5E5E;"># With squash-merge, the PR title becomes the commit on main, so check it here.</span></span>
<span id="cb5-3"><span class="co" style="color: #5E5E5E;"># No Node or npm needed in the R repo: this is a hosted action.</span></span>
<span id="cb5-4"><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> pr-title</span></span>
<span id="cb5-5"></span>
<span id="cb5-6"><span class="fu" style="color: #4758AB;">on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-7"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull_request</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">types</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">opened</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> edited</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> reopened</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> synchronize</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb5-9"></span>
<span id="cb5-10"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-11"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull-requests</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read</span></span>
<span id="cb5-12"></span>
<span id="cb5-13"><span class="fu" style="color: #4758AB;">jobs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-14"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">conventional-title</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-15"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">runs-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ubuntu-latest</span></span>
<span id="cb5-16"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-17"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> amannn/action-semantic-pull-request@v6</span></span>
<span id="cb5-18"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">env</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-19"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">GITHUB_TOKEN</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ secrets.GITHUB_TOKEN }}</span></span></code></pre></div></div>
</div>
</div>
</div>
<p><strong>For the local layer, skip <code>commitlint</code>.</strong> Pulling Node into an R package just for this isn’t worth it. A 15-line shell hook does the same job, and <code>usethis</code> installs it. Save <a href="https://insightsurge-dev.web.app/templates/git-hooks/commit-msg"><code>templates/git-hooks/commit-msg</code></a> in your project root as <code>commit-msg</code>:</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full template: <code>commit-msg</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="co" style="color: #5E5E5E;">#!/bin/sh</span></span>
<span id="cb6-2"><span class="co" style="color: #5E5E5E;"># Conventional Commits check for repos without Node (R packages, Shiny apps).</span></span>
<span id="cb6-3"><span class="co" style="color: #5E5E5E;"># Install from R:  usethis::use_git_hook("commit-msg", readLines("commit-msg"))</span></span>
<span id="cb6-4"><span class="va" style="color: #111111;">first_line</span><span class="op" style="color: #5E5E5E;">=</span><span class="va" style="color: #111111;">$(</span><span class="fu" style="color: #4758AB;">head</span> <span class="at" style="color: #657422;">-n</span> 1 <span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$1</span><span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">)</span></span>
<span id="cb6-5"><span class="cf" style="color: #003B4F;
font-weight: bold;">case</span> <span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$first_line</span><span class="st" style="color: #20794D;">"</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">in</span></span>
<span id="cb6-6">  <span class="ss" style="color: #20794D;">Merge</span><span class="dt" style="color: #AD0000;">\ </span><span class="pp" style="color: #AD0000;">*</span><span class="kw" style="color: #003B4F;
font-weight: bold;">|</span><span class="ss" style="color: #20794D;">Revert</span><span class="dt" style="color: #AD0000;">\ </span><span class="pp" style="color: #AD0000;">*</span><span class="kw" style="color: #003B4F;
font-weight: bold;">|</span><span class="ss" style="color: #20794D;">fixup!</span><span class="dt" style="color: #AD0000;">\ </span><span class="pp" style="color: #AD0000;">*</span><span class="kw" style="color: #003B4F;
font-weight: bold;">|</span><span class="ss" style="color: #20794D;">squash!</span><span class="dt" style="color: #AD0000;">\ </span><span class="pp" style="color: #AD0000;">*</span><span class="kw" style="color: #003B4F;
font-weight: bold;">)</span> <span class="bu" style="color: null;">exit</span> 0 <span class="cf" style="color: #003B4F;
font-weight: bold;">;;</span></span>
<span id="cb6-7"><span class="cf" style="color: #003B4F;
font-weight: bold;">esac</span></span>
<span id="cb6-8"><span class="va" style="color: #111111;">pattern</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">'^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9_./-]+\))?!?: .+'</span></span>
<span id="cb6-9"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> <span class="bu" style="color: null;">printf</span> <span class="st" style="color: #20794D;">'%s'</span> <span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$first_line</span><span class="st" style="color: #20794D;">"</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-Eq</span> <span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$pattern</span><span class="st" style="color: #20794D;">"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">then</span></span>
<span id="cb6-10">  <span class="bu" style="color: null;">exit</span> 0</span>
<span id="cb6-11"><span class="cf" style="color: #003B4F;
font-weight: bold;">fi</span></span>
<span id="cb6-12"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"✖ Commit message is not a Conventional Commit:"</span> <span class="op" style="color: #5E5E5E;">&gt;&amp;</span><span class="dv" style="color: #AD0000;">2</span></span>
<span id="cb6-13"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"    </span><span class="va" style="color: #111111;">$first_line</span><span class="st" style="color: #20794D;">"</span> <span class="op" style="color: #5E5E5E;">&gt;&amp;</span><span class="dv" style="color: #AD0000;">2</span></span>
<span id="cb6-14"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"  Expected: &lt;type&gt;(&lt;optional scope&gt;): &lt;description&gt;"</span> <span class="op" style="color: #5E5E5E;">&gt;&amp;</span><span class="dv" style="color: #AD0000;">2</span></span>
<span id="cb6-15"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"  e.g.  feat(read_adsl): support SAS transport files"</span> <span class="op" style="color: #5E5E5E;">&gt;&amp;</span><span class="dv" style="color: #AD0000;">2</span></span>
<span id="cb6-16"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"        fix: handle empty data in km_plot()"</span> <span class="op" style="color: #5E5E5E;">&gt;&amp;</span><span class="dv" style="color: #AD0000;">2</span></span>
<span id="cb6-17"><span class="bu" style="color: null;">exit</span> 1</span></code></pre></div></div>
</div>
</div>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_git_hook</span>(</span>
<span id="cb7-2">  <span class="st" style="color: #20794D;">"commit-msg"</span>,</span>
<span id="cb7-3">  <span class="fu" style="color: #4758AB;">readLines</span>(<span class="st" style="color: #20794D;">"commit-msg"</span>)</span>
<span id="cb7-4">)</span></code></pre></div></div>
<p>We tested the hook against these messages:</p>
<div class="table-responsive">
<table class="caption-top table">
<thead>
<tr class="header">
<th>Message</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>feat(read_adsl): support xpt files</code></td>
<td>✓</td>
</tr>
<tr class="even">
<td><code>feat!: drop R 4.1 support</code></td>
<td>✓</td>
</tr>
<tr class="odd">
<td><code>Merge branch 'main'</code></td>
<td>✓ (merges and reverts are let through)</td>
</tr>
<tr class="even">
<td><code>updated stuff</code></td>
<td>✗</td>
</tr>
<tr class="odd">
<td><code>Feat: capitalised type</code></td>
<td>✗</td>
</tr>
<tr class="even">
<td><code>feat:missing space</code></td>
<td>✗</td>
</tr>
</tbody>
</table>
</div>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Hooks are local and optional; CI is the gate
</div>
</div>
<div class="callout-body-container callout-body">
<p>Git hooks live in <code>.git/hooks/</code>, which is never committed, so every clone has to install them. Treat the local hook as a convenience that catches mistakes early. The <strong>PR title check in CI</strong> is the actual rule, because nobody can skip it.</p>
</div>
</div>
</section>
<section id="what-you-get-in-return" class="level2">
<h2 class="anchored" data-anchor-id="what-you-get-in-return">What you get in return</h2>
<ul>
<li><strong>A readable history:</strong> <code>git log --oneline</code> reads like a changelog.</li>
<li><strong>Automatic version bumps and NEWS/CHANGELOG entries.</strong> Tools read <code>feat</code>/<code>fix</code>/<code>!</code> to decide the next version (<a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html">releases &amp; changelogs</a>).</li>
<li><strong>Faster review:</strong> the title tells the reviewer what kind of change to expect.</li>
<li><strong>Better change-control evidence:</strong> each change on <code>main</code> has a type, a scope, a description and a linked PR with its review and CI results.</li>
</ul>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>The title check only runs when the PR changes.</strong> It’s triggered by <code>edited</code>, so after renaming a PR the check re-runs by itself, and you don’t need to push again.</li>
<li><strong>Squash settings are per repo.</strong> New repos default to allowing all three merge methods. Set squash-only when you create the repo.</li>
<li><strong>Don’t over-engineer scopes.</strong> Free-text function names beat a mandated list nobody remembers.</li>
<li><strong>Merge commits from <code>git pull</code></strong> would fail a strict hook. The template lets <code>Merge …</code> and <code>Revert …</code> through, and <code>pull.rebase = true</code> avoids them anyway.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards and tools</strong></p>
<ul>
<li><strong>Conventional Commits</strong>: <a href="https://www.conventionalcommits.org/en/v1.0.0/">conventionalcommits.org</a></li>
<li><strong>commitlint</strong>: <a href="https://commitlint.js.org/">commitlint.js.org</a></li>
<li><strong>husky</strong>: <a href="https://typicode.github.io/husky/">typicode.github.io/husky</a></li>
<li><strong>amannn/action-semantic-pull-request</strong>: <a href="https://github.com/amannn/action-semantic-pull-request">github.com/amannn/action-semantic-pull-request</a></li>
<li><strong>Squash merging: PR title becomes the commit message</strong>: <a href="https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/configuring-commit-squashing-for-pull-requests">GitHub Docs: Configuring commit squashing for pull requests</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>use_git_hook()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-4-contents" aria-controls="callout-4" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-4" class="callout-4-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Linked every template file and showed it on the page.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 3 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/git-workflow/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 2</span><span class="site-related-card__title">Git workflow: branches, squash-only merges, signed commits</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 4</span><span class="site-related-card__title">Pre-commit hooks, formatting &amp; linting</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html" class="site-link-row" title="Adopt semantic versioning, readable changelogs, and annotated git tags to support change control."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Releases &amp; changelogs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/index.html" class="site-link-row" title="Move reusable analysis helpers from sourced scripts into a minimal R package, and replace workspace pollution with the devtools::load_all() loop."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">From scripts to a package</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="site-link-row" title="Use the R package development loop, read R CMD check diagnostics, and fix four recurring problems."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">The package development loop and R CMD check</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Git</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Dependency updates, runtime pinning &amp; package vetting</title>
  <link>https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="three-separate-questions" class="level2">
<h2 class="anchored" data-anchor-id="three-separate-questions">Three separate questions</h2>
<ol type="1">
<li><strong>Updates:</strong> how do we learn that a dependency has a new version, and apply it safely?</li>
<li><strong>Pinning:</strong> which versions (of R, of packages, of tools) must stay fixed, and where is that written down?</li>
<li><strong>Vetting:</strong> before adding a new dependency, is it trustworthy and maintained?</li>
</ol>
</section>
<section id="updates-dependabot-and-what-it-cant-do" class="level2">
<h2 class="anchored" data-anchor-id="updates-dependabot-and-what-it-cant-do">1 · Updates: Dependabot, and what it can’t do</h2>
<p>On the website repo, Dependabot checks npm packages and GitHub Actions <strong>monthly</strong>, and groups minor/patch updates into one PR per group:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="co" style="color: #5E5E5E;"># .github/dependabot.yml (npm block)</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">groups</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">production</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">dependency-type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> production</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">update-types</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">minor</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> patch</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">development</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">dependency-type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> development</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">update-types</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">minor</span><span class="kw" style="color: #003B4F;
font-weight: bold;">,</span><span class="at" style="color: #657422;"> patch</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;">ignore</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-6"><span class="co" style="color: #5E5E5E;">  # runtime pinned to Node 24; bump with .nvmrc</span></span>
<span id="cb1-7"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">dependency-name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"@types/node"</span></span>
<span id="cb1-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">update-types</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="st" style="color: #20794D;">"version-update:semver-major"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span></code></pre></div></div>
<p>Within minutes of the first push it opened three PRs, and all three passed CI. The decisions still needed judgement:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>PR</th>
<th>Decision</th>
<th>Evidence</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>React 19.2.8 → 19.3.0 (grouped minor)</td>
<td><strong>Merge</strong></td>
<td>Inside Next’s declared peer range <code>^19.0.0</code></td>
</tr>
<tr class="even">
<td><code>@types/node</code> 24 → 26 (major)</td>
<td><strong>Close + ignore majors</strong></td>
<td>Runtime is pinned to Node 24; the types must match the runtime, not the latest</td>
</tr>
<tr class="odd">
<td>TypeScript 5.9 → 7.0 (major)</td>
<td><strong>Merge</strong></td>
<td>Next.js’s bundled docs have a “Using TypeScript 7” section</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Green CI is necessary, not sufficient.</strong> Major updates arrive as separate PRs <em>by design</em>. Read the changelog, and check compatibility with what’s pinned.</p>
<p><strong>For R:</strong> Dependabot has <strong>no R/CRAN/renv ecosystem</strong> (checked against GitHub’s list of supported ecosystems). It can still keep an R repo’s <strong>GitHub Actions</strong> and <strong>pre-commit hooks</strong> current (<code>github-actions</code> and <code>pre-commit</code> ecosystems). A ready-to-use configuration is in <a href="https://insightsurge-dev.web.app/templates/github/dependabot.yml"><code>templates/github/dependabot.yml</code></a>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full template: <code>dependabot.yml</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># Drop into .github/dependabot.yml.</span></span>
<span id="cb2-2"><span class="co" style="color: #5E5E5E;"># Dependabot cannot update R packages (no CRAN/renv ecosystem), but it CAN keep</span></span>
<span id="cb2-3"><span class="co" style="color: #5E5E5E;"># your GitHub Actions (r-lib/actions, checkout, ...) current.</span></span>
<span id="cb2-4"><span class="fu" style="color: #4758AB;">version</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">2</span></span>
<span id="cb2-5"><span class="fu" style="color: #4758AB;">updates</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-6"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">package-ecosystem</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> github-actions</span></span>
<span id="cb2-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">directory</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> /</span></span>
<span id="cb2-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">schedule</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-9"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">interval</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> monthly</span></span>
<span id="cb2-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">commit-message</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-11"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">prefix</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"ci"</span></span>
<span id="cb2-12"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">groups</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-13"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">actions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-14"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">patterns</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="st" style="color: #20794D;">"*"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span></code></pre></div></div>
</div>
</div>
</div>
<p>For packages, schedule the update yourself:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">renv<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">status</span>()     <span class="co" style="color: #5E5E5E;"># is the lockfile in sync with the library?</span></span>
<span id="cb3-2">renv<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">update</span>()     <span class="co" style="color: #5E5E5E;"># update packages in the project library</span></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;"># run tests / R CMD check, then:</span></span>
<span id="cb3-4">renv<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">snapshot</span>()   <span class="co" style="color: #5E5E5E;"># record the new versions in renv.lock</span></span></code></pre></div></div>
<p>Make it a routine, and review the diff of <code>renv.lock</code> like any other PR. A pattern that works:</p>
<ul>
<li><strong>A monthly scheduled workflow opens an issue</strong> listing the packages in <code>renv.lock</code> that have newer versions (compare the locked versions with <code>available.packages()</code> from the package manager’s <code>latest</code> snapshot). An issue, not a PR: by default the workflow token can’t open pull requests (the repository setting “Allow GitHub Actions to create and approve pull requests” is off), and a person should decide when to update anyway.</li>
<li><strong>A small update script</strong> moves to a newer snapshot, runs <code>renv::update()</code>, runs the tests, and calls <code>renv::snapshot()</code> only if they pass. If they fail, <code>renv::restore()</code> puts the old versions back.</li>
</ul>
</section>
<section id="pinning-runtimes-and-repositories" class="level2">
<h2 class="anchored" data-anchor-id="pinning-runtimes-and-repositories">2 · Pinning: runtimes and repositories</h2>
<div class="table-responsive">
<table class="caption-top table">
<thead>
<tr class="header">
<th>What</th>
<th>Web repo</th>
<th>R project</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Runtime version</td>
<td><code>.nvmrc</code> → CI reads it</td>
<td><code>renv.lock</code> records R; <code>setup-r</code> with <code>r-version: renv</code> reads it</td>
</tr>
<tr class="even">
<td>Switching runtimes locally</td>
<td>nvm/fnm</td>
<td><a href="https://github.com/r-lib/rig"><code>rig</code></a>: <code>rig add release</code>, <code>rig list</code>, <code>rig default 4.5.1</code></td>
</tr>
<tr class="odd">
<td>Exact package versions</td>
<td><code>package-lock.json</code> + <code>npm ci</code></td>
<td><code>renv.lock</code> + <code>renv::restore()</code></td>
</tr>
<tr class="even">
<td>Package source</td>
<td>Project <code>.npmrc</code>: <code>registry=https://registry.npmjs.org/</code></td>
<td><code>options(repos = …)</code> or renv’s repos, e.g.&nbsp;a dated <strong>Posit Package Manager</strong> snapshot <code>https://packagemanager.posit.co/cran/2026-09-01</code></td>
</tr>
</tbody>
</table>
</div>
<p><strong>Pin per project, not per machine.</strong> A CLI we needed (<code>firebase-tools</code>) refused to install on the Mac’s Node 26: one of its dependencies declared <code>engines: node 20 || 22 || 24</code>. The fix wasn’t downgrading the whole machine. We deferred the tool and let CI run the pinned Node 24. It’s the same idea as keeping one project on R 4.4 with <code>rig</code> while the rest move on.</p>
<p>A dated package-manager snapshot is the R superpower here. Every install in that project resolves to CRAN <em>as it was on that date</em>, on every machine and in CI.</p>
<p>Three things we learned setting this up with renv:</p>
<ul>
<li><strong>renv takes the repository from <code>renv.lock</code>.</strong> When the project loads, renv sets <code>options(repos)</code> from the lockfile, so a <code>repos</code> line in <code>.Rprofile</code> is quietly overridden. Record the snapshot URL in the lockfile instead: <code>renv::snapshot(repos = c(CRAN = "https://packagemanager.posit.co/cran/2026-09-26"))</code>.</li>
<li><strong>Binaries on macOS too.</strong> Posit Package Manager serves binaries for macOS as well as Linux. The path depends on the R build (for R 4.6 on Apple silicon it’s <code>sonoma-arm64</code>), so ask R rather than guessing: <code>contrib.url(getOption("repos"), "binary")</code>. On Linux, a binary still needs its <strong>system libraries</strong> (<code>keyring</code> needs <code>libsecret</code>, for example): <code>renv::sysreqs()</code> lists them, and CI must install them before <code>renv::restore()</code>.</li>
<li><strong>A project that isn’t a package can still declare its packages.</strong> Put them in a <code>DESCRIPTION</code> file and set <code>renv::settings$snapshot.type("explicit")</code>. renv then records exactly that list (plus dependencies) rather than whatever it finds in the code, which also covers packages you’ve planned for but not used yet.</li>
</ul>
</section>
<section id="vetting-look-before-you-install.packages" class="level2">
<h2 class="anchored" data-anchor-id="vetting-look-before-you-install.packages">3 · Vetting: look before you <code>install.packages()</code></h2>
<p>Our UI library’s installer quietly swapped two well-known helpers for a new package literally named <strong><code>cn</code></strong>. A name that generic is exactly what typosquatters use. Two minutes of checks:</p>
<ul>
<li><strong>Who publishes it?</strong> Its npm maintainer was the UI library’s author.</li>
<li><strong>Where’s the source?</strong> It linked to a repo in the same GitHub organisation.</li>
<li><strong>Is it used and maintained?</strong> Recent releases, and the issues get answered.</li>
</ul>
<p>For R, the R Validation Hub’s tools make this systematic and documentable, which is useful for GxP package risk assessment:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;">library</span>(riskmetric)</span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;">pkg_ref</span>(<span class="st" style="color: #20794D;">"ggsurvfit"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span> <span class="fu" style="color: #4758AB;">pkg_assess</span>() <span class="sc" style="color: #5E5E5E;">|&gt;</span> <span class="fu" style="color: #4758AB;">pkg_score</span>()   <span class="co" style="color: #5E5E5E;"># maintenance, testing, documentation, community metrics</span></span></code></pre></div></div>
<p><a href="https://github.com/pharmaR/riskassessment"><code>riskassessment</code></a> wraps <code>riskmetric</code> in a Shiny app for team review and sign-off.</p>
</section>
<section id="letting-a-second-model-do-the-legwork" class="level2">
<h2 class="anchored" data-anchor-id="letting-a-second-model-do-the-legwork">Letting a second model do the legwork</h2>
<p>We delegated the Dependabot analysis to a second LLM (Gemini). Its job was to read the peer ranges and the bundled docs and propose a decision per PR. Its conclusions held up, but <strong>every piece of evidence was re-checked by opening the cited files</strong> before anything was merged, and its diff was reviewed line by line. That review also caught a nuance it had glossed over: the related Next.js option is marked <em>experimental</em>. Delegate the reading; keep the decision and the verification.</p>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Dependabot</strong></p>
<ul>
<li><strong>Dependabot overview</strong>: <a href="https://docs.github.com/en/code-security/dependabot">GitHub Docs: Dependabot</a></li>
<li><strong>Supported ecosystems (no R/CRAN/renv ecosystem)</strong>: <a href="https://docs.github.com/en/code-security/dependabot/ecosystems-supported-by-dependabot/supported-ecosystems-and-repositories">GitHub Docs: Ecosystems supported by Dependabot</a></li>
</ul>
<p><strong>R tooling</strong></p>
<ul>
<li><strong>renv</strong>: <a href="https://rstudio.github.io/renv/">rstudio.github.io/renv</a></li>
<li><strong>rig</strong>: <a href="https://github.com/r-lib/rig">github.com/r-lib/rig</a></li>
<li><strong>Posit Package Manager</strong>: <a href="https://packagemanager.posit.co/client/#/repos/cran/setup">packagemanager.posit.co</a></li>
<li><strong>keyring</strong> (system library requirement, <code>libsecret</code>): <a href="https://keyring.r-lib.org/">keyring.r-lib.org</a></li>
</ul>
<p><strong>Vetting</strong></p>
<ul>
<li><strong>R Validation Hub</strong>: <a href="https://pharmar.org/">pharmar.org</a></li>
<li><strong>riskmetric</strong>: <a href="https://pharmar.github.io/riskmetric/">pharmar.github.io/riskmetric</a></li>
<li><strong>riskassessment</strong>: <a href="https://pharmar.github.io/riskassessment/">pharmar.github.io/riskassessment</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-26:</strong> Added what we learned putting a project on renv with a dated Posit Package Manager snapshot: renv takes the repository from <code>renv.lock</code>, binaries are available for macOS too (but Linux binaries still need system libraries), and explicit snapshots suit projects that aren’t packages. Described the monthly update issue and the test-gated update script.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Linked every template file and showed it on the page.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 10 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 9</span><span class="site-related-card__title">Releases &amp; changelogs</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/test-your-guardrails/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 11</span><span class="site-related-card__title">Test your guardrails: probe PRs</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/index.html" class="site-link-row" title="Declare external packages in DESCRIPTION Imports and Suggests, call functions through pkg::fun() or @importFrom, and guard optional dependencies cleanly."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Dependencies: DESCRIPTION and NAMESPACE</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/index.html" class="site-link-row" title="Why independent programming exists in clinical reporting, how risk-based QC structures verification tiers, and how to reconcile datasets and results in R with diffdf."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">QC and double programming with {diffdf}</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>GxP</category>
  <category>Security</category>
  <guid>https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Deploy a Quarto site with a preview for every pull request</title>
  <link>https://insightsurge-dev.web.app/posts/quarto-firebase-previews/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Reviewing technical documentation or rendered reports in a pull request diff is notoriously unreliable:</p>
<ol type="1">
<li><strong>Markdown diffs hide visual defects.</strong> A git diff shows line changes, but it cannot show broken CSS layouts, overflowing tables, mangled cross-references, or misaligned typography.</li>
<li><strong>Local rendering does not scale across a team.</strong> Asking reviewers to clone the branch, install matching tool versions, and run <code>quarto render</code> locally creates friction. Small errors slip into production because nobody rendered the full site.</li>
<li><strong>GitHub Pages limitations.</strong> On GitHub Free accounts, GitHub Pages functions exclusively on <strong>public</strong> repositories. If your source code, drafting notes, or research documents are kept in a private repository, GitHub Pages is unavailable. Even on GitHub Pro plans where private repositories can publish to Pages, the rendered site is published to a single static URL with no native concept of pull request preview channels.</li>
</ol>
<p>Teams need isolated, temporary preview environments for every pull request that spin up automatically, update on subsequent pushes, and expire when review concludes.</p>
</section>
<section id="the-web-repo-way-firebase-hosting-channels" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-firebase-hosting-channels">The web-repo way: Firebase Hosting channels</h2>
<p>Modern web applications solve this using ephemeral hosting channels. Google Firebase Hosting provides preview channels out-of-the-box, allowing static sites to deploy to an unlisted, temporary URL.</p>
<section id="minimal-hosting-configuration" class="level3">
<h3 class="anchored" data-anchor-id="minimal-hosting-configuration">1. Minimal hosting configuration</h3>
<p>A standard <code>firebase.json</code> file in the repository root defines the static output directory generated by Quarto (<code>_site</code>):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode json code-with-copy"><code class="sourceCode json"><span id="cb1-1"><span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb1-2">  <span class="dt" style="color: #AD0000;">"hosting"</span><span class="fu" style="color: #4758AB;">:</span> <span class="fu" style="color: #4758AB;">{</span></span>
<span id="cb1-3">    <span class="dt" style="color: #AD0000;">"public"</span><span class="fu" style="color: #4758AB;">:</span> <span class="st" style="color: #20794D;">"_site"</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb1-4">    <span class="dt" style="color: #AD0000;">"cleanUrls"</span><span class="fu" style="color: #4758AB;">:</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">true</span><span class="fu" style="color: #4758AB;">,</span></span>
<span id="cb1-5">    <span class="dt" style="color: #AD0000;">"ignore"</span><span class="fu" style="color: #4758AB;">:</span> <span class="ot" style="color: #003B4F;">[</span><span class="st" style="color: #20794D;">"firebase.json"</span><span class="ot" style="color: #003B4F;">,</span> <span class="st" style="color: #20794D;">"**/.*"</span><span class="ot" style="color: #003B4F;">]</span></span>
<span id="cb1-6">  <span class="fu" style="color: #4758AB;">}</span></span>
<span id="cb1-7"><span class="fu" style="color: #4758AB;">}</span></span></code></pre></div></div>
<p>Setting <code>cleanUrls: true</code> ensures that Firebase Hosting serves <code>page.html</code> at <code>/page</code> (dropping the <code>.html</code> extension) and redirects <code>.html</code> URLs to the clean form.</p>
</section>
<section id="ephemeral-previews-in-github-actions" class="level3">
<h3 class="anchored" data-anchor-id="ephemeral-previews-in-github-actions">2. Ephemeral previews in GitHub Actions</h3>
<p>In <code>.github/workflows/quarto.yml</code>, the workflow renders the site and deploys PRs directly to a designated channel named <code>pr-&lt;number&gt;</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Deploy PR preview channel</span></span>
<span id="cb2-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">if</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> env.DEPLOY_ENABLED == 'true' &amp;&amp; github.event_name == 'pull_request'</span></span>
<span id="cb2-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> preview</span></span>
<span id="cb2-4"><span class="fu" style="color: #4758AB;">  run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">: </span><span class="ch" style="color: #20794D;">|</span></span>
<span id="cb2-5">    npx --yes "$FIREBASE_TOOLS" hosting:channel:deploy "pr-${{ github.event.number }}" \</span>
<span id="cb2-6">      --project "${{ vars.FIREBASE_PROJECT_ID }}" --expires 7d --json &gt; deploy.json</span>
<span id="cb2-7">    url=$(node -e 'const r=require("./deploy.json").result;console.log(Object.values(r)[0].url)')</span>
<span id="cb2-8">    echo "url=$url" &gt;&gt; "$GITHUB_OUTPUT"</span>
<span id="cb2-9"></span>
<span id="cb2-10"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Comment preview URL</span></span>
<span id="cb2-11"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">if</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> steps.preview.outputs.url != ''</span></span>
<span id="cb2-12"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">env</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-13"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">GH_TOKEN</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ secrets.GITHUB_TOKEN }}</span></span>
<span id="cb2-14"><span class="fu" style="color: #4758AB;">  run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">: </span><span class="ch" style="color: #20794D;">|</span></span>
<span id="cb2-15">    gh pr comment "${{ github.event.number }}" --edit-last --create-if-none \</span>
<span id="cb2-16">      --body "📘 Preview: ${{ steps.preview.outputs.url }} (expires in 7 days)"</span></code></pre></div></div>
</section>
<section id="posting-and-updating-the-review-link" class="level3">
<h3 class="anchored" data-anchor-id="posting-and-updating-the-review-link">3. Posting and updating the review link</h3>
<p>The workflow captures the generated preview URL—which follows the structure <code>https://&lt;project&gt;--pr-&lt;number&gt;-&lt;hash&gt;.web.app</code>—and comments it directly onto the pull request. Using <code>gh pr comment --edit-last --create-if-none</code> ensures that repeated commits to the same pull request update the existing comment rather than generating comment spam.</p>
<p>When the branch is merged into <code>main</code>, the workflow executes a standard live deployment:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb3-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Deploy live (dev) site</span></span>
<span id="cb3-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">if</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> env.DEPLOY_ENABLED == 'true' &amp;&amp; github.event_name != 'pull_request'</span></span>
<span id="cb3-3"><span class="fu" style="color: #4758AB;">  run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">: </span><span class="ch" style="color: #20794D;">|</span></span>
<span id="cb3-4">    npx --yes "$FIREBASE_TOOLS" deploy --only hosting \</span>
<span id="cb3-5">      --project "${{ vars.FIREBASE_PROJECT_ID }}" --non-interactive</span></code></pre></div></div>
<p>All credentials are exchanged keylessly via Workload Identity Federation (see <a href="https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/index.html">keyless CI deploys</a>), meaning no service account keys exist in the repository.</p>
</section>
</section>
<section id="what-we-observed" class="level2">
<h2 class="anchored" data-anchor-id="what-we-observed">What we observed</h2>
<p>Our live dev deployment and preview channels were verified on 2026-09-26:</p>
<ul>
<li><strong>Automated commenting:</strong> On opening a pull request, the workflow authenticated, provisioned the Firebase Hosting channel <code>pr-2</code>, and left a single formatted comment with the live preview link.</li>
<li><strong>Graceful degradation:</strong> The deployment step evaluates a safety gate (<code>DEPLOY_ENABLED</code>). If the repository variables for Google Cloud have not yet been configured, the deployment steps skip without breaking the build, allowing Quarto rendering and link checking to proceed unhindered.</li>
<li><strong>Fork security:</strong> Fork PRs get a read-only token and no secrets; our workflow additionally skips deploys when <code>head.repo.full_name != github.repository</code>.</li>
<li><strong>Automatic retirement:</strong> Channels deploy with <code>--expires 7d</code>. Channels expire 7 days after the last deploy to that channel (each push redeploys and resets the timer), preventing orphaned staging sites from accumulating.</li>
</ul>
</section>
<section id="the-r-way-pkgdown-sites-and-quarto-reports" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-pkgdown-sites-and-quarto-reports">The R way: pkgdown sites and Quarto reports</h2>
<p>This architecture is not restricted to websites; it fits any static HTML generated by R tooling.</p>
<section id="pkgdown-documentation" class="level3">
<h3 class="anchored" data-anchor-id="pkgdown-documentation">pkgdown documentation</h3>
<p>An R package documentation site created with <code>pkgdown::build_site()</code> writes its static assets to the <code>docs/</code> folder. By pointing <code>firebase.json</code>’s <code>public</code> key to <code>docs</code>, the exact same preview pipeline can deploy previews of your package documentation whenever an author opens a pull request. Reviewers can click through reference manual updates and vignettes before the code is merged.</p>
</section>
<section id="quarto-clinical-and-scientific-reports" class="level3">
<h3 class="anchored" data-anchor-id="quarto-clinical-and-scientific-reports">Quarto clinical and scientific reports</h3>
<p>Complex Quarto reports often contain tabsets, interactive HTML widgets, and extensive data tables that cannot be adequately evaluated in code review. Building the report in CI and shipping it to an ephemeral preview channel gives statisticians, clinicians, and quality auditors a fully functional artifact to examine.</p>
</section>
<section id="deployment-alternatives" class="level3">
<h3 class="anchored" data-anchor-id="deployment-alternatives">Deployment alternatives</h3>
<p>Other platforms offer preview capabilities for static R outputs:</p>
<ul>
<li><strong>Posit Connect:</strong> Excellent for enterprise internal deployment, supporting both Shiny apps and static Quarto reports. Previews typically require publishing to distinct content items or managing access controls within the Connect server.</li>
<li><strong>Quarto Pub:</strong> Simple and built directly into Quarto, but all published content is public.</li>
<li><strong>Netlify:</strong> Provides native deploy previews for static sites by monitoring GitHub pull requests, but introduces an additional third-party vendor if your organisation already standardises on Google Cloud, AWS, or Azure.</li>
</ul>
</section>
</section>
<section id="pitfalls-we-hit" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-we-hit">Pitfalls we hit</h2>
<ul>
<li><strong>Channel sprawl without expiry:</strong> Forgetting the <code>--expires</code> flag leaves old preview channels active indefinitely. Setting <code>--expires 7d</code> ensures automatic garbage collection.</li>
<li><strong>Silent skips during initial setup:</strong> If repository variables (<code>GCP_WORKLOAD_IDENTITY_PROVIDER</code>, <code>GCP_SERVICE_ACCOUNT</code>, <code>FIREBASE_PROJECT_ID</code>) are absent or misspelled, <code>DEPLOY_ENABLED</code> evaluates to <code>false</code> and the deployment step skips quietly. Check the job log variables if a preview comment fails to appear.</li>
<li><strong>PR comment flooding:</strong> Running a naive <code>gh pr comment</code> without <code>--edit-last</code> leaves a new comment on every push, drowning out conversation. Always use <code>--edit-last --create-if-none</code>.</li>
<li><strong>Public URL discovery:</strong> Firebase preview URLs are unlisted, but they are accessible on the public internet. Firebase Hosting has no built-in access control for static content, so keep content generic and free of proprietary data, or use a host with access control (such as Posit Connect).</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
</ul>
</div>
</div>
</div>



</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor site-related">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html" class="site-link-row" title="Run R CMD check, tests, and link validation automatically on clean GitHub Actions runners with pinned dependencies."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">CI with GitHub Actions</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/index.html" class="site-link-row" title="Use OpenID Connect and Google Cloud Workload Identity Federation to authenticate CI pipelines without long-lived JSON keys."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Keyless deploys: let CI prove who it is (OIDC)</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/link-checking-rendered-sites/index.html" class="site-link-row" title="Validate internal links across rendered documentation in CI using offline link scanners to block broken references before release."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Catch broken links before your readers do</span></a></li>
</ul>
</div>
</section>


 ]]></description>
  <category>Quarto</category>
  <category>CI/CD</category>
  <category>R packages</category>
  <guid>https://insightsurge-dev.web.app/posts/quarto-firebase-previews/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>End-to-end Shiny tests with shinytest2</title>
  <link>https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Unit tests written with <a href="https://testthat.r-lib.org/">{testthat}</a>—as covered in <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html">the first post in this series</a> and in our discussion of <a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/index.html">test fixtures and mocking</a>—verify isolated data transformations and business logic. The previous post covered <code>testServer()</code>, which tests server-side reactivity directly in memory. Running in milliseconds without launching a network server or a browser, <code>testServer()</code> is ideal for verifying reactive calculations, internal session state, and output expressions.</p>
<p>Yet <code>testServer()</code> never executes code in a client browser. This leaves substantial blind spots:</p>
<ul>
<li><strong>No DOM or HTML rendering:</strong> <code>testServer()</code> computes output values, but it never renders them into actual Document Object Model (DOM) nodes. Missing HTML tags, malformed layouts, missing CSS assets, or mismatched element IDs remain completely undetected.</li>
<li><strong>No JavaScript execution:</strong> Client-side widgets such as interactive tables, plotting canvases, dynamic UI insertions, and custom JavaScript input bindings depend entirely on the browser’s JavaScript engine. Any custom event handler calling <code>Shiny.setInputValue()</code> in JavaScript never runs under <code>testServer()</code>.</li>
<li><strong>No bookmarking or URL state:</strong> Applications that restore state through URL query parameters or <code>enableBookmarking()</code> rely on browser navigation events and client-to-server synchronization.</li>
<li><strong>No WebSocket protocol testing:</strong> The WebSocket handshake, reconnection logic, message serialization, and client latency cannot be observed without a running client-server pair.</li>
</ul>
<p>When teams lack automated end-to-end testing, they fall back on manual browser verification. A developer launches the app locally, manually selects dropdown values, enters dates, verifies counts by eye, and repeats the routine across multiple browsers before every release. This manual process is slow, unrecorded, prone to oversight, and impossible to automate within continuous integration pipelines.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In modern web development, end-to-end (E2E) testing relies on browser automation engines such as Playwright or Cypress. In a TypeScript application, unit test runners verify functions in isolation, while Playwright launches real headless browsers (Chromium, Firefox, or WebKit) to drive the full user journey:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb1-1"><span class="co" style="color: #5E5E5E;">// tests/e2e/safety-summary.spec.ts</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;">import</span> { test<span class="op" style="color: #5E5E5E;">,</span> expect } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"@playwright/test"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="fu" style="color: #4758AB;">test</span>(<span class="st" style="color: #20794D;">"updates safety subject count when treatment arm changes"</span><span class="op" style="color: #5E5E5E;">,</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">async</span> ({ page }) <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-5">  <span class="cf" style="color: #003B4F;
font-weight: bold;">await</span> page<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">goto</span>(<span class="st" style="color: #20794D;">"http://localhost:3000"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-6"></span>
<span id="cb1-7">  <span class="co" style="color: #5E5E5E;">// Verify initial selection and rendered count</span></span>
<span id="cb1-8">  <span class="cf" style="color: #003B4F;
font-weight: bold;">await</span> <span class="fu" style="color: #4758AB;">expect</span>(page<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">locator</span>(<span class="st" style="color: #20794D;">"#subject_count"</span>))<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toHaveText</span>(<span class="st" style="color: #20794D;">"86"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-9"></span>
<span id="cb1-10">  <span class="co" style="color: #5E5E5E;">// Select a new treatment arm and assert updated DOM text</span></span>
<span id="cb1-11">  <span class="cf" style="color: #003B4F;
font-weight: bold;">await</span> page<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">selectOption</span>(<span class="st" style="color: #20794D;">"#arm"</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-12">  <span class="cf" style="color: #003B4F;
font-weight: bold;">await</span> <span class="fu" style="color: #4758AB;">expect</span>(page<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">locator</span>(<span class="st" style="color: #20794D;">"#subject_count"</span>))<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toHaveText</span>(<span class="st" style="color: #20794D;">"72"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-13">})<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<p>Web repositories structure automated browser testing around three core principles:</p>
<ol type="1">
<li><strong>Full-stack fidelity:</strong> The application runs as a real web server communicating over HTTP and WebSockets with a real browser engine.</li>
<li><strong>Deterministic synchronization:</strong> The test driver automatically awaits DOM updates, network traffic, and rendering stabilization before evaluating assertions, avoiding flaky timeouts.</li>
<li><strong>Headless automation in CI:</strong> Real headless browsers run on every pull request, turning user journeys into merge-blocking regression gates.</li>
</ol>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In R, <a href="https://cran.r-project.org/package=shinytest2">{shinytest2}</a> brings end-to-end browser testing to Shiny applications. Replacing the older PhantomJS-based <code>{shinytest}</code> package, <code>{shinytest2}</code> uses <a href="https://cran.r-project.org/package=chromote">{chromote}</a> to control headless Google Chrome or Chromium via the Chrome DevTools Protocol (CDP).</p>
<section id="the-core-orchestrator-shinytest2appdriver" class="level3">
<h3 class="anchored" data-anchor-id="the-core-orchestrator-shinytest2appdriver">The core orchestrator: <code>shinytest2::AppDriver</code></h3>
<p>Every <code>{shinytest2}</code> test revolves around an instance of the <code>AppDriver</code> R6 class. An <code>AppDriver</code> object starts a background R process hosting your Shiny application, launches a headless Chrome session, navigates to the application URL, and coordinates interactions between testthat and the browser.</p>
<p>Here are the seven primary methods on <code>AppDriver</code>:</p>
<ol type="1">
<li><strong><code>AppDriver$new(app_dir = ...)</code></strong>: Initializes the background Shiny process and connects headless Chrome. Important arguments include:
<ul>
<li><code>app_dir</code>: Path to the directory containing <code>app.R</code>.</li>
<li><code>name</code>: An optional identifier used to prefix snapshot files.</li>
<li><code>seed</code>: An optional numeric seed passed to the background process for reproducibility.</li>
<li><code>wait = TRUE</code>: Blocks initialization until the Shiny app reaches its initial idle state.</li>
<li><code>check_names = TRUE</code>: Validates that all HTML <code>input</code> and <code>output</code> IDs are unique, catching duplicate identifier bugs before user interactions begin.</li>
<li><code>view</code>: Set to <code>TRUE</code> to watch Chrome run visually during local debugging.</li>
</ul></li>
<li><strong><code>$set_inputs(...)</code></strong>: Programmatically updates one or more inputs in the browser. To avoid collisions between Shiny input IDs and parameter names, <code>{shinytest2}</code> reserves trailing underscores for its internal control arguments:
<ul>
<li><code>wait_ = TRUE</code> (the default) instructs <code>AppDriver</code> to pause execution until the Shiny reactive graph completes recalculating and all affected outputs are rendered in the browser.</li>
<li><code>timeout_</code> defines the maximum wait duration before timing out.</li>
<li><code>allow_no_input_binding_</code> (default <code>FALSE</code>): set <code>TRUE</code> to allow setting a value on an input that has no Shiny input binding.</li>
<li><code>priority_ = c("input", "event")</code> specifies event priority.</li>
</ul></li>
<li><strong><code>$get_value(input = , output = , export = )</code></strong>: Retrieves a single scalar or data structure from the running application. You must provide exactly one of <code>input</code>, <code>output</code>, or <code>export</code> as a string name. For example, <code>app$get_value(output = "subject_count")</code> returns the current rendered text value of that output.</li>
<li><strong><code>$get_values(input = , output = , export = )</code></strong>: Returns a named list containing all current reactive values across <code>$input</code>, <code>$output</code>, and <code>$export</code>. Passing specific variable names or <code>TRUE</code> filters the returned list to selected scopes.</li>
<li><strong><code>$expect_values()</code></strong>: Creates or compares a JSON snapshot of reactive values (similar to <code>testthat::expect_snapshot_value()</code>, covered in <a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html">snapshot testing</a>). It serializes the specified inputs, outputs, and exports to a <code>.json</code> file in <code>tests/testthat/_snaps/</code>. In addition, it saves a debug screenshot ending in <code>_.png</code>. This debug image aids human visual inspection during pull request reviews, but differences in the image never fail the test.</li>
<li><strong><code>$wait_for_idle(duration = 500, timeout = ...)</code></strong>: Explicitly halts the test execution until Shiny has remained idle (with no pending WebSocket messages or reactive computations) for <code>duration</code> milliseconds (default 500 ms).</li>
<li><strong><code>$stop()</code></strong>: Terminates the background Shiny R process and closes the Chrome session. Register <code>withr::defer(app$stop())</code> right after creating the driver, so the app and Chrome are stopped even if the test errors part-way through. (A failed <em>expectation</em> does not stop a test — only an error does — but you still want the driver cleaned up on that error path.)</li>
</ol>
</section>
<section id="interactive-test-authoring-with-shinytest2record_test" class="level3">
<h3 class="anchored" data-anchor-id="interactive-test-authoring-with-shinytest2record_test">Interactive test authoring with <code>shinytest2::record_test()</code></h3>
<p>Writing browser test sequences by hand can be challenging when determining precise input IDs and event sequences. For interactive test authoring, <code>{shinytest2}</code> provides <code>record_test()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># Run interactively in the R console:</span></span>
<span id="cb2-2">shinytest2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">record_test</span>(<span class="st" style="color: #20794D;">"path/to/app"</span>)</span></code></pre></div></div>
<p><code>record_test()</code> launches the application in a visible Chrome window alongside a test recorder. As you interact with the app, the recorder logs your actions and any expectations you ask it to capture. Once the recording is complete, it creates or appends a <code>shinytest2</code> test to a <code>testthat</code> test file.</p>
</section>
<section id="snapshot-files-versus-visual-screenshots" class="level3">
<h3 class="anchored" data-anchor-id="snapshot-files-versus-visual-screenshots">Snapshot files versus visual screenshots</h3>
<p>When <code>{shinytest2}</code> runs snapshot tests via <code>$expect_values()</code>, the captured JSON state files are stored under:</p>
<pre><code>tests/testthat/_snaps/&lt;test_file&gt;/&lt;name&gt;-001.json</code></pre>
<p>While <code>AppDriver</code> also provides an <code>$expect_screenshot()</code> method for comparing pixel-by-pixel images of the rendered UI, pixel screenshots often differ between machines (fonts, anti-aliasing, rendering), so a screenshot recorded on one OS can fail on another. Common causes include:</p>
<ul>
<li>Differences in system font packages and font rendering engines.</li>
<li>Subtle anti-aliasing variations across operating systems.</li>
<li>Variations in how Chrome paints borders, SVG curves, or drop shadows on different graphics architectures.</li>
<li>Incomplete CSS transition or animation frames.</li>
</ul>
<p>For resilient test suites, prefer testing underlying data values rather than pixels. Assert rendered text directly using <code>$get_value()</code> with <code>expect_equal()</code>, snapshot structured state with <code>$expect_values()</code>, or expose reactive objects directly using <code>shiny::exportTestValues()</code>.</p>
</section>
<section id="runtime-cost-and-the-testing-pyramid" class="level3">
<h3 class="anchored" data-anchor-id="runtime-cost-and-the-testing-pyramid">Runtime cost and the testing pyramid</h3>
<p>End-to-end tests provide high fidelity, but they come with a runtime cost:</p>
<ul>
<li>A <code>testServer()</code> test typically completes in milliseconds because it operates entirely within the current R process.</li>
<li>A <code>shinytest2</code> test takes noticeably longer — seconds rather than milliseconds — because it must spawn a background R process, launch headless Chrome via <code>{chromote}</code>, establish a WebSocket connection, and wait for browser DOM stabilization.</li>
</ul>
<p>Follow the testing pyramid strategy:</p>
<ol type="1">
<li><strong>Base (Unit tests):</strong> Write unit tests with <code>testthat</code> for pure business logic and data transformations (such as derivation functions or statistical formatting).</li>
<li><strong>Middle (<code>testServer</code>):</strong> Test complex reactive calculations, module communication, and reactive branching in memory with <code>testServer()</code>.</li>
<li><strong>Top (<code>shinytest2</code>):</strong> Reserve <code>shinytest2</code> for high-value end-to-end user journeys: critical onboarding flows, bookmarking restoration, file download generation, and integration across custom JavaScript components.</li>
</ol>
</section>
<section id="running-in-continuous-integration-ci" class="level3">
<h3 class="anchored" data-anchor-id="running-in-continuous-integration-ci">Running in continuous integration (CI)</h3>
<p>Executing <code>{shinytest2}</code> in continuous integration requires a Chrome or Chromium browser executable. Standard GitHub Actions virtual runners (<code>ubuntu-latest</code>, <code>macos-latest</code>, and <code>windows-latest</code>) include Google Chrome in their default system images.</p>
<p>CRAN build machines, however, do not provide an external Chrome executable, so <code>{shinytest2}</code> automatically calls <code>testthat::skip_on_cran()</code> inside <code>AppDriver$new()</code> — any test that creates an <code>AppDriver</code> already skips on CRAN. A separate <code>skip_on_cran()</code> in your test file is optional; what you do need to check yourself is Chrome’s availability with <code>chromote::find_chrome()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># tests/testthat/test-app-e2e.R</span></span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;">library</span>(shinytest2)</span>
<span id="cb4-3"></span>
<span id="cb4-4"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"application loads and updates count"</span>, {</span>
<span id="cb4-5">  <span class="fu" style="color: #4758AB;">skip_if_not</span>(<span class="fu" style="color: #4758AB;">nzchar</span>(chromote<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">find_chrome</span>()))</span>
<span id="cb4-6"></span>
<span id="cb4-7">  app <span class="ot" style="color: #003B4F;">&lt;-</span> AppDriver<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_path</span>(<span class="st" style="color: #20794D;">"../../inst/app"</span>), <span class="at" style="color: #657422;">name =</span> <span class="st" style="color: #20794D;">"e2e"</span>)</span>
<span id="cb4-8">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">defer</span>(app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">stop</span>())</span>
<span id="cb4-9"></span>
<span id="cb4-10">  app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">expect_values</span>()</span>
<span id="cb4-11">})</span></code></pre></div></div>
<p>That same <code>skip_on_cran()</code> check reads the <code>NOT_CRAN</code> environment variable, which matters well outside of CRAN: without <code>NOT_CRAN = "true"</code> set, <code>AppDriver$new()</code> skips the test everywhere, not just on CRAN. Run <code>Rscript -e 'testthat::test_dir("tests/testthat")'</code> (or any CI job that doesn’t set it) and every <code>shinytest2</code> test silently reports as skipped rather than run. Two ways to make sure it is set:</p>
<ul>
<li>In a GitHub Actions workflow, add <code>NOT_CRAN: true</code> under the job or step’s <code>env:</code>. The <code>r-lib/actions/setup-r</code> action already sets <code>NOT_CRAN=true</code> for the whole job, so an <code>R CMD check</code> job on GitHub runs the browser tests that CRAN skips.</li>
<li>In a standalone script, as this post’s companion script does: <code>withr::local_envvar(NOT_CRAN = "true")</code> before creating the <code>AppDriver</code>. Never put this in a package’s <code>tests/testthat/</code> files: it would switch <code>skip_on_cran()</code> off on CRAN too, where there is no Chrome, so the test would error instead of skipping and <code>R CMD check</code> would fail.</li>
</ul>
<p>If you drive your package tests with <code>devtools::test()</code>, this is already handled — it sets <code>NOT_CRAN = "true"</code> (unless you’ve set it to something else) before running your test suite.</p>
</section>
</section>
<section id="worked-clinical-example-adsl-safety-summary" class="level2">
<h2 class="anchored" data-anchor-id="worked-clinical-example-adsl-safety-summary">Worked clinical example: ADSL safety summary</h2>
<p>Consider a clinical trial application that displays subject counts from <code>pharmaverseadam::adsl</code>. In clinical reporting, summarizing demographics or adverse events begins with the safety population (<code>SAFFL == "Y"</code>).</p>
<p>We inspect the actual safety population counts by treatment arm (<code>TRT01A</code>):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># Baseline counts from ADSL safety population</span></span>
<span id="cb5-2">saf_data <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb5-3"><span class="fu" style="color: #4758AB;">table</span>(saf_data<span class="sc" style="color: #5E5E5E;">$</span>TRT01A)</span></code></pre></div></div>
<p>The safety population consists of 86 subjects on Placebo, 72 on Xanomeline High Dose, and 96 on Xanomeline Low Dose.</p>
<p>We define a minimal Shiny application that allows a user to select a treatment arm and view the corresponding count:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;">library</span>(shiny)</span>
<span id="cb6-2"></span>
<span id="cb6-3">ui <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">fluidPage</span>(</span>
<span id="cb6-4">  <span class="fu" style="color: #4758AB;">titlePanel</span>(<span class="st" style="color: #20794D;">"Safety Population Summary"</span>),</span>
<span id="cb6-5">  <span class="fu" style="color: #4758AB;">sidebarLayout</span>(</span>
<span id="cb6-6">    <span class="fu" style="color: #4758AB;">sidebarPanel</span>(</span>
<span id="cb6-7">      <span class="fu" style="color: #4758AB;">selectInput</span>(</span>
<span id="cb6-8">        <span class="at" style="color: #657422;">inputId =</span> <span class="st" style="color: #20794D;">"arm"</span>,</span>
<span id="cb6-9">        <span class="at" style="color: #657422;">label =</span> <span class="st" style="color: #20794D;">"Treatment Arm"</span>,</span>
<span id="cb6-10">        <span class="at" style="color: #657422;">choices =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"Placebo"</span>, <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>, <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>),</span>
<span id="cb6-11">        <span class="at" style="color: #657422;">selected =</span> <span class="st" style="color: #20794D;">"Placebo"</span></span>
<span id="cb6-12">      )</span>
<span id="cb6-13">    ),</span>
<span id="cb6-14">    <span class="fu" style="color: #4758AB;">mainPanel</span>(</span>
<span id="cb6-15">      <span class="fu" style="color: #4758AB;">h4</span>(<span class="st" style="color: #20794D;">"Safety Subjects (SAFFL == Y)"</span>),</span>
<span id="cb6-16">      <span class="fu" style="color: #4758AB;">textOutput</span>(<span class="st" style="color: #20794D;">"subject_count"</span>)</span>
<span id="cb6-17">    )</span>
<span id="cb6-18">  )</span>
<span id="cb6-19">)</span>
<span id="cb6-20"></span>
<span id="cb6-21">server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb6-22">  output<span class="sc" style="color: #5E5E5E;">$</span>subject_count <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">renderText</span>({</span>
<span id="cb6-23">    <span class="fu" style="color: #4758AB;">req</span>(input<span class="sc" style="color: #5E5E5E;">$</span>arm)</span>
<span id="cb6-24">    saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> TRT01A <span class="sc" style="color: #5E5E5E;">==</span> input<span class="sc" style="color: #5E5E5E;">$</span>arm)</span>
<span id="cb6-25">    <span class="fu" style="color: #4758AB;">as.character</span>(<span class="fu" style="color: #4758AB;">nrow</span>(saf))</span>
<span id="cb6-26">  })</span>
<span id="cb6-27">}</span></code></pre></div></div>
<p>Now we write an automated end-to-end test with <code>AppDriver</code> to verify the full user workflow:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="co" style="color: #5E5E5E;"># tests/testthat/test-adsl-app.R</span></span>
<span id="cb7-2"><span class="fu" style="color: #4758AB;">library</span>(shinytest2)</span>
<span id="cb7-3"></span>
<span id="cb7-4"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"ADSL safety summary updates displayed count on arm selection"</span>, {</span>
<span id="cb7-5">  <span class="fu" style="color: #4758AB;">skip_on_cran</span>()</span>
<span id="cb7-6">  <span class="fu" style="color: #4758AB;">skip_if_not</span>(<span class="fu" style="color: #4758AB;">nzchar</span>(chromote<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">find_chrome</span>()))</span>
<span id="cb7-7"></span>
<span id="cb7-8">  app <span class="ot" style="color: #003B4F;">&lt;-</span> AppDriver<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(<span class="st" style="color: #20794D;">"path/to/app"</span>, <span class="at" style="color: #657422;">name =</span> <span class="st" style="color: #20794D;">"adsl-summary"</span>)</span>
<span id="cb7-9">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">defer</span>(app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">stop</span>())</span>
<span id="cb7-10"></span>
<span id="cb7-11">  <span class="co" style="color: #5E5E5E;"># 1. Verify initial count for default selection (Placebo)</span></span>
<span id="cb7-12">  <span class="fu" style="color: #4758AB;">expect_equal</span>(app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">get_value</span>(<span class="at" style="color: #657422;">output =</span> <span class="st" style="color: #20794D;">"subject_count"</span>), <span class="st" style="color: #20794D;">"86"</span>)</span>
<span id="cb7-13"></span>
<span id="cb7-14">  <span class="co" style="color: #5E5E5E;"># 2. Select Xanomeline High Dose and assert updated reactive count</span></span>
<span id="cb7-15">  app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_inputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)</span>
<span id="cb7-16">  <span class="fu" style="color: #4758AB;">expect_equal</span>(app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">get_value</span>(<span class="at" style="color: #657422;">output =</span> <span class="st" style="color: #20794D;">"subject_count"</span>), <span class="st" style="color: #20794D;">"72"</span>)</span>
<span id="cb7-17"></span>
<span id="cb7-18">  <span class="co" style="color: #5E5E5E;"># 3. Select Xanomeline Low Dose and assert updated reactive count</span></span>
<span id="cb7-19">  app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_inputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>)</span>
<span id="cb7-20">  <span class="fu" style="color: #4758AB;">expect_equal</span>(app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">get_value</span>(<span class="at" style="color: #657422;">output =</span> <span class="st" style="color: #20794D;">"subject_count"</span>), <span class="st" style="color: #20794D;">"96"</span>)</span>
<span id="cb7-21"></span>
<span id="cb7-22">  <span class="co" style="color: #5E5E5E;"># 4. Verify complete input/output state</span></span>
<span id="cb7-23">  vals <span class="ot" style="color: #003B4F;">&lt;-</span> app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">get_values</span>()</span>
<span id="cb7-24">  <span class="fu" style="color: #4758AB;">expect_equal</span>(vals<span class="sc" style="color: #5E5E5E;">$</span>input<span class="sc" style="color: #5E5E5E;">$</span>arm, <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>)</span>
<span id="cb7-25">  <span class="fu" style="color: #4758AB;">expect_equal</span>(vals<span class="sc" style="color: #5E5E5E;">$</span>output<span class="sc" style="color: #5E5E5E;">$</span>subject_count, <span class="st" style="color: #20794D;">"96"</span>)</span>
<span id="cb7-26">})</span></code></pre></div></div>
<p>When evaluated, <code>AppDriver</code> launches Chrome headlessly, changes the selected arm via the browser’s input binding, waits for Shiny to finish reactive recalculations (<code>wait_ = TRUE</code>), and asserts that the exact string rendered in the browser DOM matches our clinical dataset.</p>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/scripts/app-driver-demo.R">View <code>app-driver-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/scripts/app-driver-demo.R" download="app-driver-demo.R">Download</a></p>
<p>Writes a clinical safety Shiny application to a temporary directory, launches Chrome headlessly with <code>shinytest2::AppDriver</code>, asserts rendered DOM outputs against <code>pharmaverseadam::adsl</code>, and stops the application. Requires <code>{shinytest2}</code>, <code>{shiny}</code>, <code>{pharmaverseadam}</code>, and <code>{withr}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>app-driver-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="co" style="color: #5E5E5E;"># End-to-end Shiny testing with shinytest2 and AppDriver</span></span>
<span id="cb8-2"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb8-3"><span class="co" style="color: #5E5E5E;"># Writes a Shiny application summarizing clinical trial safety subjects</span></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;"># (pharmaverseadam::adsl where SAFFL == "Y") by treatment arm, drives it</span></span>
<span id="cb8-5"><span class="co" style="color: #5E5E5E;"># headlessly with shinytest2::AppDriver, asserts initial and updated output</span></span>
<span id="cb8-6"><span class="co" style="color: #5E5E5E;"># values, and cleanly stops the application.</span></span>
<span id="cb8-7"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb8-8"><span class="co" style="color: #5E5E5E;"># Run with:</span></span>
<span id="cb8-9"><span class="co" style="color: #5E5E5E;">#   Rscript app-driver-demo.R</span></span>
<span id="cb8-10"></span>
<span id="cb8-11"><span class="co" style="color: #5E5E5E;">#' Write the ADSL summary Shiny application to disk</span></span>
<span id="cb8-12"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb8-13"><span class="co" style="color: #5E5E5E;">#' @param app_dir Directory where app.R will be written.</span></span>
<span id="cb8-14"><span class="co" style="color: #5E5E5E;">#' @return The application directory path, invisibly.</span></span>
<span id="cb8-15"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb8-16">write_adsl_app <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(app_dir) {</span>
<span id="cb8-17">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">dir.exists</span>(app_dir)) {</span>
<span id="cb8-18">    <span class="fu" style="color: #4758AB;">dir.create</span>(app_dir, <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb8-19">  }</span>
<span id="cb8-20"></span>
<span id="cb8-21">  app_code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb8-22">    <span class="st" style="color: #20794D;">"library(shiny)"</span>,</span>
<span id="cb8-23">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb8-24">    <span class="st" style="color: #20794D;">"ui &lt;- fluidPage("</span>,</span>
<span id="cb8-25">    <span class="st" style="color: #20794D;">"  titlePanel(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Safety Population Summary</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">),"</span>,</span>
<span id="cb8-26">    <span class="st" style="color: #20794D;">"  sidebarLayout("</span>,</span>
<span id="cb8-27">    <span class="st" style="color: #20794D;">"    sidebarPanel("</span>,</span>
<span id="cb8-28">    <span class="st" style="color: #20794D;">"      selectInput("</span>,</span>
<span id="cb8-29">    <span class="st" style="color: #20794D;">"        inputId = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">arm</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">,"</span>,</span>
<span id="cb8-30">    <span class="st" style="color: #20794D;">"        label = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Treatment Arm</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">,"</span>,</span>
<span id="cb8-31">    <span class="st" style="color: #20794D;">"        choices = c(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Placebo</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Xanomeline High Dose</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Xanomeline Low Dose</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">),"</span>,</span>
<span id="cb8-32">    <span class="st" style="color: #20794D;">"        selected = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Placebo</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">"</span>,</span>
<span id="cb8-33">    <span class="st" style="color: #20794D;">"      )"</span>,</span>
<span id="cb8-34">    <span class="st" style="color: #20794D;">"    ),"</span>,</span>
<span id="cb8-35">    <span class="st" style="color: #20794D;">"    mainPanel("</span>,</span>
<span id="cb8-36">    <span class="st" style="color: #20794D;">"      h4(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Safety Subjects (SAFFL == Y)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">),"</span>,</span>
<span id="cb8-37">    <span class="st" style="color: #20794D;">"      textOutput(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">subject_count</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb8-38">    <span class="st" style="color: #20794D;">"    )"</span>,</span>
<span id="cb8-39">    <span class="st" style="color: #20794D;">"  )"</span>,</span>
<span id="cb8-40">    <span class="st" style="color: #20794D;">")"</span>,</span>
<span id="cb8-41">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb8-42">    <span class="st" style="color: #20794D;">"server &lt;- function(input, output, session) {"</span>,</span>
<span id="cb8-43">    <span class="st" style="color: #20794D;">"  output$subject_count &lt;- renderText({"</span>,</span>
<span id="cb8-44">    <span class="st" style="color: #20794D;">"    req(input$arm)"</span>,</span>
<span id="cb8-45">    <span class="st" style="color: #20794D;">"    saf &lt;- subset(pharmaverseadam::adsl, SAFFL == </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Y</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;"> &amp; TRT01A == input$arm)"</span>,</span>
<span id="cb8-46">    <span class="st" style="color: #20794D;">"    as.character(nrow(saf))"</span>,</span>
<span id="cb8-47">    <span class="st" style="color: #20794D;">"  })"</span>,</span>
<span id="cb8-48">    <span class="st" style="color: #20794D;">"}"</span>,</span>
<span id="cb8-49">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb8-50">    <span class="st" style="color: #20794D;">"shinyApp(ui = ui, server = server)"</span></span>
<span id="cb8-51">  )</span>
<span id="cb8-52"></span>
<span id="cb8-53">  <span class="fu" style="color: #4758AB;">writeLines</span>(app_code, <span class="fu" style="color: #4758AB;">file.path</span>(app_dir, <span class="st" style="color: #20794D;">"app.R"</span>))</span>
<span id="cb8-54">  <span class="fu" style="color: #4758AB;">invisible</span>(app_dir)</span>
<span id="cb8-55">}</span>
<span id="cb8-56"></span>
<span id="cb8-57"><span class="co" style="color: #5E5E5E;">#' Calculate expected safety subject count from ADSL</span></span>
<span id="cb8-58"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb8-59"><span class="co" style="color: #5E5E5E;">#' @param arm Treatment arm (TRT01A).</span></span>
<span id="cb8-60"><span class="co" style="color: #5E5E5E;">#' @return Integer subject count.</span></span>
<span id="cb8-61"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb8-62">compute_safety_count <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(arm) {</span>
<span id="cb8-63">  <span class="fu" style="color: #4758AB;">sum</span>(</span>
<span id="cb8-64">    pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl<span class="sc" style="color: #5E5E5E;">$</span>SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span> <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb8-65">      pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl<span class="sc" style="color: #5E5E5E;">$</span>TRT01A <span class="sc" style="color: #5E5E5E;">==</span> arm,</span>
<span id="cb8-66">    <span class="at" style="color: #657422;">na.rm =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb8-67">  )</span>
<span id="cb8-68">}</span>
<span id="cb8-69"></span>
<span id="cb8-70"><span class="co" style="color: #5E5E5E;">#' Drive the ADSL application with AppDriver</span></span>
<span id="cb8-71"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb8-72"><span class="co" style="color: #5E5E5E;">#' @param app_dir Directory containing the Shiny application.</span></span>
<span id="cb8-73"><span class="co" style="color: #5E5E5E;">#' @return Named list with recorded values from AppDriver.</span></span>
<span id="cb8-74"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb8-75">run_app_driver_demo <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(app_dir) {</span>
<span id="cb8-76">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_envvar</span>(<span class="at" style="color: #657422;">NOT_CRAN =</span> <span class="st" style="color: #20794D;">"true"</span>)</span>
<span id="cb8-77"></span>
<span id="cb8-78">  app <span class="ot" style="color: #003B4F;">&lt;-</span> shinytest2<span class="sc" style="color: #5E5E5E;">::</span>AppDriver<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>(app_dir, <span class="at" style="color: #657422;">name =</span> <span class="st" style="color: #20794D;">"adsl-summary"</span>)</span>
<span id="cb8-79">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">defer</span>(app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">stop</span>())</span>
<span id="cb8-80"></span>
<span id="cb8-81">  initial_val <span class="ot" style="color: #003B4F;">&lt;-</span> app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">get_value</span>(<span class="at" style="color: #657422;">output =</span> <span class="st" style="color: #20794D;">"subject_count"</span>)</span>
<span id="cb8-82"></span>
<span id="cb8-83">  app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_inputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)</span>
<span id="cb8-84">  high_dose_val <span class="ot" style="color: #003B4F;">&lt;-</span> app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">get_value</span>(<span class="at" style="color: #657422;">output =</span> <span class="st" style="color: #20794D;">"subject_count"</span>)</span>
<span id="cb8-85"></span>
<span id="cb8-86">  app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">set_inputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>)</span>
<span id="cb8-87">  low_dose_val <span class="ot" style="color: #003B4F;">&lt;-</span> app<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">get_value</span>(<span class="at" style="color: #657422;">output =</span> <span class="st" style="color: #20794D;">"subject_count"</span>)</span>
<span id="cb8-88"></span>
<span id="cb8-89">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb8-90">    <span class="at" style="color: #657422;">placebo =</span> initial_val,</span>
<span id="cb8-91">    <span class="at" style="color: #657422;">high_dose =</span> high_dose_val,</span>
<span id="cb8-92">    <span class="at" style="color: #657422;">low_dose =</span> low_dose_val</span>
<span id="cb8-93">  )</span>
<span id="cb8-94">}</span>
<span id="cb8-95"></span>
<span id="cb8-96"><span class="co" style="color: #5E5E5E;"># Run demo only when executed directly as a script.</span></span>
<span id="cb8-97"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb8-98">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Writing ADSL safety summary app to temporary directory..."</span>)</span>
<span id="cb8-99">  demo_dir <span class="ot" style="color: #003B4F;">&lt;-</span> withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_tempdir</span>()</span>
<span id="cb8-100">  <span class="fu" style="color: #4758AB;">write_adsl_app</span>(demo_dir)</span>
<span id="cb8-101"></span>
<span id="cb8-102">  <span class="fu" style="color: #4758AB;">message</span>(</span>
<span id="cb8-103">    <span class="st" style="color: #20794D;">"Starting AppDriver and testing reactive outputs in headless Chrome..."</span></span>
<span id="cb8-104">  )</span>
<span id="cb8-105">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_app_driver_demo</span>(demo_dir)</span>
<span id="cb8-106"></span>
<span id="cb8-107">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Initial (Placebo) count: "</span>, results<span class="sc" style="color: #5E5E5E;">$</span>placebo)</span>
<span id="cb8-108">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Updated (High Dose) count: "</span>, results<span class="sc" style="color: #5E5E5E;">$</span>high_dose)</span>
<span id="cb8-109">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Updated (Low Dose) count: "</span>, results<span class="sc" style="color: #5E5E5E;">$</span>low_dose)</span>
<span id="cb8-110">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"AppDriver stopped cleanly. Demo complete."</span>)</span>
<span id="cb8-111">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>r-lib/actions <code>setup-r</code></strong>: <a href="https://github.com/r-lib/actions/tree/v2/setup-r">README</a></li>
<li><strong>shinytest2</strong>: <a href="https://cran.r-project.org/package=shinytest2">CRAN</a></li>
<li><strong>chromote</strong>: <a href="https://cran.r-project.org/package=chromote">CRAN</a></li>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>withr</strong>: <a href="https://withr.r-lib.org/">withr.r-lib.org</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
</ul>
<p><strong>Web-repo comparison</strong></p>
<ul>
<li><strong>Playwright</strong>: <a href="https://playwright.dev/">playwright.dev</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
<li><strong>2026-11-13:</strong> The in-file <code>NOT_CRAN</code> override is for standalone scripts only, never package tests, because it makes the test error on CRAN instead of skipping. Added that <code>setup-r</code> sets <code>NOT_CRAN=true</code> by default.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-series-nav__series">Testing series · part 5 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/shiny-testserver/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 4</span><span class="site-related-card__title">Testing Shiny server logic with testServer()</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/property-based-testing/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 6</span><span class="site-related-card__title">Property-based testing in R</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html" class="site-link-row" title="Run R CMD check, tests, and link validation automatically on clean GitHub Actions runners with pinned dependencies."><span class="is-card__eyebrow site-link-row__label">Builds on</span><span class="site-link-row__title">CI with GitHub Actions</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html" class="site-link-row" title="Capture complex console output, rtables layouts, and plots with testthat snapshots and vdiffr to catch regressions without fragile manual assertions."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Snapshot tests for R output, tables and plots</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/secret-scanning/index.html" class="site-link-row" title="Scan commits and history for accidental credentials before code leaves your machine and on CI."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Secret scanning with gitleaks</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Shiny</category>
  <category>R</category>
  <category>CI/CD</category>
  <guid>https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Generating tables, figures and listings in R</title>
  <link>https://insightsurge-dev.web.app/posts/tfl-generation-r/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Tables, Figures, and Listings (TFLs) represent the bulk of clinical study deliverables. A Phase III Clinical Study Report (CSR) needs a long list of them: demographic baselines, adverse events grouped by system organ class, laboratory shifts, and patient listings.</p>
<p>Historically, statistical programming teams built TFLs through monolithic procedural scripts. A single program loaded data, filtered records, calculated summaries, formatted numbers like <code>"75.2 (8.6)"</code>, injected Rich Text Format (RTF) control tags, and managed page breaks.</p>
<p>This coupling creates three chronic engineering problems:</p>
<ul>
<li><strong>Re-deriving numbers per table</strong>: When Table 14.1.1 (demographics) and Table 14.3.1 (adverse events) independently recalculate population counts (N), subtle discrepancies in filtering or rounding rules emerge. Programmers and statisticians then spend time reconciling numbers across tables.</li>
<li><strong>Fragile layout and pagination</strong>: When a reviewer requests a cosmetic adjustment—such as altering decimal precision or moving footnotes—programmers must edit and re-run the entire script, forcing re-verification of the underlying statistical calculations.</li>
<li><strong>Opaque quality control</strong>: Double-programming verification often degenerates into visual inspection of rendered RTF or PDF documents. Reviewers end up scrutinising typographic margins instead of programmatically verifying numbers as data.</li>
</ul>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>Web engineering encountered this exact failure decades ago. In early web frameworks, SQL queries were embedded directly inside HTML markup. Altering a layout broke queries; changing a table schema crashed the user interface.</p>
<p>Modern web architectures solved this by separating <strong>data</strong> from <strong>presentation</strong>:</p>
<pre class="text"><code>Database Layer ──&gt; [API / Schema] ──&gt; Structured Data ──&gt; [Design System] ──&gt; Presentation
  (ADaM Data)        (Stats Engine)      (Typed JSON / ARD)   (UI Components)       (HTML / RTF)</code></pre>
<ul>
<li><strong>The data contract</strong>: The backend API serves structured, typed data (usually JSON) containing raw numbers and category labels, independent of fonts, margins, or page breaks.</li>
<li><strong>The presentation components</strong>: Client frameworks consume that structured payload and render it through reusable templates and visual components.</li>
<li><strong>The design system</strong>: Centralised design tokens dictate spacing, typography, and borders across every screen, ensuring visual consistency without redesigning tables on every page.</li>
</ul>
<p>Applying this separation of concerns to clinical reporting replaces fragile monolithic scripts with two decoupled layers: an analytics engine that derives auditable numerical results, and a presentation engine that arranges those results into submission-ready displays.</p>
</section>
<section id="the-r-way-two-reporting-architectures" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-two-reporting-architectures">The R way: two reporting architectures</h2>
<p>The modern <a href="https://pharmaverse.org">pharmaverse</a> ecosystem provides two distinct architectural approaches for building clinical tables. Neither is universally superior; each addresses specific operational needs.</p>
<section id="architecture-1-direct-table-code" class="level3">
<h3 class="anchored" data-anchor-id="architecture-1-direct-table-code">Architecture 1: Direct table code</h3>
<p>Direct table generation builds formatted displays directly from ADaM data in a single declarative pipeline. This approach fits teams delivering standard clinical study reports with predefined table shells. Three primary packages lead this space:</p>
<section id="rtables-tern" class="level4">
<h4 class="anchored" data-anchor-id="rtables-tern">1. <code>{rtables}</code> + <code>{tern}</code></h4>
<p><a href="https://cran.r-project.org/package=rtables"><code>{rtables}</code></a> models tables as hierarchical tree structures (<code>basic_table()</code>, <code>split_cols_by()</code>, <code>analyze()</code>, <code>build_table()</code>). You declare the layout first—specifying column splits and nested row hierarchies—before populating it with data. <a href="https://cran.r-project.org/package=tern"><code>{tern}</code></a> provides clinical analysis functions (such as <code>analyze_vars()</code>) built on <code>{rtables}</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">library</span>(rtables)</span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">library</span>(tern)</span>
<span id="cb2-3"></span>
<span id="cb2-4">adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb2-5"></span>
<span id="cb2-6">tbl_rtables <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">basic_table</span>(</span>
<span id="cb2-7">  <span class="at" style="color: #657422;">title =</span> <span class="st" style="color: #20794D;">"Demographic and Baseline Characteristics"</span>,</span>
<span id="cb2-8">  <span class="at" style="color: #657422;">subtitles =</span> <span class="st" style="color: #20794D;">"Safety Population"</span>,</span>
<span id="cb2-9">  <span class="at" style="color: #657422;">main_footer =</span> <span class="st" style="color: #20794D;">"Source: pharmaverseadam::adsl"</span></span>
<span id="cb2-10">) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-11">  <span class="fu" style="color: #4758AB;">split_cols_by</span>(<span class="st" style="color: #20794D;">"TRT01A"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-12">  <span class="fu" style="color: #4758AB;">analyze_vars</span>(</span>
<span id="cb2-13">    <span class="at" style="color: #657422;">vars =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"AGE"</span>, <span class="st" style="color: #20794D;">"SEX"</span>),</span>
<span id="cb2-14">    <span class="at" style="color: #657422;">var_labels =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="at" style="color: #657422;">AGE =</span> <span class="st" style="color: #20794D;">"Age (Years)"</span>, <span class="at" style="color: #657422;">SEX =</span> <span class="st" style="color: #20794D;">"Sex"</span>)</span>
<span id="cb2-15">  ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-16">  <span class="fu" style="color: #4758AB;">build_table</span>(adsl_saf)</span></code></pre></div></div>
<p><code>{rtables}</code> excels at complex, multi-level clinical tables—such as adverse events nested by System Organ Class and Preferred Term, or multi-arm summaries with nested column splits—while preserving cell-level metadata.</p>
</section>
<section id="tplyr" class="level4">
<h4 class="anchored" data-anchor-id="tplyr">2. <code>{Tplyr}</code></h4>
<p><a href="https://atorus-research.github.io/Tplyr/"><code>{Tplyr}</code></a> provides an explicit “grammar of clinical tables”. It organizes table construction into modular analytical layers: count layers (<code>group_count()</code>), descriptive summary layers (<code>group_desc()</code>), and shift layers:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;">library</span>(Tplyr)</span>
<span id="cb3-2"></span>
<span id="cb3-3">adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb3-4"></span>
<span id="cb3-5">tbl_tplyr <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tplyr_table</span>(adsl_saf, TRT01A) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-6">  <span class="fu" style="color: #4758AB;">add_layer</span>(</span>
<span id="cb3-7">    <span class="fu" style="color: #4758AB;">group_desc</span>(<span class="at" style="color: #657422;">target_var =</span> AGE, <span class="at" style="color: #657422;">by =</span> <span class="st" style="color: #20794D;">"Age (Years)"</span>)</span>
<span id="cb3-8">  ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-9">  <span class="fu" style="color: #4758AB;">add_layer</span>(</span>
<span id="cb3-10">    <span class="fu" style="color: #4758AB;">group_count</span>(<span class="at" style="color: #657422;">target_var =</span> SEX, <span class="at" style="color: #657422;">by =</span> <span class="st" style="color: #20794D;">"Sex"</span>)</span>
<span id="cb3-11">  ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-12">  <span class="fu" style="color: #4758AB;">build</span>()</span></code></pre></div></div>
<p><code>{Tplyr}</code> compiles these layers into an intermediate data frame with structured row labels and formatted character values, ready for any downstream formatting engine.</p>
</section>
<section id="gtsummary" class="level4">
<h4 class="anchored" data-anchor-id="gtsummary">3. <code>{gtsummary}</code></h4>
<p>Built on top of <code>{gt}</code>, <a href="https://www.danieldsjoberg.com/gtsummary/"><code>{gtsummary}</code></a> offers a concise syntax for summary tables via <code>tbl_summary()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;">library</span>(gtsummary)</span>
<span id="cb4-2"></span>
<span id="cb4-3">adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb4-4"></span>
<span id="cb4-5">tbl_gt <span class="ot" style="color: #003B4F;">&lt;-</span> adsl_saf <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb4-6">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">select</span>(TRT01A, AGE, SEX) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb4-7">  <span class="fu" style="color: #4758AB;">tbl_summary</span>(</span>
<span id="cb4-8">    <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb4-9">    <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">list</span>(AGE <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"Age (Years)"</span>, SEX <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"Sex"</span>),</span>
<span id="cb4-10">    <span class="at" style="color: #657422;">statistic =</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb4-11">      AGE <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"{mean} ({sd})"</span>,</span>
<span id="cb4-12">      SEX <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"{n} ({p}%)"</span></span>
<span id="cb4-13">    )</span>
<span id="cb4-14">  )</span></code></pre></div></div>
<p><code>{gtsummary}</code> is widely used across clinical research and exploratory biostatistics, providing rapid prototyping and clean default styling.</p>
<hr>
</section>
</section>
<section id="architecture-2-ard-first-analysis-results-data" class="level3">
<h3 class="anchored" data-anchor-id="architecture-2-ard-first-analysis-results-data">Architecture 2: ARD-first (Analysis Results Data)</h3>
<p>The second architecture separates statistical calculations entirely from table presentation by creating an intermediate dataset called <strong>Analysis Results Data (ARD)</strong>.</p>
<p>In an ARD-first workflow, you never compute statistics inside a layout routine. Instead, an analytics engine derives a tidy, standardised results table containing calculated values, parameter names, grouping variables, and statistical context.</p>
<p><a href="https://pharmaverse.github.io/cards/"><code>{cards}</code></a> is the foundational pharmaverse package for generating ARDs. Functions like <code>ard_continuous()</code> and <code>ard_categorical()</code> calculate statistical summaries, while <code>ard_stack()</code> binds them into a consistent structure:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;">library</span>(cards)</span>
<span id="cb5-2"></span>
<span id="cb5-3">adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb5-4"></span>
<span id="cb5-5">ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">ard_stack</span>(</span>
<span id="cb5-6">  <span class="at" style="color: #657422;">data =</span> adsl_saf,</span>
<span id="cb5-7">  <span class="fu" style="color: #4758AB;">ard_continuous</span>(<span class="at" style="color: #657422;">variables =</span> AGE),</span>
<span id="cb5-8">  <span class="fu" style="color: #4758AB;">ard_categorical</span>(<span class="at" style="color: #657422;">variables =</span> SEX),</span>
<span id="cb5-9">  <span class="at" style="color: #657422;">.by =</span> TRT01A,</span>
<span id="cb5-10">  <span class="at" style="color: #657422;">.attributes =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb5-11">)</span></code></pre></div></div>
<p>The resulting <code>ard</code> object contains purely numerical results and metadata—no formatted strings, borders, or display logic. Presentation frameworks render it without re-running computations:</p>
<ul>
<li><strong><code>gtsummary::tbl_ard_summary()</code></strong>: Formats the pre-computed ARD into a presentation-ready display:</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;">library</span>(gtsummary)</span>
<span id="cb6-2"></span>
<span id="cb6-3">tbl_rendered <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tbl_ard_summary</span>(</span>
<span id="cb6-4">  <span class="at" style="color: #657422;">cards =</span> ard,</span>
<span id="cb6-5">  <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb6-6">  <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">list</span>(AGE <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"Age (Years)"</span>, SEX <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"Sex"</span>),</span>
<span id="cb6-7">  <span class="at" style="color: #657422;">statistic =</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb6-8">    AGE <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"{mean} ({sd})"</span>,</span>
<span id="cb6-9">    SEX <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"{n} ({p}%)"</span></span>
<span id="cb6-10">  )</span>
<span id="cb6-11">)</span></code></pre></div></div>
<ul>
<li><strong><code>{tfrmt}</code></strong>: The <a href="https://cran.r-project.org/package=tfrmt"><code>{tfrmt}</code></a> (table format) package defines an external formatting language (<code>tfrmt()</code>, <code>print_to_gt()</code>) that applies visual layouts, decimal formatting, and row-grouping plans to pre-aggregated data.</li>
</ul>
<section id="why-ard-first-helps-qc-and-re-use" class="level4">
<h4 class="anchored" data-anchor-id="why-ard-first-helps-qc-and-re-use">Why ARD-first helps QC and re-use</h4>
<p>Separating results into structured data delivers two substantial engineering advantages:</p>
<ol type="1">
<li><strong>QC as automated data comparison</strong>: In traditional double-programming, quality control requires comparing formatted text strings or visual reports. With ARD-first workflows, the primary and validation programmers each produce an ARD data frame. Independent verification becomes a structured data comparison (for example <code>waldo::compare()</code> or <code>diffdf::diffdf()</code>). Any discrepancy immediately highlights the exact variable, treatment arm, and statistic where the calculation diverged, without noise from whitespace or font differences.</li>
<li><strong>One calculation, multiple presentations</strong>: A single ARD generated during an analysis run can render multiple downstream deliverables: a formal CSR submission table in RTF, an executive slide deck, an interactive safety dashboard in Shiny, or a web report. The underlying statistical numbers are computed and verified once.</li>
</ol>
</section>
<section id="choosing-between-the-two-architectures" class="level4">
<h4 class="anchored" data-anchor-id="choosing-between-the-two-architectures">Choosing between the two architectures</h4>
<ul>
<li><strong>Direct table code</strong> (<code>{rtables}</code> or <code>{Tplyr}</code>) fits individual clinical studies with standard table shells and tight submission timelines, where producing a fixed set of CSR tables within a single framework is the primary objective.</li>
<li><strong>ARD-first</strong> (<code>{cards}</code> paired with <code>tbl_ard_summary()</code> or <code>{tfrmt}</code>) fits larger drug programmes, cross-study integrated summaries of safety (ISS), interactive reporting platforms, and teams transitioning toward standardized statistical data exchange.</li>
</ul>
</section>
</section>
</section>
<section id="output-formats-and-clinical-publishing" class="level2">
<h2 class="anchored" data-anchor-id="output-formats-and-clinical-publishing">Output formats and clinical publishing</h2>
<p>Clinical trial reporting requires strict adherence to regulatory formatting guidelines:</p>
<ul>
<li><strong>RTF via <code>{r2rtf}</code></strong>: RTF is still a common delivery format for CSR tables and listings. <a href="https://cran.r-project.org/package=r2rtf"><code>{r2rtf}</code></a> provides granular programmatic control over submission RTFs (<code>rtf_body()</code>, <code>rtf_encode()</code>, <code>write_rtf()</code>), enabling precise configuration of margins, cell heights, borders, and page orientations.</li>
<li><strong>RTF export via <code>{gt}</code></strong>: <code>{gtsummary}</code> tables (via <code>as_gt()</code>) and <code>{tfrmt}</code> tables (via <code>print_to_gt()</code>) are <code>{gt}</code> objects, and <code>gt::gtsave(gt_tbl, "table.rtf")</code> writes them to RTF.</li>
<li><strong>Patient listings via <code>{rlistings}</code></strong>: Patient listings demand specialised pagination and layout behaviour. <a href="https://cran.r-project.org/package=rlistings"><code>{rlistings}</code></a> (<code>as_listing()</code>) automatically suppresses repeating keys across successive rows (<code>key_cols</code>), and handles column wrapping and pagination for long listings:</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;">library</span>(rlistings)</span>
<span id="cb7-2"></span>
<span id="cb7-3">adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb7-4"></span>
<span id="cb7-5">lsting <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">as_listing</span>(</span>
<span id="cb7-6">  <span class="at" style="color: #657422;">df =</span> adsl_saf,</span>
<span id="cb7-7">  <span class="at" style="color: #657422;">key_cols =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"TRT01A"</span>, <span class="st" style="color: #20794D;">"USUBJID"</span>),</span>
<span id="cb7-8">  <span class="at" style="color: #657422;">disp_cols =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"TRT01A"</span>, <span class="st" style="color: #20794D;">"USUBJID"</span>, <span class="st" style="color: #20794D;">"AGE"</span>, <span class="st" style="color: #20794D;">"SEX"</span>, <span class="st" style="color: #20794D;">"RACE"</span>)</span>
<span id="cb7-9">)</span></code></pre></div></div>
<ul>
<li><strong>Clinical figures with <code>{ggplot2}</code></strong>: Figures must maintain consistent visual hierarchy across a CSR. Standardise a project-level theme (extending <code>theme_minimal()</code> or <code>theme_classic()</code>) to enforce uniform font sizes, axis line widths, and colour palettes.</li>
<li><strong>Titles, footnotes, and pagination conventions</strong>: In regulatory reporting, titles and footnotes represent auditable provenance metadata. Define study-wide conventions to capture the table identifier, analysis population, data cut-off date, and source script path on every page.</li>
</ul>
</section>
<section id="team-conventions-and-gxp-discipline" class="level2">
<h2 class="anchored" data-anchor-id="team-conventions-and-gxp-discipline">Team conventions and GxP discipline</h2>
<p>Tool diversity without governance leads to fragmented pipelines. Applying software engineering discipline to TFL generation requires four shared team practices:</p>
<ul>
<li><strong>One table framework per study or team</strong>: Standardising on <code>{rtables}</code> or <code>{Tplyr}</code> across a team enables shared helper functions, uniform review standards, and collective code ownership.</li>
<li><strong>The mock shell as a contract</strong>: Treat mock shells from the Statistical Analysis Plan as formal schema contracts. Specifying exact row labels, column splits, and statistic requirements upfront prevents miscommunication.</li>
<li><strong>Pinned runtime environments</strong>: Reproducible reporting requires pinning package versions using <code>renv</code>. Discrepancies in package versions or operating system defaults can subtly alter text wrapping, pagination, or rounding behaviour across developer environments and CI runners.</li>
<li><strong>Validation-ready mindset</strong>: An open-source R package cannot simply be declared “validated” off the shelf. Qualification is an organisational, risk-based assessment that evaluates whether a package is fit for its intended purpose within a qualified execution environment. Combine pinned dependencies with independent double-programming quality control to produce defensible, auditable clinical deliverables.</li>
</ul>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Different defaults for the same statistic</strong>: packages format numbers differently out of the box. In this post’s companion script (<a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/scripts/tfl-demo.R">scripts/tfl-demo.R</a>), <code>{gtsummary}</code>’s default shows a median of 75.5 as “76”, while <code>{rtables}</code> + <code>{tern}</code> shows “75.5”. Put decimal places and rounding rules in the shell, and set them explicitly in code.</li>
<li><strong>Formatting numbers inside ADaM datasets</strong>: Concatenating numbers into strings (such as <code>"75.2 (8.6)"</code>) within ADaM columns destroys their utility for subsequent analyses or modeling. Keep ADaM strictly numeric and typed; leave formatting strings to the presentation layer.</li>
<li><strong>Fragile column width definitions</strong>: Hardcoding absolute column widths in characters or pixels often leads to clipped text or awkward wrapping when converting between HTML previews and landscape RTFs. Use proportional column widths wherever possible.</li>
<li><strong>Divergent Big-N denominators</strong>: Calculating percentage denominators from the filtered table subset rather than the true population total generates inaccurate percentages for sparse safety events. Ensure your table framework explicitly references the true population header counts.</li>
<li><strong>Mixing frameworks across study tables</strong>: Using <code>{rtables}</code> for demographic tables and <code>{Tplyr}</code> for adverse events within the same study creates duplicated formatting utilities, complicates code reviews, and doubles the team’s package qualification surface.</li>
</ul>
<div class="callout callout-style-simple callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Coming up in the Pharma series
</div>
</div>
<div class="callout-body-container callout-body">
<p>Later posts explore generating Analysis Results Data with <code>{cards}</code> in depth, adopting the CDISC Analysis Results Standard (ARS), and establishing independent double-programming quality control in R.</p>
</div>
</div>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/scripts/tfl-demo.R">View <code>tfl-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/scripts/tfl-demo.R" download="tfl-demo.R">Download</a></p>
<p>Builds a demographics summary table three ways: using <code>{rtables}</code> with <code>{tern}</code>, <code>{gtsummary}</code>, and an ARD dataset from <code>{cards}</code> rendered with <code>{gtsummary}</code>, exporting output via <code>{gt}</code>. Requires <code>{pharmaverseadam}</code>, <code>{dplyr}</code>, <code>{rtables}</code>, <code>{tern}</code>, <code>{gtsummary}</code>, <code>{cards}</code>, and <code>{gt}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>tfl-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="co" style="color: #5E5E5E;"># One demographics summary, three ways: {rtables} + {tern}, {gtsummary}, and</span></span>
<span id="cb8-2"><span class="co" style="color: #5E5E5E;"># an Analysis Results Data (ARD) set from {cards} rendered with</span></span>
<span id="cb8-3"><span class="co" style="color: #5E5E5E;"># gtsummary::tbl_ard_summary(). Then writes the gtsummary table to RTF.</span></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;"># Data: {pharmaverseadam} ADSL (example data, not real patients).</span></span>
<span id="cb8-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb8-6"><span class="co" style="color: #5E5E5E;">#   Rscript tfl-demo.R</span></span>
<span id="cb8-7"></span>
<span id="cb8-8"><span class="co" style="color: #5E5E5E;"># Safety population, with factors so every table shows the same levels.</span></span>
<span id="cb8-9">safety_adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">adsl =</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl) {</span>
<span id="cb8-10">  adsl <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb8-11">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">filter</span>(SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb8-12">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mutate</span>(<span class="at" style="color: #657422;">TRT01A =</span> <span class="fu" style="color: #4758AB;">factor</span>(TRT01A), <span class="at" style="color: #657422;">SEX =</span> <span class="fu" style="color: #4758AB;">factor</span>(SEX))</span>
<span id="cb8-13">}</span>
<span id="cb8-14"></span>
<span id="cb8-15"><span class="co" style="color: #5E5E5E;"># 1. Direct table code: an rtables layout with a tern analysis function.</span></span>
<span id="cb8-16">demog_rtables <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(adsl) {</span>
<span id="cb8-17">  rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">basic_table</span>(</span>
<span id="cb8-18">    <span class="at" style="color: #657422;">title =</span> <span class="st" style="color: #20794D;">"Demographics"</span>,</span>
<span id="cb8-19">    <span class="at" style="color: #657422;">subtitles =</span> <span class="st" style="color: #20794D;">"Safety population"</span></span>
<span id="cb8-20">  ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb8-21">    rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">split_cols_by</span>(<span class="st" style="color: #20794D;">"TRT01A"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb8-22">    rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">add_overall_col</span>(<span class="st" style="color: #20794D;">"All patients"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb8-23">    tern<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">analyze_vars</span>(</span>
<span id="cb8-24">      <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"AGE"</span>, <span class="st" style="color: #20794D;">"SEX"</span>),</span>
<span id="cb8-25">      <span class="at" style="color: #657422;">var_labels =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="at" style="color: #657422;">AGE =</span> <span class="st" style="color: #20794D;">"Age (years)"</span>, <span class="at" style="color: #657422;">SEX =</span> <span class="st" style="color: #20794D;">"Sex"</span>)</span>
<span id="cb8-26">    ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb8-27">    rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">build_table</span>(adsl)</span>
<span id="cb8-28">}</span>
<span id="cb8-29"></span>
<span id="cb8-30"><span class="co" style="color: #5E5E5E;"># 2. Direct table code: gtsummary.</span></span>
<span id="cb8-31">demog_gtsummary <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(adsl) {</span>
<span id="cb8-32">  gtsummary<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">tbl_summary</span>(</span>
<span id="cb8-33">    adsl,</span>
<span id="cb8-34">    <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb8-35">    <span class="at" style="color: #657422;">include =</span> <span class="fu" style="color: #4758AB;">c</span>(AGE, SEX),</span>
<span id="cb8-36">    <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">AGE =</span> <span class="st" style="color: #20794D;">"Age (years)"</span>, <span class="at" style="color: #657422;">SEX =</span> <span class="st" style="color: #20794D;">"Sex"</span>)</span>
<span id="cb8-37">  )</span>
<span id="cb8-38">}</span>
<span id="cb8-39"></span>
<span id="cb8-40"><span class="co" style="color: #5E5E5E;"># 3. ARD-first: compute the numbers as data, then render them.</span></span>
<span id="cb8-41">demog_ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(adsl) {</span>
<span id="cb8-42">  cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_stack</span>(</span>
<span id="cb8-43">    adsl,</span>
<span id="cb8-44">    <span class="at" style="color: #657422;">.by =</span> TRT01A,</span>
<span id="cb8-45">    cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_continuous</span>(<span class="at" style="color: #657422;">variables =</span> AGE),</span>
<span id="cb8-46">    cards<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ard_categorical</span>(<span class="at" style="color: #657422;">variables =</span> SEX),</span>
<span id="cb8-47">    <span class="at" style="color: #657422;">.attributes =</span> <span class="cn" style="color: #8f5902;">TRUE</span> <span class="co" style="color: #5E5E5E;"># variable labels, for the rendered table</span></span>
<span id="cb8-48">  )</span>
<span id="cb8-49">}</span>
<span id="cb8-50"></span>
<span id="cb8-51">demog_from_ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(ard) {</span>
<span id="cb8-52">  gtsummary<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">tbl_ard_summary</span>(</span>
<span id="cb8-53">    ard,</span>
<span id="cb8-54">    <span class="at" style="color: #657422;">by =</span> TRT01A,</span>
<span id="cb8-55">    <span class="at" style="color: #657422;">label =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">AGE =</span> <span class="st" style="color: #20794D;">"Age (years)"</span>, <span class="at" style="color: #657422;">SEX =</span> <span class="st" style="color: #20794D;">"Sex"</span>)</span>
<span id="cb8-56">  )</span>
<span id="cb8-57">}</span>
<span id="cb8-58"></span>
<span id="cb8-59"><span class="co" style="color: #5E5E5E;"># RTF output via gt.</span></span>
<span id="cb8-60">write_rtf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(tbl, path) {</span>
<span id="cb8-61">  gt<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">gtsave</span>(gtsummary<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">as_gt</span>(tbl), path)</span>
<span id="cb8-62">  <span class="fu" style="color: #4758AB;">invisible</span>(path)</span>
<span id="cb8-63">}</span>
<span id="cb8-64"></span>
<span id="cb8-65"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb8-66"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb8-67">  adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">safety_adsl</span>()</span>
<span id="cb8-68">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">demog_rtables</span>(adsl))</span>
<span id="cb8-69">  <span class="fu" style="color: #4758AB;">print</span>(gtsummary<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">as_kable</span>(<span class="fu" style="color: #4758AB;">demog_gtsummary</span>(adsl)))</span>
<span id="cb8-70">  ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">demog_ard</span>(adsl)</span>
<span id="cb8-71">  <span class="fu" style="color: #4758AB;">print</span>(ard[ard<span class="sc" style="color: #5E5E5E;">$</span>stat_name <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"mean"</span>, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"group1_level"</span>, <span class="st" style="color: #20794D;">"variable"</span>, <span class="st" style="color: #20794D;">"stat"</span>)])</span>
<span id="cb8-72">  <span class="fu" style="color: #4758AB;">print</span>(gtsummary<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">as_kable</span>(<span class="fu" style="color: #4758AB;">demog_from_ard</span>(ard)))</span>
<span id="cb8-73">  path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">write_rtf</span>(<span class="fu" style="color: #4758AB;">demog_gtsummary</span>(adsl), <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"demog.rtf"</span>))</span>
<span id="cb8-74">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"RTF written to "</span>, path)</span>
<span id="cb8-75">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards and organisations</strong></p>
<ul>
<li><strong>pharmaverse</strong> initiative: <a href="https://pharmaverse.org">pharmaverse.org</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
<li><strong>rtables</strong>: <a href="https://cran.r-project.org/package=rtables">CRAN</a></li>
<li><strong>tern</strong>: <a href="https://cran.r-project.org/package=tern">CRAN</a></li>
<li><strong>Tplyr</strong>: <a href="https://atorus-research.github.io/Tplyr/">atorus-research.github.io/Tplyr</a></li>
<li><strong>gtsummary</strong>: <a href="https://www.danieldsjoberg.com/gtsummary/">danieldsjoberg.com/gtsummary</a></li>
<li><strong>cards</strong>: <a href="https://pharmaverse.github.io/cards/">pharmaverse.github.io/cards</a></li>
<li><strong>tfrmt</strong>: <a href="https://cran.r-project.org/package=tfrmt">CRAN</a></li>
<li><strong>r2rtf</strong>: <a href="https://cran.r-project.org/package=r2rtf">CRAN</a></li>
<li><strong>gt</strong>: <a href="https://gt.rstudio.com">gt.rstudio.com</a></li>
<li><strong>rlistings</strong>: <a href="https://cran.r-project.org/package=rlistings">CRAN</a></li>
<li><strong>ggplot2</strong>: <a href="https://ggplot2.tidyverse.org/">ggplot2.tidyverse.org</a></li>
<li><strong>waldo</strong>: <a href="https://waldo.r-lib.org/">waldo.r-lib.org</a></li>
<li><strong>diffdf</strong>: <a href="https://cran.r-project.org/package=diffdf">CRAN</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-series-nav__series">Pharma series · part 2 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 1</span><span class="site-related-card__title">The clinical reporting pipeline in R</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 3</span><span class="site-related-card__title">Analysis Results Data in R with {cards} and {cardx}</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html" class="site-link-row" title="Capture complex console output, rtables layouts, and plots with testthat snapshots and vdiffr to catch regressions without fragile manual assertions."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Snapshot tests for R output, tables and plots</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/index.html" class="site-link-row" title="Declare external packages in DESCRIPTION Imports and Suggests, call functions through pkg::fun() or @importFrom, and guard optional dependencies cleanly."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Dependencies: DESCRIPTION and NAMESPACE</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html" class="site-link-row" title="Manage dependencies through lockfiles, runtime pinning, and package vetting for reproducible R environments."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Dependency updates, runtime pinning &amp; package vetting</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Pharma</category>
  <category>R</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/tfl-generation-r/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Git workflow: branches, squash-only merges, signed commits</title>
  <link>https://insightsurge-dev.web.app/posts/git-workflow/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Solo R work often happens straight on <code>main</code>: edit, commit, push. It works until two people touch the same package, a half-finished change reaches a user, or someone asks “who approved this change, and what tests ran?”</p>
<p>A small workflow fixes all three, and every piece of it has an R-native helper.</p>
</section>
<section id="the-workflow" class="level2">
<h2 class="anchored" data-anchor-id="the-workflow">The workflow</h2>
<pre><code>main ──●───────────────●──────────  (always releasable; one squash commit per PR)
        \             /
         ●──●──●──●──●   feat/km-risk-table  (messy commits are fine here)
                      └─ PR: title "feat(km_plot): add risk table", CI green, reviewed</code></pre>
<ol type="1">
<li><strong>Branch</strong> from an up-to-date <code>main</code>, one branch per issue: <code>feat/…</code>, <code>fix/…</code>, <code>docs/…</code>.</li>
<li><strong>Commit freely</strong> on the branch.</li>
<li><strong>Open a PR.</strong> CI runs, someone reviews, and the PR title follows <a href="https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/index.html">Conventional Commits</a>.</li>
<li><strong>Squash-merge.</strong> The branch becomes one commit on <code>main</code>, and the branch is deleted.</li>
</ol>
</section>
<section id="the-web-repo-way-repo-settings" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-repo-settings">The web-repo way: repo settings</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb2-1"><span class="ex" style="color: null;">gh</span> api <span class="at" style="color: #657422;">-X</span> PATCH repos/OWNER/REPO <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb2-2">  <span class="at" style="color: #657422;">-F</span> allow_squash_merge=true <span class="at" style="color: #657422;">-F</span> allow_merge_commit=false <span class="at" style="color: #657422;">-F</span> allow_rebase_merge=false <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb2-3">  <span class="at" style="color: #657422;">-F</span> delete_branch_on_merge=true <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb2-4">  <span class="at" style="color: #657422;">-f</span> squash_merge_commit_title=PR_TITLE <span class="at" style="color: #657422;">-f</span> squash_merge_commit_message=PR_BODY</span></code></pre></div></div>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Setting</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Squash only</td>
<td>Linear history, where one commit is one reviewed change. <code>git revert &lt;sha&gt;</code> undoes a whole feature.</td>
</tr>
<tr class="even">
<td>Title = PR title</td>
<td>The commit message is the reviewed, conventional title</td>
</tr>
<tr class="odd">
<td>Auto-delete branches</td>
<td>No graveyard of stale branches</td>
</tr>
</tbody>
</table>
</div>
<section id="branch-protection-check-your-plan" class="level3">
<h3 class="anchored" data-anchor-id="branch-protection-check-your-plan">Branch protection: check your plan</h3>
<p>Branch protection and rulesets are what <em>enforce</em> “no direct pushes to <code>main</code>” and “CI must pass”. <strong>On GitHub Free they only work on public repos.</strong> We checked a private repo on a free account, and the API answered: <em>“Upgrade to GitHub Pro or make this repository public to enable this feature.”</em></p>
<p>On a private free repo you have two options: follow the workflow <strong>by convention</strong> (and say so in <code>CONTRIBUTING.md</code>), or upgrade. On Team or Enterprise plans, turn on: require a PR, require status checks (<code>R-CMD-check</code>), require linear history, and block force-pushes.</p>
</section>
</section>
<section id="signed-commits" class="level2">
<h2 class="anchored" data-anchor-id="signed-commits">Signed commits</h2>
<p><code>user.email</code> is just text; anyone can type yours. A <strong>signature</strong> proves a commit came from a key you control, and GitHub then shows <strong>Verified</strong>. SSH signing reuses the kind of key you already push with:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode ini code-with-copy"><code class="sourceCode ini"><span id="cb3-1"><span class="kw" style="color: #003B4F;
font-weight: bold;">[gpg]</span></span>
<span id="cb3-2"><span class="dt" style="color: #AD0000;">    format </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> ssh</span></span>
<span id="cb3-3"><span class="kw" style="color: #003B4F;
font-weight: bold;">[user]</span></span>
<span id="cb3-4"><span class="dt" style="color: #AD0000;">    signingkey </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> ~/.ssh/id_ed25519_work.pub</span></span>
<span id="cb3-5"><span class="kw" style="color: #003B4F;
font-weight: bold;">[commit]</span></span>
<span id="cb3-6"><span class="dt" style="color: #AD0000;">    gpgsign </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">true</span></span>
<span id="cb3-7"><span class="kw" style="color: #003B4F;
font-weight: bold;">[tag]</span></span>
<span id="cb3-8"><span class="dt" style="color: #AD0000;">    gpgsign </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">true</span></span></code></pre></div></div>
<p>Add the <strong>same public key to GitHub a second time, as a Signing key</strong>. The Authentication key entry doesn’t cover signing.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>“No signature” locally doesn’t mean unsigned
</div>
</div>
<div class="callout-body-container callout-body">
<p>After enabling signing, <code>git log --show-signature</code> printed <em>“No signature”</em> with an error about <code>gpg.ssh.allowedSignersFile</code>. The commit <strong>was</strong> signed: <code>git cat-file -p HEAD</code> showed a <code>BEGIN SSH SIGNATURE</code> block, and GitHub marked it Verified. Git simply had no list of keys to trust locally. Fix:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"you@users.noreply.github.com </span><span class="va" style="color: #111111;">$(</span><span class="fu" style="color: #4758AB;">cut</span> <span class="at" style="color: #657422;">-d</span><span class="st" style="color: #20794D;">' '</span> <span class="at" style="color: #657422;">-f1,2</span> ~/.ssh/id_ed25519_work.pub<span class="va" style="color: #111111;">)</span><span class="st" style="color: #20794D;">"</span> <span class="op" style="color: #5E5E5E;">&gt;</span> ~/.ssh/allowed_signers</span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;">git</span> config gpg.ssh.allowedSignersFile ~/.ssh/allowed_signers</span></code></pre></div></div>
<p>Now <code>git log --show-signature</code> reports <em>Good “git” signature</em>.</p>
</div>
</div>
<p>For GxP, signed commits plus PR review are strong evidence of <strong>who</strong> made a change and <strong>who approved it</strong>. The same ALCOA+ <em>Attributable</em> point comes up in <a href="https://insightsurge-dev.web.app/posts/identity-isolation/index.html">identity and environment isolation</a>.</p>
</section>
<section id="the-r-way-usethispr_" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-usethispr_">The R way: <code>usethis::pr_*()</code></h2>
<p><code>usethis</code> wraps the whole loop, so you never need to remember the git commands:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pr_init</span>(<span class="st" style="color: #20794D;">"feat-km-risk-table"</span>)  <span class="co" style="color: #5E5E5E;"># branch from an up-to-date default branch</span></span>
<span id="cb5-2"><span class="co" style="color: #5E5E5E;"># ... edit, commit (RStudio/Positron Git pane is fine) ...</span></span>
<span id="cb5-3">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pr_push</span>()                       <span class="co" style="color: #5E5E5E;"># push and open the PR page in the browser</span></span>
<span id="cb5-4">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pr_pull</span>()                       <span class="co" style="color: #5E5E5E;"># pull reviewer changes</span></span>
<span id="cb5-5">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pr_merge_main</span>()                 <span class="co" style="color: #5E5E5E;"># bring in new commits from main</span></span>
<span id="cb5-6">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pr_finish</span>()                     <span class="co" style="color: #5E5E5E;"># after merge: delete local branch, back to main</span></span>
<span id="cb5-7">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">pr_fetch</span>(<span class="dv" style="color: #AD0000;">42</span>)                    <span class="co" style="color: #5E5E5E;"># check out someone else's PR #42 to review it</span></span></code></pre></div></div>
<p>Squash-merge in the GitHub UI, or with <code>gh pr merge 42 --squash</code>. The IDE Git panes call your system <code>git</code>, so signing configured in git applies to IDE commits too.</p>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong><code>git pull</code> merge commits.</strong> Set <code>git config --global pull.rebase true</code>.</li>
<li><strong>Long-lived branches</strong> drift and conflict. Keep PRs small, and use <code>pr_merge_main()</code> often.</li>
<li><strong>Squash hides branch history on <code>main</code>.</strong> That’s the point: the PR keeps the detail.</li>
<li><strong>Signing key on a new machine.</strong> Signing fails until the key and config exist, so set it up once per machine (<a href="https://insightsurge-dev.web.app/posts/identity-isolation/index.html">identity and environment isolation</a>).</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Git and GitHub</strong></p>
<ul>
<li><strong>git config (<code>gpg.format</code>, <code>gpg.ssh.allowedSignersFile</code>, <code>commit.gpgsign</code>)</strong>: <a href="https://git-scm.com/docs/git-config#Documentation/git-config.txt-gpgsshallowedSignersFile">git-scm.com/docs/git-config</a></li>
<li><strong>Repository settings API (squash-only merge, branch deletion)</strong>: <a href="https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#update-a-repository">GitHub REST API: Update a repository</a></li>
<li><strong>Branch protection</strong>: <a href="https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches">GitHub Docs: About protected branches</a></li>
<li><strong>Rulesets</strong>: <a href="https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets">GitHub Docs: About rulesets</a></li>
<li><strong>Signing commits (SSH signatures, Verified badge)</strong>: <a href="https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits">GitHub Docs: Signing commits</a></li>
<li><strong><code>gh pr merge</code></strong>: <a href="https://cli.github.com/manual/gh_pr_merge">cli.github.com/manual/gh_pr_merge</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>pr_init()</code>, <code>pr_push()</code>, <code>pr_pull()</code>, <code>pr_merge_main()</code>, <code>pr_finish()</code>, <code>pr_fetch()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 2 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/identity-isolation/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 1</span><span class="site-related-card__title">Identity &amp; environment isolation</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 3</span><span class="site-related-card__title">Conventional commits &amp; PR title checks</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/test-your-guardrails/index.html" class="site-link-row" title="Challenge CI checks and pre-commit hooks deliberately with failing test PRs to prove guardrails work."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Test your guardrails: probe PRs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html" class="site-link-row" title="Adopt semantic versioning, readable changelogs, and annotated git tags to support change control."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Releases &amp; changelogs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/two-model-workflow/index.html" class="site-link-row" title="Structure dual-model AI workflows with clear task ownership, written briefs, and human verification to maintain engineering rigor."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">One owner, two models: delegating to a second AI and verifying it</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Git</category>
  <category>GxP</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/git-workflow/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Google Analytics with cookie consent on a Quarto site</title>
  <link>https://insightsurge-dev.web.app/posts/quarto-google-analytics-consent/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Adding analytics to a documentation site or technical blog seems trivial until you consider privacy rules and development noise:</p>
<ol type="1">
<li><strong>Unconditional tracking breaches privacy standards.</strong> Injecting a standard tracking script causes the browser to fetch third-party scripts and set tracking cookies (<code>_ga</code>, <code>_ga_*</code>) the moment a page opens. Under EU GDPR/ePrivacy rules, non-essential cookies such as analytics generally need prior opt-in consent.</li>
<li><strong>Preview noise pollutes production metrics.</strong> If your analytics tag is enabled in the default site configuration, every local build, automated CI render, and pull request preview logs page views into your production dashboard.</li>
<li><strong>Confusion between public IDs and secrets.</strong> Developers often treat Google Analytics Measurement IDs (<code>G-XXXXXXXXXX</code>) as confidential secrets and attempt to hide them behind environment variables. In reality, client-side tracking IDs are embedded in plain text within page source by design.</li>
</ol>
<p>The goal is to enable Google Analytics 4 (GA4) with a clear opt-in consent mechanism, while ensuring that local previews and automated builds generate no tracking requests.</p>
</section>
<section id="the-quarto-way-profiles-and-express-consent" class="level2">
<h2 class="anchored" data-anchor-id="the-quarto-way-profiles-and-express-consent">The Quarto way: profiles and express consent</h2>
<p>Quarto provides native support for both Google Analytics 4 and cookie consent management via its site metadata. Rather than baking the tracking configuration into the primary <code>_quarto.yml</code>, we isolate it in an environment profile:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="co" style="color: #5E5E5E;"># _quarto-live.yml (merged only when QUARTO_PROFILE=live)</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">website</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">google-analytics</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">tracking-id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"G-XXXXXXXXXX"</span><span class="co" style="color: #5E5E5E;">   # Public GA4 measurement stream ID</span></span>
<span id="cb1-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">anonymize-ip</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb1-6"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">cookie-consent</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> express</span><span class="co" style="color: #5E5E5E;">                  # No tracking cookies until explicit opt-in</span></span>
<span id="cb1-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">style</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> simple</span></span>
<span id="cb1-9"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">palette</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> light</span></span></code></pre></div></div>
<section id="how-express-consent-functions" class="level3">
<h3 class="anchored" data-anchor-id="how-express-consent-functions">How express consent functions</h3>
<p>When <code>cookie-consent: type: express</code> is declared, Quarto does not inject an immediately executable analytics snippet. Instead, it rewrites the script tag roughly like this:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode html code-with-copy"><code class="sourceCode html"><span id="cb2-1"><span class="dt" style="color: #AD0000;">&lt;</span><span class="kw" style="color: #003B4F;
font-weight: bold;">script</span><span class="ot" style="color: #003B4F;"> type=</span><span class="st" style="color: #20794D;">"text/plain"</span><span class="ot" style="color: #003B4F;"> cookie-consent</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"tracking"</span><span class="dt" style="color: #AD0000;">&gt;</span></span>
<span id="cb2-2">  <span class="bu" style="color: null;">window</span><span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">dataLayer</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="bu" style="color: null;">window</span><span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">dataLayer</span> <span class="op" style="color: #5E5E5E;">||</span> []<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb2-3">  <span class="kw" style="color: #003B4F;
font-weight: bold;">function</span> <span class="fu" style="color: #4758AB;">gtag</span>(){dataLayer<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">push</span>(<span class="kw" style="color: #003B4F;
font-weight: bold;">arguments</span>)<span class="op" style="color: #5E5E5E;">;</span>}</span>
<span id="cb2-4">  <span class="fu" style="color: #4758AB;">gtag</span>(<span class="st" style="color: #20794D;">'js'</span><span class="op" style="color: #5E5E5E;">,</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">new</span> <span class="bu" style="color: null;">Date</span>())<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb2-5">  <span class="fu" style="color: #4758AB;">gtag</span>(<span class="st" style="color: #20794D;">'config'</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">'G-XXXXXXXXXX'</span><span class="op" style="color: #5E5E5E;">,</span> { <span class="st" style="color: #20794D;">'anonymize_ip'</span><span class="op" style="color: #5E5E5E;">:</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">true</span>})<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb2-6"><span class="dt" style="color: #AD0000;">&lt;/</span><span class="kw" style="color: #003B4F;
font-weight: bold;">script</span><span class="dt" style="color: #AD0000;">&gt;</span></span></code></pre></div></div>
<p>Because the MIME type is <code>text/plain</code>, the browser refuses to execute the script during initial page parsing. The bundled consent library (served from <code>site_libs/cookie-consent/</code>) activates scripts marked <code>cookie-consent="tracking"</code> once the visitor opts in, and records the choice in a <code>cookie_consent_level</code> cookie.</p>
</section>
<section id="hold-back-the-loader-too" class="level3">
<h3 class="anchored" data-anchor-id="hold-back-the-loader-too">Hold back the loader too</h3>
<p>Quarto’s <code>google-analytics:</code> option holds back only the configuration snippet. It also emits the loader as an ordinary script, <code>&lt;script async src="https://www.googletagmanager.com/gtag/js?id=..."&gt;</code>, so the browser requests it from Google on every page load, before the visitor has chosen anything.</p>
<p>The consent library can hold that back as well. When a visitor accepts a category, it recreates each <code>text/plain</code> script marked with that category as a real script and copies its <code>src</code>. So we stopped using Quarto’s <code>google-analytics:</code> option and load GA4 from an include, with both scripts marked:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb3-1"><span class="co" style="color: #5E5E5E;"># _quarto-live.yml</span></span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;">website</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">cookie-consent</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> express</span></span>
<span id="cb3-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">style</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> simple</span></span>
<span id="cb3-6"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">palette</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> light</span></span>
<span id="cb3-7"></span>
<span id="cb3-8"><span class="fu" style="color: #4758AB;">format</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-9"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">html</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">include-in-header</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> _includes/analytics.html</span></span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode html code-with-copy"><code class="sourceCode html"><span id="cb4-1"><span class="co" style="color: #5E5E5E;">&lt;!-- _includes/analytics.html --&gt;</span></span>
<span id="cb4-2"><span class="dt" style="color: #AD0000;">&lt;</span><span class="kw" style="color: #003B4F;
font-weight: bold;">script</span><span class="ot" style="color: #003B4F;"> type=</span><span class="st" style="color: #20794D;">"text/plain"</span><span class="ot" style="color: #003B4F;"> cookie-consent</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"tracking"</span><span class="ot" style="color: #003B4F;"> async</span></span>
<span id="cb4-3"><span class="ot" style="color: #003B4F;">        src</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"</span><span class="dt" style="color: #AD0000;">&gt;&lt;/</span><span class="kw" style="color: #003B4F;
font-weight: bold;">script</span><span class="dt" style="color: #AD0000;">&gt;</span></span>
<span id="cb4-4"><span class="dt" style="color: #AD0000;">&lt;</span><span class="kw" style="color: #003B4F;
font-weight: bold;">script</span><span class="ot" style="color: #003B4F;"> type=</span><span class="st" style="color: #20794D;">"text/plain"</span><span class="ot" style="color: #003B4F;"> cookie-consent</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"tracking"</span><span class="dt" style="color: #AD0000;">&gt;</span></span>
<span id="cb4-5">  <span class="bu" style="color: null;">window</span><span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">dataLayer</span> <span class="op" style="color: #5E5E5E;">=</span> <span class="bu" style="color: null;">window</span><span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">dataLayer</span> <span class="op" style="color: #5E5E5E;">||</span> []<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb4-6">  <span class="kw" style="color: #003B4F;
font-weight: bold;">function</span> <span class="fu" style="color: #4758AB;">gtag</span>(){dataLayer<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">push</span>(<span class="kw" style="color: #003B4F;
font-weight: bold;">arguments</span>)<span class="op" style="color: #5E5E5E;">;</span>}</span>
<span id="cb4-7">  <span class="fu" style="color: #4758AB;">gtag</span>(<span class="st" style="color: #20794D;">'js'</span><span class="op" style="color: #5E5E5E;">,</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">new</span> <span class="bu" style="color: null;">Date</span>())<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb4-8">  <span class="fu" style="color: #4758AB;">gtag</span>(<span class="st" style="color: #20794D;">'config'</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">'G-XXXXXXXXXX'</span><span class="op" style="color: #5E5E5E;">,</span> { <span class="st" style="color: #20794D;">'anonymize_ip'</span><span class="op" style="color: #5E5E5E;">:</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">true</span> })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb4-9"><span class="dt" style="color: #AD0000;">&lt;/</span><span class="kw" style="color: #003B4F;
font-weight: bold;">script</span><span class="dt" style="color: #AD0000;">&gt;</span></span></code></pre></div></div>
<p>The include sits in the <code>live</code> profile, so previews and local renders stay free of analytics as before.</p>
</section>
<section id="gating-analytics-in-github-actions" class="level3">
<h3 class="anchored" data-anchor-id="gating-analytics-in-github-actions">Gating analytics in GitHub Actions</h3>
<p>To keep pull request previews and local renders free of tracking tags, configure your CI workflow to activate the <code>live</code> profile only on merges to your primary branch:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># .github/workflows/quarto.yml</span></span>
<span id="cb5-2"><span class="fu" style="color: #4758AB;">env</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">QUARTO_PROFILE</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ github.event_name != 'pull_request' &amp;&amp; github.ref == 'refs/heads/main' &amp;&amp; 'live' || '' }}</span></span></code></pre></div></div>
<p>During a pull request build or local <code>quarto render</code>, <code>QUARTO_PROFILE</code> remains empty. Quarto reads only <code>_quarto.yml</code>, producing static HTML with no Google Analytics tags and no consent banner. When code merges into <code>main</code>, Quarto overlays <code>_quarto-live.yml</code> and produces the production build.</p>
</section>
</section>
<section id="what-we-observed" class="level2">
<h2 class="anchored" data-anchor-id="what-we-observed">What we observed</h2>
<p>We tested this configuration across local builds, pull requests, and live dev hosting on 2026-09-26:</p>
<ul>
<li><strong>Local and PR builds are sterile.</strong> Inspecting the rendered HTML of a PR preview showed no occurrences of <code>googletagmanager</code> or <code>G-</code>. No tracking code was present in the deployment.</li>
<li><strong>Opt-in operates as designed.</strong> On the live deployment, visiting the site presented the consent banner. Inspection of browser storage confirmed that <code>cookie_consent_level</code> was initialised with <code>tracking:false</code>. No <code>_ga</code> cookies existed in the browser before consent was clicked.</li>
<li><strong>A technical nuance on loader fetching.</strong> While Quarto blocks execution of the <code>gtag</code> configuration snippet, the external loader (<code>https://www.googletagmanager.com/gtag/js?id=...</code>) is still fetched over the network on initial page load. While no persistent cookies are set before consent, the HTTP request itself reaches Google’s servers. For teams with strict no-external-traffic requirements prior to consent, the loader tag itself must be gated. We now gate it (see <em>Hold back the loader too</em>).</li>
<li><strong>The gated loader, checked on 2026-09-27.</strong> We served a <code>live</code> render through the Firebase Hosting emulator, with the Measurement ID swapped for a test ID so no data reached the real stream. Before consent the browser made no request to <code>googletagmanager.com</code>, <code>gtag</code> was undefined and there were no <code>_ga</code> cookies. After clicking <em>I agree</em>, <code>gtag.js</code> was requested and the <code>_ga</code> cookies appeared. After <em>I decline</em> (in a fresh cookie store), the next page made no request and set no <code>_ga</code> cookies.</li>
<li><strong>Banner copy wording.</strong> Quarto’s default banner text contains boilerplate mentioning third-party advertising cookies. Because an engineering site runs no advertising networks, this wording is inaccurate. The wording cannot be changed through Quarto’s <code>cookie-consent</code> options (only <code>prefs-text</code> for the preferences link is configurable), and we are tracking a fix (a custom include or another consent tool).</li>
<li><strong>Measurement IDs are public.</strong> As shown in the HTML snippet above, the Measurement ID is visible to anyone inspecting page source. It does not require storage in a secret vault (see <a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html">secrets management</a>).</li>
</ul>
</section>
<section id="the-r-way-shiny-and-pkgdown" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-shiny-and-pkgdown">The R way: Shiny and pkgdown</h2>
<p>The same principles of environment separation and consent gating apply to the wider R ecosystem.</p>
<section id="shiny-applications" class="level3">
<h3 class="anchored" data-anchor-id="shiny-applications">Shiny applications</h3>
<p>Shiny applications often track user sessions or tab navigation by inserting <code>gtag()</code> calls via <code>tags$script()</code>. Firing <code>gtag("event", ...)</code> as soon as <code>server.R</code> runs places tracking cookies on the user’s system without permission.</p>
<p>To implement equivalent express consent in Shiny: 1. Store a user consent state in a reactive value or browser cookie. 2. Render the analytics script conditionally inside an <code>observeEvent()</code> only after the user accepts a consent modal or banner. 3. Check <code>Sys.getenv("R_CONFIG_ACTIVE")</code> or configuration settings so local development runs never initialise the tracking client.</p>
</section>
<section id="pkgdown-documentation-sites" class="level3">
<h3 class="anchored" data-anchor-id="pkgdown-documentation-sites">pkgdown documentation sites</h3>
<p>R package authors frequently include analytics to measure documentation usage. In <code>pkgdown</code>, custom scripts are added to <code>_pkgdown.yml</code> using <code>template.includes</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb6-1"><span class="fu" style="color: #4758AB;">template</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb6-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">includes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb6-3"><span class="fu" style="color: #4758AB;">    in_header</span><span class="kw" style="color: #003B4F;
font-weight: bold;">: </span><span class="ch" style="color: #20794D;">|</span></span>
<span id="cb6-4">      &lt;!-- Google tag (gtag.js) --&gt;</span>
<span id="cb6-5">      &lt;script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"&gt;&lt;/script&gt;</span>
<span id="cb6-6">      &lt;script&gt;</span>
<span id="cb6-7">        window.dataLayer = window.dataLayer || [];</span>
<span id="cb6-8">        function gtag(){dataLayer.push(arguments);}</span>
<span id="cb6-9">        gtag('js', new Date());</span>
<span id="cb6-10">        gtag('config', 'G-XXXXXXXXXX');</span>
<span id="cb6-11">      &lt;/script&gt;</span></code></pre></div></div>
<p>Unlike Quarto, <code>pkgdown</code> does not offer an out-of-the-box <code>cookie-consent</code> engine. Adding raw <code>gtag.js</code> in <code>in_header</code> fires tracking immediately for every reader. If your package documentation must respect cookie consent, you cannot rely on a single YAML switch. You must either embed a third-party consent banner script in <code>in_header</code> or manually structure the tracking snippet to read a consent flag before invoking <code>gtag('config')</code>.</p>
</section>
</section>
<section id="pitfalls-we-hit" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-we-hit">Pitfalls we hit</h2>
<ul>
<li><strong>Expecting analytics in default local renders.</strong> Running <code>quarto preview</code> or <code>quarto render</code> without specifying <code>--profile live</code> renders the base configuration. The banner will not appear. To test consent styling locally, run <code>QUARTO_PROFILE=live quarto preview</code>.</li>
<li><strong>Assuming the loader is completely blocked.</strong> As noted in our observations, Quarto’s built-in express consent delays the <em>config script</em> but still loads the external <code>gtag.js</code> script tag on initial render. Verify whether your organisation’s interpretation of privacy guidelines allows this external script fetch.</li>
<li><strong>Default banner mentions non-existent ad trackers.</strong> Leaving default Quarto banner copy intact can suggest that technical documentation shares data with advertising partners. Because Quarto’s options do not expose banner text configuration, addressing this requires a custom include or alternative consent integration.</li>
<li><strong>Hiding Measurement IDs in CI secrets.</strong> Storing a public tracking ID in GitHub Secrets adds maintenance burden without reducing risk. Keep identifiers in repository variables or profile configuration files.</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> The <code>gtag.js</code> loader is now held back until consent too (a custom include instead of Quarto’s <code>google-analytics:</code> option), with the browser check that shows it.</li>
</ul>
</div>
</div>
</div>



</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor site-related">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/building-this-blog/index.html" class="site-link-row" title="How we transformed a 14-part topic site into a Quarto engineering blog and portfolio using URL aliases, living-document conventions, and multi-model agentic collaboration."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Building this blog: from numbered topics to a living Quarto publication</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/hosted-site-pitfalls/index.html" class="site-link-row" title="A static Quarto site passed every local link and render test, but failed in a PR preview: how trailing slashes and unconfigured MIME types break hosted assets."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">It worked locally: two hosting bugs every check missed</span></a></li>
</ul>
</div>
</section>


 ]]></description>
  <category>Quarto</category>
  <category>Shiny</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/quarto-google-analytics-consent/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Handoffs &amp; agentic context</title>
  <link>https://insightsurge-dev.web.app/posts/handoffs-agentic-context/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>AI coding agents are fast, but every session starts cold. Teams typically compensate in one of two ways, and both are expensive:</p>
<ul>
<li><strong>very long chats</strong>, which cost tokens on every turn, drift, and can’t be reviewed later;</li>
<li><strong>re-explaining the project</strong> each time, which is slow and inconsistent.</li>
</ul>
<p>Instead, give the agent <strong>durable, versioned context</strong> (what a senior colleague would read on day one) plus <strong>short, curated notes</strong> about the work in progress.</p>
</section>
<section id="layer-1-project-instructions-claude.md-agents.md" class="level2">
<h2 class="anchored" data-anchor-id="layer-1-project-instructions-claude.md-agents.md">Layer 1: project instructions (<code>CLAUDE.md</code> / <code>AGENTS.md</code>)</h2>
<p>A markdown file at the repo root that the agent reads at the start of every session. <code>CLAUDE.md</code> is Claude Code’s file. <code>AGENTS.md</code> is a tool-neutral convention that several agents read, and Next.js now generates one for its own framework rules. A <code>CLAUDE.md</code> can import it (<code>@AGENTS.md</code>) and add project rules.</p>
<p>What belongs in it, and what we learned to put there:</p>
<div class="table-responsive">
<table class="caption-top table">
<thead>
<tr class="header">
<th>Section</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Stack + <strong>exact commands</strong> (test one file, full check, format)</td>
<td>Agents otherwise guess, and run the slow full suite every time</td>
</tr>
<tr class="even">
<td>Git rules (Conventional Commits, squash, <strong>no AI attribution</strong>)</td>
<td>Consistent history (<a href="https://insightsurge-dev.web.app/posts/git-workflow/index.html">git workflow</a>, <a href="https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/index.html">conventional commits</a>)</td>
</tr>
<tr class="odd">
<td><strong>Confidentiality rules</strong> (no client/employer names, no real data)</td>
<td>The agent will otherwise happily paste whatever it sees</td>
</tr>
<tr class="even">
<td>Domain rules (e.g.&nbsp;banned compliance claims or blanket validation claims)</td>
<td>Encodes review knowledge once</td>
</tr>
<tr class="odd">
<td><strong>Verification rule</strong>: done means tests pass, not “the model said so”</td>
<td>Self-reports are not evidence</td>
</tr>
<tr class="even">
<td>Handoff and teaching rules</td>
<td>Continuity and learning</td>
</tr>
</tbody>
</table>
</div>
<p>Keep it short and specific: these instructions take up context in each session. A starter for R packages is in <a href="https://insightsurge-dev.web.app/templates/agentic/CLAUDE.md"><code>templates/agentic/CLAUDE.md</code></a>.</p>
</section>
<section id="layer-2-handoffs-for-work-in-progress" class="level2">
<h2 class="anchored" data-anchor-id="layer-2-handoffs-for-work-in-progress">Layer 2: handoffs for work in progress</h2>
<p>We now keep <strong>long-lived areas</strong>, such as <code>content/</code>, <code>site/</code>, <code>design/</code> and <code>agents/</code>, under <code>dev/handoffs/</code>. An area survives individual issues and PRs. A short-lived feature folder still makes sense for bounded work; close it when that work is done.</p>
<p>The root <code>README.md</code> maps folders to responsibilities. An optional <code>overview/</code> holds shared priorities, decision pointers and a delivered index when work spans areas. Every folder uses the same numbered files (the first keeps its old name, <code>01-feature.md</code>):</p>
<pre class="text"><code>dev/handoffs/&lt;area&gt;/
├── README.md          # dated Status · Next step · Read order · Last session; ≤ 60 lines
├── 01-feature.md      # what and why, scope, acceptance, source-of-truth links
├── 02-code-map.md     # where things live
├── 03-open-issues.md  # open work: tracker pointers and current gotchas
├── 04-plan.md         # next steps, how work runs, verification
├── 05-questions.md    # pending decisions: question, options, recommendation
└── 06-delivered.md    # finished work, newest first, with links</code></pre>
<p>Delete files an area does not need, without renumbering; an overview without code needs no code map. Named extras are fine, including <code>overview/decisions.md</code> for brief decision pointers. The templates live inside the committed skill. The working notes stay <strong>local and gitignored</strong>.</p>
<p>We share one handoff skill across two repositories and two coding agents. Each repository keeps its own handoffs; each agent reads the skill from its own folder, with the instructions, helper and templates kept as identical copies. Shared behaviour does not mean shared session state across repositories. Within one repository, the helper resolves the main checkout’s handoffs, including when called from a worktree.</p>
<p>To use it, copy the published skill into your repository as <code>.claude/skills/handoff/</code> (another agent gets an identical copy in its own skills folder). The commands below use that path. For a new project, <code>init</code> creates the root index and an overview; <code>start content</code> copies the area templates. Both require <code>dev/handoffs/</code> to be gitignored. Fill in the new folder and add it to the root index yourself.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb2-1"><span class="fu" style="color: #4758AB;">bash</span> .claude/skills/handoff/scripts/handoff.sh init</span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">bash</span> .claude/skills/handoff/scripts/handoff.sh start content</span></code></pre></div></div>
<p>A fresh session reads the root index, then runs <code>status</code> to see each folder’s Status and Next step. Read only the area the task needs; read the overview when priorities cross areas.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="fu" style="color: #4758AB;">bash</span> .claude/skills/handoff/scripts/handoff.sh status</span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;">bash</span> .claude/skills/handoff/scripts/handoff.sh check</span></code></pre></div></div>
<p><code>check</code> warns about a missing root index or folder README, a README over 60 lines, and an active Status without a date or older than 14 days by default (<code>HANDOFF_STALE_DAYS</code>). It also checks recognised handoff paths in backticks. Repository paths are opt-in with <code>HANDOFF_CHECK_REPO_PATHS=1</code>; bare filenames, URLs and placeholders are skipped. This is a lint check, not proof that the tracker agrees with the notes. Warnings produce exit status 1.</p>
<p>Updating and closing are <strong>skill procedures</strong>, <code>/handoff update content</code> and <code>/handoff close content</code>, not shell subcommands. The rules that make the notes useful:</p>
<ul>
<li><strong>Verify before writing Status.</strong> Check the linked issues and PRs, the branch and the latest commit on main. Do not copy yesterday’s claim that a PR is open after it has merged.</li>
<li><strong>Update every area touched</strong>, before a PR, before compaction and when stopping or handing over. Change <code>overview/</code> only when a shared priority or decision changes, then run <code>check</code>.</li>
<li><strong>Keep the README short.</strong> Date the Status, give one concrete Next step and record 1–3 Last session bullets. Use absolute dates and a Read order. Move finished items from the README, open issues and plan to <code>06-delivered.md</code>, newest first, with brief links.</li>
<li><strong>Point to the tracker; don’t recreate it.</strong> Remove answered questions. Put lasting decisions in issues or <a href="https://insightsurge-dev.web.app/posts/adrs-and-evidence/index.html">ADRs</a>, documentation in the repo and reusable scripts in <code>tools/</code>. Handoffs are not backed up by git.</li>
<li><strong>Close bounded work deliberately.</strong> Do a final update, mark the dated Status as closed, link the durable outcomes and remove the live Next step. Keep the folder unless asked to delete it.</li>
</ul>
<p>When several repositories work together, a session in one often learns something another needs: an idea, a decision, a change, a note there that went stale. It writes it as an entry in the other repository’s inbox, <code>dev/handoffs/external-notes.md</code> (<code>handoff.sh note</code>). The receiving project treats each entry as a claim to verify, not a decision: it spreads what holds into its own notes, opens an issue for agreed work, and moves the entry along with <code>handoff.sh set</code> (<code>triaged</code>, <code>planned</code>, <code>in-progress</code>, then <code>done</code>, <code>future</code>, <code>rejected</code>, <code>duplicate</code> or <code>noted</code>). Handled entries shrink to one line at the bottom of the file, and that record is the point: when the same request arrives again months later, the next session can see it was already rejected, and why. A session hook announces new entries and blocks a merge while an entry has waited untriaged for a day.</p>
<p>For R readers, think of a package’s <code>NEWS.md</code> versus your working lab notebook: the package keeps its lasting change record, while the notebook tells you which test to open next. An area’s <code>06-delivered.md</code> is a local index to finished work, not a replacement for that record. For an R package, exclude <code>dev/</code> from the source tarball with <code>^dev$</code> in <code>.Rbuildignore</code> too.</p>
<section id="the-skill-files" class="level3">
<h3 class="anchored" data-anchor-id="the-skill-files">The skill files</h3>
<p>The full skill, as we run it, is published here. Keep its folder structure when you copy it (the script finds the templates next to itself):</p>
<ul>
<li><a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/SKILL.md"><code>SKILL.md</code></a>: the procedures</li>
<li><a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/scripts/handoff.sh"><code>scripts/handoff.sh</code></a>: the helper (<code>init</code>, <code>start</code>, <code>status</code>, <code>check</code>, and the inbox commands)</li>
<li><a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/scripts/external-notes.sh"><code>scripts/external-notes.sh</code></a>: the inbox commands (<code>inbox</code>, <code>note</code>, <code>set</code>, <code>migrate</code>, <code>gate</code>)</li>
<li><a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/scripts/hook.sh"><code>scripts/hook.sh</code></a> and <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/scripts/hook.py"><code>scripts/hook.py</code></a>: a session hook for Claude Code, Codex and Antigravity (announces new entries, guards merges)</li>
<li>Root index template: <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/root/README.md"><code>root/README.md</code></a></li>
<li>Inbox template: <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/root/external-notes.md"><code>root/external-notes.md</code></a></li>
<li>Overview decision log template: <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/overview/decisions.md"><code>overview/decisions.md</code></a></li>
<li>Area templates: <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/area/README.md"><code>README.md</code></a>, <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/area/01-feature.md"><code>01-feature.md</code></a>, <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/area/02-code-map.md"><code>02-code-map.md</code></a>, <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/area/03-open-issues.md"><code>03-open-issues.md</code></a>, <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/area/04-plan.md"><code>04-plan.md</code></a>, <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/area/05-questions.md"><code>05-questions.md</code></a>, <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/templates/area/06-delivered.md"><code>06-delivered.md</code></a></li>
</ul>
</section>
</section>
<section id="layer-3-skills-and-plugins" class="level2">
<h2 class="anchored" data-anchor-id="layer-3-skills-and-plugins">Layer 3: skills and plugins</h2>
<p>Reusable procedures (a release checklist, a handoff, a review recipe) can be packaged as <strong>skills</strong>: a <code>SKILL.md</code> with instructions, plus scripts and templates. The agent loads them only when relevant, though skill names and descriptions also take up context. Plugins can be enabled at <strong>project scope</strong> (<code>.claude/settings.json</code>) to share the selection with contributors.</p>
</section>
<section id="working-with-more-than-one-model" class="level2">
<h2 class="anchored" data-anchor-id="working-with-more-than-one-model">Working with more than one model</h2>
<p>On this project one model (Claude) <strong>owns</strong> the work: it plans, decides and verifies. A second (Gemini) takes well-scoped tasks: reading docs, analysing dependency PRs, drafting. The rules:</p>
<ul>
<li>Give a clear brief with acceptance checks and constraints (for example, “edit only this file; no git, no push”).</li>
<li>Take back a <strong>short digest</strong>, not a transcript.</li>
<li><strong>Re-check the evidence and review the diff.</strong> In our dependency case the second model’s conclusions held up, but review still surfaced a nuance it had glossed over.</li>
<li>Keep outward-facing actions (push, merge, publish) with the owner, after verification.</li>
</ul>
</section>
<section id="token-discipline-is-cost-governance" class="level2">
<h2 class="anchored" data-anchor-id="token-discipline-is-cost-governance">Token discipline is cost governance</h2>
<p>For teams paying for AI seats, context is money. I use these patterns to keep context focused:</p>
<ul>
<li>short project instructions;</li>
<li>handoffs instead of long chats;</li>
<li>targeted tests while iterating;</li>
<li>digests from delegated work;</li>
<li>skills loaded on demand.</li>
</ul>
<p>We don’t quote savings figures until we’ve measured them. Neither should you.</p>
</section>
<section id="the-gxp-angle" class="level2">
<h2 class="anchored" data-anchor-id="the-gxp-angle">The GxP angle</h2>
<ul>
<li><strong>No real data in prompts, ever.</strong> Use synthetic or public pilot data, or your organisation’s approved enterprise AI environment.</li>
<li><strong>A named human is accountable</strong> for every change an agent makes. It goes through the same PR, review and CI as human code.</li>
<li><strong>Provenance:</strong> keep the lasting record in commits, reviewed PRs and ADRs; local handoffs point to it.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<ul>
<li><strong><code>CLAUDE.md</code> / project memory</strong>: <a href="https://docs.claude.com/en/docs/claude-code/memory">Claude Code Docs: How Claude remembers your project</a></li>
<li><strong><code>AGENTS.md</code></strong> (tool-neutral convention): <a href="https://agents.md/">agents.md</a></li>
<li><strong>Next.js generating <code>AGENTS.md</code>/<code>CLAUDE.md</code> for its own framework rules</strong>: <a href="https://nextjs.org/docs/app/guides/ai-agents">Next.js Docs: Set up your project for AI coding agents</a></li>
<li><strong>Claude Code Skills</strong>: <a href="https://code.claude.com/docs/en/skills">code.claude.com/docs/en/skills</a></li>
<li><strong>Claude Code Plugins</strong>: <a href="https://code.claude.com/docs/en/plugins">overview</a> and <a href="https://code.claude.com/docs/en/discover-plugins">installation scopes</a>.</li>
<li><strong>Areas layout and helper behaviour</strong>: the published skill above (<a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/SKILL.md"><code>SKILL.md</code></a> and <a href="https://insightsurge-dev.web.app/templates/agentic/handoff-skill/scripts/handoff.sh"><code>handoff.sh</code></a>), run on 2026-09-28.</li>
<li><strong>Gitignored working notes</strong>: <a href="https://git-scm.com/docs/gitignore">Git: gitignore</a>.</li>
<li><strong>R package records and build exclusions</strong>: <a href="https://r-pkgs.org/other-markdown.html#sec-news">R Packages: NEWS.md</a> and <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Building-package-tarballs">Writing R Extensions: Building package tarballs</a>.</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-26:</strong> Established repository-scoped handoffs across two repositories, configuring <code>CLAUDE.md</code> to reference sibling handoffs for cross-repo context. Copied the handoff skill into the second repository.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Linked every template file and showed it on the page.</li>
<li><strong>2026-09-28:</strong> Reworked handoffs around long-lived areas, with an optional overview, dated status checks and <code>06-delivered.md</code>. Clarified what belongs in git, the shared skill copies, and <code>status</code> / <code>check</code>. The downloadable skill is now the current version (areas, <code>init</code> / <code>status</code> / <code>check</code>).</li>
<li><strong>2026-10-03:</strong> Added an inbox for notes between related repositories (<code>external-notes.md</code>, with statuses from <code>new</code> to <code>done</code> or <code>rejected</code>), a migration for older notes, and a session hook that announces new entries and blocks a merge while an entry has waited untriaged for a day. The skill now also asks you to keep the tracker in step: close issues through a PR, with a comment, or as not planned. An optional update step now asks whether delegated work showed a new kind of mistake, for projects that keep standing rules for delegated AI work.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 14 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/repo-hygiene-files/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 13</span><span class="site-related-card__title">Repo hygiene files</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/companion-code/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 15</span><span class="site-related-card__title">Companion code: show it, link it, test it</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/two-model-workflow/index.html" class="site-link-row" title="Structure dual-model AI workflows with clear task ownership, written briefs, and human verification to maintain engineering rigor."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">One owner, two models: delegating to a second AI and verifying it</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/building-this-blog/index.html" class="site-link-row" title="How we transformed a 14-part topic site into a Quarto engineering blog and portfolio using URL aliases, living-document conventions, and multi-model agentic collaboration."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Building this blog: from numbered topics to a living Quarto publication</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/index.html" class="site-link-row" title="The mascot package is now on CRAN: add mood-driven characters to Shiny apps and Quarto pages, with visible status text, speech bubbles, click menus and reduced-motion support."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">mascot is on CRAN: live, mood-driven mascots for Shiny and Quarto</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Agentic AI</category>
  <category>R packages</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/handoffs-agentic-context/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Identity &amp; environment isolation</title>
  <link>https://insightsurge-dev.web.app/posts/identity-isolation/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Many of us run more than one “self” on the same machine: a day job, a side project, open-source work, a client engagement. Each has its own:</p>
<ul>
<li><strong>git author</strong>: the name and email stamped on every commit;</li>
<li><strong>git transport credentials</strong>: the SSH key or token used to push;</li>
<li><strong>GitHub CLI/API login</strong>: what <code>gh</code>, or <code>gh::gh()</code> in R, acts as;</li>
<li><strong>cloud login</strong>: the account <code>gcloud</code>, <code>firebase</code> or <code>az</code> deploys with;</li>
<li><strong>AI tool account</strong>: which subscription, and which organisation’s data policy, your prompts fall under;</li>
<li><strong>package registry</strong>: where <code>npm install</code> or <code>install.packages()</code> downloads from.</li>
</ul>
<p>Get any one of these wrong and you can commit company work under a personal email, push to the wrong organisation, deploy into someone else’s cloud project, or send code to an AI tool under the wrong data agreement. None of these fail loudly.</p>
<p>In GxP terms this is <strong>ALCOA+ “Attributable”</strong>: every record, including a commit, should show unambiguously who created it. Identity isolation is how you make that true by construction, not by remembering.</p>
<blockquote class="blockquote">
<p><strong>Principle:</strong> scope identity to a <em>folder</em>, not to a <em>machine</em>, and have every session prove its identity before it does anything outward-facing.</p>
</blockquote>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>The pattern below is common in JavaScript and TypeScript shops. All of a project’s repos live under one workspace folder, and every identity is pinned to that folder.</p>
<section id="folder-scoped-git-identity-with-includeif" class="level3">
<h3 class="anchored" data-anchor-id="folder-scoped-git-identity-with-includeif">1. Folder-scoped git identity with <code>includeIf</code></h3>
<p>Your global <code>~/.gitconfig</code> keeps your everyday identity. One extra block loads a second config file, but only for repos under the workspace folder:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode ini code-with-copy"><code class="sourceCode ini"><span id="cb1-1"><span class="co" style="color: #5E5E5E;"># ~/.gitconfig (the only global edit)</span></span>
<span id="cb1-2"><span class="kw" style="color: #003B4F;
font-weight: bold;">[includeIf "gitdir/i:~/Projects/Acme/"]</span></span>
<span id="cb1-3"><span class="dt" style="color: #AD0000;">    path </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> ~/Projects/Acme/.gitconfig-acme</span></span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode ini code-with-copy"><code class="sourceCode ini"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># ~/Projects/Acme/.gitconfig-acme</span></span>
<span id="cb2-2"><span class="kw" style="color: #003B4F;
font-weight: bold;">[user]</span></span>
<span id="cb2-3"><span class="dt" style="color: #AD0000;">    name </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> Your Name</span></span>
<span id="cb2-4"><span class="dt" style="color: #AD0000;">    email </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> 12345+acme-bot@users.noreply.github.com   # GitHub noreply address</span></span>
<span id="cb2-5"><span class="dt" style="color: #AD0000;">    signingkey </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> ~/.ssh/id_ed25519_acme.pub</span></span>
<span id="cb2-6"><span class="kw" style="color: #003B4F;
font-weight: bold;">[core]</span></span>
<span id="cb2-7"><span class="dt" style="color: #AD0000;">    sshCommand </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> ssh -i ~/.ssh/id_ed25519_acme -o IdentitiesOnly=yes</span></span>
<span id="cb2-8"><span class="kw" style="color: #003B4F;
font-weight: bold;">[gpg]</span></span>
<span id="cb2-9"><span class="dt" style="color: #AD0000;">    format </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> ssh</span></span>
<span id="cb2-10"><span class="kw" style="color: #003B4F;
font-weight: bold;">[commit]</span></span>
<span id="cb2-11"><span class="dt" style="color: #AD0000;">    gpgsign </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">true</span></span>
<span id="cb2-12"><span class="kw" style="color: #003B4F;
font-weight: bold;">[credential]</span></span>
<span id="cb2-13"><span class="dt" style="color: #AD0000;">    helper </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;">                                  # blank: never reuse another account's token</span></span>
<span id="cb2-14"><span class="kw" style="color: #003B4F;
font-weight: bold;">[url "git@github.com:"]</span></span>
<span id="cb2-15"><span class="dt" style="color: #AD0000;">    insteadOf </span><span class="ot" style="color: #003B4F;">=</span><span class="st" style="color: #20794D;"> https://github.com/           # always use SSH, so always this key</span></span></code></pre></div></div>
<p>What each line buys you:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Setting</th>
<th>Protects against</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>gitdir/i:</code> with a trailing <code>/</code></td>
<td>Case differences on macOS; the <code>/</code> means “everything under this folder”</td>
</tr>
<tr class="even">
<td>noreply email</td>
<td>Exposing a personal inbox; commits still link to the right account</td>
</tr>
<tr class="odd">
<td><code>IdentitiesOnly=yes</code> + a dedicated key</td>
<td>SSH offering your <em>other</em> key first and pushing as the wrong user</td>
</tr>
<tr class="even">
<td>blank <code>credential.helper</code></td>
<td>An HTTPS token saved in the OS keychain for another account being reused</td>
</tr>
<tr class="odd">
<td><code>insteadOf</code></td>
<td>An <code>https://</code> URL quietly bypassing the SSH key</td>
</tr>
<tr class="even">
<td>SSH commit signing</td>
<td>Anyone setting <code>user.email</code> to your address. GitHub shows <strong>Verified</strong> only for your key</td>
</tr>
</tbody>
</table>
</div>
<p>Check it from inside a repo:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="fu" style="color: #4758AB;">git</span> config <span class="at" style="color: #657422;">--show-origin</span> user.email      <span class="co" style="color: #5E5E5E;"># shows which file the value came from</span></span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;">ssh</span> <span class="at" style="color: #657422;">-T</span> git@github.com                    <span class="co" style="color: #5E5E5E;"># greets the account that owns the key</span></span></code></pre></div></div>
<section id="hardening-dedicated-keys-with-a-passphrase" class="level4">
<h4 class="anchored" data-anchor-id="hardening-dedicated-keys-with-a-passphrase">Hardening dedicated keys with a passphrase</h4>
<p>Never leave private SSH keys unencrypted on disk. Add a passphrase to your dedicated key and delegate passphrase caching to the macOS keychain:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="fu" style="color: #4758AB;">ssh-keygen</span> <span class="at" style="color: #657422;">-p</span> <span class="at" style="color: #657422;">-f</span> ~/.ssh/id_ed25519_acme</span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;">ssh-add</span> <span class="at" style="color: #657422;">--apple-use-keychain</span> ~/.ssh/id_ed25519_acme</span></code></pre></div></div>
<p>An empty passphrase is the same as none; it provides no protection if a local file is read or exfiltrated. Once the key is loaded into the agent, SSH commit signing and git operations continue working without interactive passphrase prompts on every commit.</p>
</section>
</section>
<section id="cli-logins-in-the-workspace-not-in-your-home-folder" class="level3">
<h3 class="anchored" data-anchor-id="cli-logins-in-the-workspace-not-in-your-home-folder">2. CLI logins in the workspace, not in your home folder</h3>
<p>Most CLIs store their login in a config folder that an environment variable can override. Point these variables inside the workspace, and the logins can’t collide with your other accounts:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb5-1"><span class="bu" style="color: null;">export</span> <span class="va" style="color: #111111;">GH_CONFIG_DIR</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$WS</span><span class="st" style="color: #20794D;">/.config/gh"</span>            <span class="co" style="color: #5E5E5E;"># GitHub CLI</span></span>
<span id="cb5-2"><span class="bu" style="color: null;">export</span> <span class="va" style="color: #111111;">CLOUDSDK_CONFIG</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$WS</span><span class="st" style="color: #20794D;">/.config/gcloud"</span>      <span class="co" style="color: #5E5E5E;"># gcloud</span></span>
<span id="cb5-3"><span class="bu" style="color: null;">export</span> <span class="va" style="color: #111111;">XDG_CONFIG_HOME</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$WS</span><span class="st" style="color: #20794D;">/.config"</span>             <span class="co" style="color: #5E5E5E;"># many other CLIs (firebase, etc.)</span></span></code></pre></div></div>
<p>Put these in an <code>activate.sh</code> that you <code>source</code> when you start work, the way you’d activate a Python virtual environment.</p>
</section>
<section id="guards-print-every-identity-and-refuse-on-a-mismatch" class="level3">
<h3 class="anchored" data-anchor-id="guards-print-every-identity-and-refuse-on-a-mismatch">3. Guards: print every identity and refuse on a mismatch</h3>
<p>The activation script ends by printing each identity, and <strong>aborts and rolls back</strong> if any of them matches a pattern you never want active here, such as your employer’s domain. The patterns live in a local, never-committed file, so the script itself stays generic.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb6-1"><span class="va" style="color: #111111;">login</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$(</span><span class="ex" style="color: null;">gh</span> api user <span class="at" style="color: #657422;">--jq</span> .login<span class="va" style="color: #111111;">)</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb6-2"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> <span class="bu" style="color: null;">printf</span> <span class="st" style="color: #20794D;">'%s'</span> <span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$login</span><span class="st" style="color: #20794D;">"</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">grep</span> <span class="at" style="color: #657422;">-Eiq</span> <span class="st" style="color: #20794D;">"</span><span class="va" style="color: #111111;">$BLOCKED</span><span class="st" style="color: #20794D;">"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">then</span></span>
<span id="cb6-3">  <span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"✗ gh is logged in as </span><span class="va" style="color: #111111;">$login</span><span class="st" style="color: #20794D;">, aborting"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="ex" style="color: null;">deactivate</span><span class="kw" style="color: #003B4F;
font-weight: bold;">;</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> <span class="dv" style="color: #AD0000;">1</span></span>
<span id="cb6-4"><span class="cf" style="color: #003B4F;
font-weight: bold;">fi</span></span>
<span id="cb6-5"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"✓ gh: </span><span class="va" style="color: #111111;">$login</span><span class="st" style="color: #20794D;">"</span></span></code></pre></div></div>
</section>
<section id="no-global-installs-pin-the-registry" class="level3">
<h3 class="anchored" data-anchor-id="no-global-installs-pin-the-registry">4. No global installs; pin the registry</h3>
<p>Tools go into the project as <code>devDependencies</code>, and a project <code>.npmrc</code> pins <code>registry=https://registry.npmjs.org/</code>. Nothing from another context (a corporate mirror in <code>~/.npmrc</code>, or a globally installed CLI at a different version) can leak in.</p>
</section>
<section id="gui-apps-dont-read-your-shell" class="level3">
<h3 class="anchored" data-anchor-id="gui-apps-dont-read-your-shell">5. GUI apps don’t read your shell</h3>
<p>Desktop apps and IDE extensions usually <strong>don’t</strong> source <code>activate.sh</code>. For those, use the tool’s own project-level settings file (for example a local, gitignored settings file that sets the same environment variables). Before any GitHub action, check which account is active again: <code>gh api user --jq .login</code>.</p>
</section>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>R already has most of these ideas, spread across a few tools you probably use.</p>
<section id="projects-are-the-folder-scope" class="level3">
<h3 class="anchored" data-anchor-id="projects-are-the-folder-scope">Projects are the “folder scope”</h3>
<p>An RStudio project (<code>.Rproj</code>) or a Positron folder sets the <strong>working directory</strong> when it opens. R then reads a <code>.Renviron</code> from that directory at startup, so it works as a per-project set of environment variables:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb7-1"><span class="co" style="color: #5E5E5E;"># my-project/.Renviron (gitignored)</span></span>
<span id="cb7-2"><span class="va" style="color: #111111;">GITHUB_PAT_GITHUB_COM</span><span class="op" style="color: #5E5E5E;">=</span>ghp_...          <span class="co" style="color: #5E5E5E;"># the token for THIS project's account</span></span>
<span id="cb7-3"><span class="va" style="color: #111111;">R_CONFIG_ACTIVE</span><span class="op" style="color: #5E5E5E;">=</span>dev</span></code></pre></div></div>
<div class="callout callout-style-default callout-warning callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Warning</span>Gotcha: a project <code>.Renviron</code> <em>replaces</em> your personal one
</div>
</div>
<div class="callout-body-container callout-body">
<p>R reads the <strong>first</strong> <code>.Renviron</code> it finds: the one in the working directory, <em>otherwise</em> <code>~/.Renviron</code>. It does not merge them. We checked this with two files: the variables from <code>~/.Renviron</code> disappeared once a project <code>.Renviron</code> existed. If your project needs something from your personal file, copy it across deliberately.</p>
</div>
</div>
<p><code>usethis</code> writes the right file for the right scope:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb8-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">edit_r_environ</span>(<span class="at" style="color: #657422;">scope =</span> <span class="st" style="color: #20794D;">"project"</span>)   <span class="co" style="color: #5E5E5E;"># opens my-project/.Renviron</span></span>
<span id="cb8-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">edit_r_environ</span>(<span class="at" style="color: #657422;">scope =</span> <span class="st" style="color: #20794D;">"user"</span>)      <span class="co" style="color: #5E5E5E;"># opens ~/.Renviron</span></span></code></pre></div></div>
</section>
<section id="which-github-account-does-r-act-as" class="level3">
<h3 class="anchored" data-anchor-id="which-github-account-does-r-act-as">Which GitHub account does R act as?</h3>
<p><code>gh::gh()</code> and <code>usethis</code> find a GitHub token in this order. We checked this with <code>gh</code> 1.4.1:</p>
<ol type="1">
<li><code>GITHUB_PAT_GITHUB_COM</code> (host-specific, the most precise)</li>
<li><code>GITHUB_PAT</code></li>
<li>the <strong>git credential helper</strong>, via <code>gitcreds</code></li>
</ol>
<p>A host-specific PAT in the project <code>.Renviron</code> therefore beats whatever token is saved in your keychain. It’s the R equivalent of <code>GH_CONFIG_DIR</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">gh<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">gh_whoami</span>()          <span class="co" style="color: #5E5E5E;"># which account R is acting as, and the token's scopes</span></span></code></pre></div></div>
</section>
<section id="git-identity-per-repo-with-usethis" class="level3">
<h3 class="anchored" data-anchor-id="git-identity-per-repo-with-usethis">Git identity per repo with <code>usethis</code></h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb10-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_git_config</span>(</span>
<span id="cb10-2">  <span class="at" style="color: #657422;">scope =</span> <span class="st" style="color: #20794D;">"project"</span>,</span>
<span id="cb10-3">  <span class="at" style="color: #657422;">user.name  =</span> <span class="st" style="color: #20794D;">"Your Name"</span>,</span>
<span id="cb10-4">  <span class="at" style="color: #657422;">user.email =</span> <span class="st" style="color: #20794D;">"12345+acme-bot@users.noreply.github.com"</span></span>
<span id="cb10-5">)</span></code></pre></div></div>
<p>This writes to <em>that repo’s</em> <code>.git/config</code>, so it’s per repo, not per folder. It’s fine for one repo, but it’s easy to forget on the next clone. The <code>includeIf</code> block covers every repo under the workspace automatically, including commits made from the <strong>RStudio or Positron Git pane</strong>, because both IDEs call your system <code>git</code>.</p>
</section>
<section id="the-situation-report-is-your-guard" class="level3">
<h3 class="anchored" data-anchor-id="the-situation-report-is-your-guard">The situation report is your guard</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">git_sitrep</span>()    <span class="co" style="color: #5E5E5E;"># git user, signing, default branch, GitHub user and token</span></span></code></pre></div></div>
<p><code>git_sitrep()</code> prints the same identities an <code>activate.sh</code> checks. <a href="https://insightsurge-dev.web.app/posts/identity-isolation/scripts/identity-check.R">scripts/identity-check.R</a> wraps it in a hard stop you can put at the top of a deployment script (save the companion file in your project as <code>R/identity-check.R</code>):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;">source</span>(<span class="st" style="color: #20794D;">"R/identity-check.R"</span>)</span>
<span id="cb12-2"><span class="fu" style="color: #4758AB;">assert_identity</span>(</span>
<span id="cb12-3">  <span class="at" style="color: #657422;">expected_email_pattern =</span> <span class="st" style="color: #20794D;">"noreply</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.github</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.com$"</span>,</span>
<span id="cb12-4">  <span class="at" style="color: #657422;">blocked_pattern        =</span> <span class="st" style="color: #20794D;">"@example-employer</span><span class="sc" style="color: #5E5E5E;">\\</span><span class="st" style="color: #20794D;">.com$"</span></span>
<span id="cb12-5">)</span></code></pre></div></div>
</section>
<section id="renv-isolates-packages-not-people" class="level3">
<h3 class="anchored" data-anchor-id="renv-isolates-packages-not-people"><code>renv</code> isolates packages, not people</h3>
<p><code>renv</code> gives each project its own library and a lockfile, just as <code>node_modules</code> and <code>package-lock.json</code> do. That’s <strong>dependency</strong> isolation, a separate question from <strong>identity</strong> isolation, and you need both. <code>renv.lock</code> also records the R version, much as <code>.nvmrc</code> pins the Node version.</p>
</section>
</section>
<section id="side-by-side" class="level2">
<h2 class="anchored" data-anchor-id="side-by-side">Side by side</h2>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Concern</th>
<th>Web-repo way</th>
<th>R way</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Folder scope</td>
<td><code>includeIf "gitdir/i:…"</code></td>
<td>RStudio/Positron project + project <code>.Renviron</code></td>
</tr>
<tr class="even">
<td>Git author</td>
<td>workspace <code>.gitconfig-*</code></td>
<td><code>usethis::use_git_config(scope = "project")</code></td>
</tr>
<tr class="odd">
<td>GitHub account for tools</td>
<td><code>GH_CONFIG_DIR</code></td>
<td><code>GITHUB_PAT_GITHUB_COM</code> in project <code>.Renviron</code></td>
</tr>
<tr class="even">
<td>Verify before acting</td>
<td><code>activate.sh</code> guards, <code>gh api user</code></td>
<td><code>usethis::git_sitrep()</code>, <code>gh::gh_whoami()</code></td>
</tr>
<tr class="odd">
<td>Commit signing</td>
<td>SSH signing (<code>gpg.format=ssh</code>)</td>
<td>Same git setting; the IDE Git pane uses it</td>
</tr>
<tr class="even">
<td>Dependencies</td>
<td><code>devDependencies</code>, <code>package-lock.json</code>, <code>.nvmrc</code></td>
<td><code>renv</code> library, <code>renv.lock</code></td>
</tr>
<tr class="odd">
<td>Registry</td>
<td>project <code>.npmrc</code></td>
<td><code>options(repos = …)</code> in project <code>.Rprofile</code>, or via <code>renv</code></td>
</tr>
</tbody>
</table>
</div>
</section>
<section id="pitfalls-we-hit" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-we-hit">Pitfalls we hit</h2>
<ul>
<li><strong><code>includeIf</code> only applies once the folder is a git repo.</strong> Before <code>git init</code>, <code>git config user.email</code> still shows your global identity. Check again straight after init.</li>
<li><strong>Desktop apps ignore your shell.</strong> An IDE or desktop agent launched from the Dock never sources <code>activate.sh</code>. Configure the same variables in the tool’s project settings.</li>
<li><strong>A project <code>.Renviron</code> hides <code>~/.Renviron</code></strong> (see the callout above).</li>
<li><strong>Tools can refuse your runtime.</strong> One CLI refused to install on a newer Node than it supports. Pin the runtime per project (<code>.nvmrc</code>, or <code>renv.lock</code>’s R version) instead of upgrading or downgrading the whole machine.</li>
<li><strong>The blocked-pattern file is sensitive.</strong> It names the identities you’re guarding against. Keep it local and never commit it.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/identity-isolation/scripts/identity-check.R">View <code>identity-check.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/identity-isolation/scripts/identity-check.R" download="identity-check.R">Download</a></p>
<p>Defines <code>assert_identity()</code> to stop execution if git <code>user.email</code> or the active GitHub account does not match expected patterns or matches a blocked identity. Uses base R and optionally calls <code>{gh}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>identity-check.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="co" style="color: #5E5E5E;"># Identity guard for R projects.</span></span>
<span id="cb13-2"><span class="co" style="color: #5E5E5E;"># Stops with an error if the git author or GitHub account in use is not the</span></span>
<span id="cb13-3"><span class="co" style="color: #5E5E5E;"># one this project expects. Source it at the top of any script that commits,</span></span>
<span id="cb13-4"><span class="co" style="color: #5E5E5E;"># pushes, publishes or deploys.</span></span>
<span id="cb13-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb13-6"><span class="co" style="color: #5E5E5E;"># nolint start: commented_code_linter. Usage example.</span></span>
<span id="cb13-7"><span class="co" style="color: #5E5E5E;">#   source("R/identity-check.R")</span></span>
<span id="cb13-8"><span class="co" style="color: #5E5E5E;">#   assert_identity(</span></span>
<span id="cb13-9"><span class="co" style="color: #5E5E5E;">#     expected_email_pattern = "noreply\\.github\\.com$",</span></span>
<span id="cb13-10"><span class="co" style="color: #5E5E5E;">#     blocked_pattern        = "@example-employer\\.com$",</span></span>
<span id="cb13-11"><span class="co" style="color: #5E5E5E;">#     expected_github_login  = "my-company-bot"      # optional</span></span>
<span id="cb13-12"><span class="co" style="color: #5E5E5E;">#   )</span></span>
<span id="cb13-13"><span class="co" style="color: #5E5E5E;"># nolint end</span></span>
<span id="cb13-14"></span>
<span id="cb13-15">git_value <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(key) {</span>
<span id="cb13-16">  out <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">suppressWarnings</span>(</span>
<span id="cb13-17">    <span class="fu" style="color: #4758AB;">system2</span>(<span class="st" style="color: #20794D;">"git"</span>, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"config"</span>, <span class="st" style="color: #20794D;">"--get"</span>, key), <span class="at" style="color: #657422;">stdout =</span> <span class="cn" style="color: #8f5902;">TRUE</span>, <span class="at" style="color: #657422;">stderr =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb13-18">  )</span>
<span id="cb13-19">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(out) <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>) <span class="cn" style="color: #8f5902;">NA_character_</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> out[[<span class="dv" style="color: #AD0000;">1</span>]]</span>
<span id="cb13-20">}</span>
<span id="cb13-21"></span>
<span id="cb13-22">github_login <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb13-23">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">requireNamespace</span>(<span class="st" style="color: #20794D;">"gh"</span>, <span class="at" style="color: #657422;">quietly =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)) {</span>
<span id="cb13-24">    <span class="fu" style="color: #4758AB;">return</span>(<span class="cn" style="color: #8f5902;">NA_character_</span>)</span>
<span id="cb13-25">  }</span>
<span id="cb13-26">  <span class="co" style="color: #5E5E5E;"># gh_whoami() returns NULL (with a message) when no token is found.</span></span>
<span id="cb13-27">  who <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tryCatch</span>(<span class="fu" style="color: #4758AB;">suppressMessages</span>(gh<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">gh_whoami</span>()), <span class="at" style="color: #657422;">error =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(e) <span class="cn" style="color: #8f5902;">NULL</span>)</span>
<span id="cb13-28">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(who<span class="sc" style="color: #5E5E5E;">$</span>login)) <span class="cn" style="color: #8f5902;">NA_character_</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> who<span class="sc" style="color: #5E5E5E;">$</span>login</span>
<span id="cb13-29">}</span>
<span id="cb13-30"></span>
<span id="cb13-31">assert_identity <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb13-32">  expected_email_pattern,</span>
<span id="cb13-33">  <span class="at" style="color: #657422;">blocked_pattern =</span> <span class="cn" style="color: #8f5902;">NULL</span>,</span>
<span id="cb13-34">  <span class="at" style="color: #657422;">expected_github_login =</span> <span class="cn" style="color: #8f5902;">NULL</span></span>
<span id="cb13-35">) {</span>
<span id="cb13-36">  email <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">git_value</span>(<span class="st" style="color: #20794D;">"user.email"</span>)</span>
<span id="cb13-37">  login <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(expected_github_login)) <span class="cn" style="color: #8f5902;">NA_character_</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="fu" style="color: #4758AB;">github_login</span>()</span>
<span id="cb13-38">  checked <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(email, login)</span>
<span id="cb13-39">  checked <span class="ot" style="color: #003B4F;">&lt;-</span> checked[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(checked)]</span>
<span id="cb13-40"></span>
<span id="cb13-41">  problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">character</span>()</span>
<span id="cb13-42">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.na</span>(email)) {</span>
<span id="cb13-43">    problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(problems, <span class="st" style="color: #20794D;">"git user.email is not set"</span>)</span>
<span id="cb13-44">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">grepl</span>(expected_email_pattern, email)) {</span>
<span id="cb13-45">    problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb13-46">      problems,</span>
<span id="cb13-47">      <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb13-48">        <span class="st" style="color: #20794D;">"git user.email '%s' does not match '%s'"</span>,</span>
<span id="cb13-49">        email,</span>
<span id="cb13-50">        expected_email_pattern</span>
<span id="cb13-51">      )</span>
<span id="cb13-52">    )</span>
<span id="cb13-53">  }</span>
<span id="cb13-54">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (</span>
<span id="cb13-55">    <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(blocked_pattern) <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span></span>
<span id="cb13-56">      <span class="fu" style="color: #4758AB;">any</span>(<span class="fu" style="color: #4758AB;">grepl</span>(blocked_pattern, checked, <span class="at" style="color: #657422;">ignore.case =</span> <span class="cn" style="color: #8f5902;">TRUE</span>))</span>
<span id="cb13-57">  ) {</span>
<span id="cb13-58">    problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(problems, <span class="st" style="color: #20794D;">"an active identity matches the blocked pattern"</span>)</span>
<span id="cb13-59">  }</span>
<span id="cb13-60">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (</span>
<span id="cb13-61">    <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.null</span>(expected_github_login) <span class="sc" style="color: #5E5E5E;">&amp;&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">identical</span>(login, expected_github_login)</span>
<span id="cb13-62">  ) {</span>
<span id="cb13-63">    problems <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb13-64">      problems,</span>
<span id="cb13-65">      <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb13-66">        <span class="st" style="color: #20794D;">"GitHub login is '%s', expected '%s'"</span>,</span>
<span id="cb13-67">        login,</span>
<span id="cb13-68">        expected_github_login</span>
<span id="cb13-69">      )</span>
<span id="cb13-70">    )</span>
<span id="cb13-71">  }</span>
<span id="cb13-72"></span>
<span id="cb13-73">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">length</span>(problems) <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span>) {</span>
<span id="cb13-74">    <span class="fu" style="color: #4758AB;">stop</span>(</span>
<span id="cb13-75">      <span class="st" style="color: #20794D;">"Identity check failed:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">- "</span>,</span>
<span id="cb13-76">      <span class="fu" style="color: #4758AB;">paste</span>(problems, <span class="at" style="color: #657422;">collapse =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">- "</span>),</span>
<span id="cb13-77">      <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb13-78">    )</span>
<span id="cb13-79">  }</span>
<span id="cb13-80">  <span class="fu" style="color: #4758AB;">message</span>(</span>
<span id="cb13-81">    <span class="st" style="color: #20794D;">"✓ git: "</span>,</span>
<span id="cb13-82">    email,</span>
<span id="cb13-83">    <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(login)) <span class="fu" style="color: #4758AB;">paste0</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">✓ GitHub: "</span>, login) <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="st" style="color: #20794D;">""</span></span>
<span id="cb13-84">  )</span>
<span id="cb13-85">  <span class="fu" style="color: #4758AB;">invisible</span>(<span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb13-86">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Git and SSH</strong></p>
<ul>
<li><strong>git config (<code>includeIf</code>, <code>credential.helper</code>, <code>url.insteadOf</code>, <code>gpg.format</code>)</strong>: <a href="https://git-scm.com/docs/git-config">git-scm.com/docs/git-config</a></li>
<li><strong><code>ssh-add --apple-use-keychain</code></strong>: <a href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent">GitHub Docs: Generating a new SSH key and adding it to the ssh-agent</a></li>
</ul>
<p><strong>CLIs and their config-directory variables</strong></p>
<ul>
<li><strong>GitHub CLI (<code>gh</code>), <code>GH_CONFIG_DIR</code></strong>: <a href="https://cli.github.com/manual/gh_help_environment">cli.github.com/manual</a></li>
<li><strong><code>gh api</code></strong>: <a href="https://cli.github.com/manual/gh_api">cli.github.com/manual/gh_api</a></li>
<li><strong>gcloud CLI, <code>CLOUDSDK_CONFIG</code></strong>: <a href="https://docs.cloud.google.com/sdk/docs/configurations">Google Cloud SDK: Configurations</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>gh</strong> (R client for the GitHub API; token lookup order): <a href="https://gh.r-lib.org/">gh.r-lib.org</a></li>
<li><strong>usethis</strong>: <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
<li><strong>renv</strong>: <a href="https://rstudio.github.io/renv/">rstudio.github.io/renv</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-26:</strong> Hardened the dedicated SSH key by adding a passphrase via <code>ssh-keygen -p</code> and storing it in the macOS keychain agent using <code>ssh-add --apple-use-keychain</code>. Verified that signed commits continue working automatically once the key is resident in the agent.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 1 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/git-workflow/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 2</span><span class="site-related-card__title">Git workflow: branches, squash-only merges, signed commits</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html" class="site-link-row" title="Separate configuration names in version control from secrets stored in vaults and environment variables."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Secrets management</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/index.html" class="site-link-row" title="Use OpenID Connect and Google Cloud Workload Identity Federation to authenticate CI pipelines without long-lived JSON keys."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Keyless deploys: let CI prove who it is (OIDC)</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>Git</category>
  <category>Security</category>
  <guid>https://insightsurge-dev.web.app/posts/identity-isolation/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Issue forms, PR templates, labels &amp; milestones</title>
  <link>https://insightsurge-dev.web.app/posts/issue-forms-pr-templates/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>A typical bug report on an internal R package says “km_plot is broken”. You then spend three messages collecting the R version, the package version, the data shape and what “broken” means. Feature requests arrive with no acceptance criteria, so nobody can say when they’re done. PRs arrive with no tests, no <code>NEWS.md</code> bullet and undocumented arguments.</p>
<p>GitHub can ask for all of this up front. The same structure also gives you <strong>traceability</strong>, which GxP work needs anyway: requirement → issue → PR → test → release.</p>
</section>
<section id="issue-forms-yaml-vs-issue-templates-markdown" class="level2">
<h2 class="anchored" data-anchor-id="issue-forms-yaml-vs-issue-templates-markdown">Issue forms (YAML) vs issue templates (Markdown)</h2>
<p>GitHub has two kinds of issue template in <code>.github/ISSUE_TEMPLATE/</code>:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th></th>
<th>Markdown template (<code>*.md</code>)</th>
<th>Issue form (<code>*.yml</code>)</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>What the reporter sees</td>
<td>A pre-filled text box they can overwrite</td>
<td>Real form fields: text areas, inputs, dropdowns, checkboxes</td>
</tr>
<tr class="even">
<td>Required fields</td>
<td>No; headings get deleted</td>
<td><strong>Yes</strong>, with <code>validations: required: true</code></td>
</tr>
<tr class="odd">
<td>Code/log fields</td>
<td>Reporter must add backticks</td>
<td><code>render: r</code> formats the field as a code block automatically</td>
</tr>
<tr class="even">
<td>Auto labels</td>
<td>Yes</td>
<td>Yes</td>
</tr>
</tbody>
</table>
</div>
<p><code>usethis::use_tidy_github()</code> creates the <strong>Markdown</strong> kind (<code>issue_template.md</code>). It’s a fine start, but forms are the upgrade: required fields can’t be skipped.</p>
<p>GitHub’s documentation still labels issue forms as <em>public preview</em>. After adding them, open <code>…/issues/new/choose</code> in your repo to check that they render.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>Three small files:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="co" style="color: #5E5E5E;"># .github/ISSUE_TEMPLATE/config.yml: force people to pick a form</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">blank_issues_enabled</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">false</span></span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># .github/ISSUE_TEMPLATE/feature.yml (abridged)</span></span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Feature request</span></span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;">description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> A new page, section, capability or standard</span></span>
<span id="cb2-4"><span class="fu" style="color: #4758AB;">labels</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="st" style="color: #20794D;">"type: feature"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb2-5"><span class="fu" style="color: #4758AB;">body</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-6"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> textarea</span></span>
<span id="cb2-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> problem</span></span>
<span id="cb2-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Problem or goal </span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb2-9"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">validations</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">required</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb2-10"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> textarea</span></span>
<span id="cb2-11"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> acceptance</span></span>
<span id="cb2-12"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-13"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Acceptance criteria</span></span>
<span id="cb2-14"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Testable conditions that mean this is done.</span></span>
<span id="cb2-15"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">validations</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">required</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span></code></pre></div></div>
<p>Add a <code>.github/PULL_REQUEST_TEMPLATE.md</code> with <em>What / Why / Closes #… / Checklist</em>, plus a <strong>label taxonomy</strong> and <strong>milestones with exit criteria</strong>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;">gh</span> label create <span class="st" style="color: #20794D;">"type: bug"</span>     <span class="at" style="color: #657422;">--color</span> d73a4a <span class="at" style="color: #657422;">--description</span> <span class="st" style="color: #20794D;">"Something is broken"</span></span>
<span id="cb3-2"><span class="ex" style="color: null;">gh</span> label create <span class="st" style="color: #20794D;">"area: ci"</span>      <span class="at" style="color: #657422;">--color</span> 1d76db <span class="at" style="color: #657422;">--description</span> <span class="st" style="color: #20794D;">"GitHub Actions, hooks, release tooling"</span></span>
<span id="cb3-3"><span class="ex" style="color: null;">gh</span> api repos/OWNER/REPO/milestones <span class="at" style="color: #657422;">-f</span> title=<span class="st" style="color: #20794D;">"M2 Static site"</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb3-4">  <span class="at" style="color: #657422;">-f</span> description=<span class="st" style="color: #20794D;">"Exit: Lighthouse &gt;= 95; 0 broken links; form returns 400 on invalid input"</span></span></code></pre></div></div>
<p>Prefixed labels (<code>type: …</code>, <code>area: …</code>) group nicely in GitHub’s label picker and in filters (<code>label:"type: bug" label:"area: ci"</code>).</p>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>Drop-in files for R packages and Shiny apps are catalogued in <a href="https://insightsurge-dev.web.app/templates/README.md"><code>templates/README.md</code></a>, including:</p>
<ul>
<li><a href="https://insightsurge-dev.web.app/templates/github/ISSUE_TEMPLATE/config.yml"><code>templates/github/ISSUE_TEMPLATE/config.yml</code></a> to disable blank issues and require forms</li>
<li><a href="https://insightsurge-dev.web.app/templates/github/ISSUE_TEMPLATE/bug.yml"><code>templates/github/ISSUE_TEMPLATE/bug.yml</code></a> for reproducible bug reports</li>
<li><a href="https://insightsurge-dev.web.app/templates/github/ISSUE_TEMPLATE/feature.yml"><code>templates/github/ISSUE_TEMPLATE/feature.yml</code></a> for feature requests with acceptance criteria</li>
<li><a href="https://insightsurge-dev.web.app/templates/github/PULL_REQUEST_TEMPLATE.md"><code>templates/github/PULL_REQUEST_TEMPLATE.md</code></a> for pull request reviews</li>
</ul>
<section id="bug-form-reprex-and-session-info-are-required" class="level3">
<h3 class="anchored" data-anchor-id="bug-form-reprex-and-session-info-are-required">Bug form: reprex and session info are required</h3>
<p>The complete bug form template is provided in <a href="https://insightsurge-dev.web.app/templates/github/ISSUE_TEMPLATE/bug.yml"><code>templates/github/ISSUE_TEMPLATE/bug.yml</code></a>:</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full template: <code>bug.yml</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb4-1"><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Bug report</span></span>
<span id="cb4-2"><span class="fu" style="color: #4758AB;">description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Something in the package or app does not work as documented</span></span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;">labels</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="st" style="color: #20794D;">"type: bug"</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb4-4"><span class="fu" style="color: #4758AB;">body</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-5"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> markdown</span></span>
<span id="cb4-6"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-7"><span class="fu" style="color: #4758AB;">      value</span><span class="kw" style="color: #003B4F;
font-weight: bold;">: </span><span class="ch" style="color: #20794D;">|</span></span>
<span id="cb4-8">        Thanks! Please use **synthetic or public data only**. Never paste real patient or client data.</span>
<span id="cb4-9"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> textarea</span></span>
<span id="cb4-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> what</span></span>
<span id="cb4-11"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-12"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> What happened, and what did you expect?</span></span>
<span id="cb4-13"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">validations</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-14"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">required</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb4-15"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> textarea</span></span>
<span id="cb4-16"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> reprex</span></span>
<span id="cb4-17"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-18"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Reproducible example</span></span>
<span id="cb4-19"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Ideally the output of `reprex::reprex()`. For Shiny apps, the steps to reproduce.</span></span>
<span id="cb4-20"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">render</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> r</span></span>
<span id="cb4-21"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">validations</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-22"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">required</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb4-23"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> textarea</span></span>
<span id="cb4-24"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> session</span></span>
<span id="cb4-25"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-26"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Session info</span></span>
<span id="cb4-27"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Output of `sessioninfo::session_info()` (or `sessionInfo()`).</span></span>
<span id="cb4-28"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">render</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> text</span></span>
<span id="cb4-29"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">validations</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-30"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">required</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span></span>
<span id="cb4-31"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> input</span></span>
<span id="cb4-32"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> where</span></span>
<span id="cb4-33"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-34"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Where did you see it?</span></span>
<span id="cb4-35"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">placeholder</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="st" style="color: #20794D;">"local R 4.5.1 / Posit Connect / shinyapps.io / browser + version"</span></span></code></pre></div></div>
</div>
</div>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb5-1"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> textarea</span></span>
<span id="cb5-2"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> reprex</span></span>
<span id="cb5-3"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-4"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Reproducible example</span></span>
<span id="cb5-5"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Ideally the output of `reprex::reprex()`. For Shiny apps, the steps to reproduce.</span></span>
<span id="cb5-6"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">render</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> r</span></span>
<span id="cb5-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">validations</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">required</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span>
<span id="cb5-8"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> textarea</span></span>
<span id="cb5-9"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> session</span></span>
<span id="cb5-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">attributes</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-11"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">label</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Session info</span></span>
<span id="cb5-12"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">description</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Output of `sessioninfo::session_info()` (or `sessionInfo()`).</span></span>
<span id="cb5-13"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">render</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> text</span></span>
<span id="cb5-14"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">validations</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">{</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">required</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="ch" style="color: #20794D;">true</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">}</span></span></code></pre></div></div>
<p>The form also opens with a reminder to use <strong>synthetic or public data only</strong>. In pharma, that sentence prevents a real incident.</p>
</section>
<section id="feature-form-acceptance-criteria-become-tests" class="level3">
<h3 class="anchored" data-anchor-id="feature-form-acceptance-criteria-become-tests">Feature form: acceptance criteria become tests</h3>
<p>The feature form has a required <strong>Acceptance criteria</strong> field and an optional <strong>Requirement ID</strong> field (for example <code>URS-042</code>). Write the criteria so each one maps to an <code>expect_*()</code> call or a <code>shinytest2</code> snapshot. The issue then traces requirement → test, which is exactly what a validation reviewer asks for.</p>
</section>
<section id="pr-template-the-r-definition-of-done" class="level3">
<h3 class="anchored" data-anchor-id="pr-template-the-r-definition-of-done">PR template: the R definition of done</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb6-1"><span class="ss" style="color: #20794D;">- </span><span class="va" style="color: #111111;">[ ]</span> <span class="in" style="color: #5E5E5E;">`devtools::check()`</span> clean (0 errors, 0 warnings, notes explained)</span>
<span id="cb6-2"><span class="ss" style="color: #20794D;">- </span><span class="va" style="color: #111111;">[ ]</span> Tests added or updated (<span class="in" style="color: #5E5E5E;">`testthat`</span> / <span class="in" style="color: #5E5E5E;">`shinytest2`</span>)</span>
<span id="cb6-3"><span class="ss" style="color: #20794D;">- </span><span class="va" style="color: #111111;">[ ]</span> <span class="in" style="color: #5E5E5E;">`devtools::document()`</span> run; roxygen docs updated</span>
<span id="cb6-4"><span class="ss" style="color: #20794D;">- </span><span class="va" style="color: #111111;">[ ]</span> <span class="in" style="color: #5E5E5E;">`NEWS.md`</span> bullet added (user-facing changes only)</span>
<span id="cb6-5"><span class="ss" style="color: #20794D;">- </span><span class="va" style="color: #111111;">[ ]</span> Code styled (<span class="in" style="color: #5E5E5E;">`air format .`</span> or <span class="in" style="color: #5E5E5E;">`styler`</span>) and <span class="in" style="color: #5E5E5E;">`lintr::lint_package()`</span> clean</span>
<span id="cb6-6"><span class="ss" style="color: #20794D;">- </span><span class="va" style="color: #111111;">[ ]</span> No secrets, tokens or real patient/client data in the diff</span></code></pre></div></div>
</section>
<section id="labels-from-r" class="level3">
<h3 class="anchored" data-anchor-id="labels-from-r">Labels from R</h3>
<p><code>usethis</code> can manage labels without leaving R:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_labels</span>(</span>
<span id="cb7-2">  <span class="at" style="color: #657422;">labels =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"type: bug"</span>, <span class="st" style="color: #20794D;">"type: feature"</span>, <span class="st" style="color: #20794D;">"area: shiny"</span>, <span class="st" style="color: #20794D;">"area: validation"</span>),</span>
<span id="cb7-3">  <span class="at" style="color: #657422;">colours =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"type: bug"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="st" style="color: #20794D;">"d73a4a"</span>, <span class="st" style="color: #20794D;">"type: feature"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="st" style="color: #20794D;">"0e8a16"</span>,</span>
<span id="cb7-4">              <span class="st" style="color: #20794D;">"area: shiny"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="st" style="color: #20794D;">"c5def5"</span>, <span class="st" style="color: #20794D;">"area: validation"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="st" style="color: #20794D;">"5319e7"</span>)</span>
<span id="cb7-5">)</span>
<span id="cb7-6"><span class="co" style="color: #5E5E5E;"># or the tidyverse's standard set:</span></span>
<span id="cb7-7">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_tidy_github_labels</span>()</span></code></pre></div></div>
</section>
<section id="keep-.github-out-of-the-package" class="level3">
<h3 class="anchored" data-anchor-id="keep-.github-out-of-the-package">Keep <code>.github/</code> out of the package</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb8-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_build_ignore</span>(<span class="st" style="color: #20794D;">".github"</span>)   <span class="co" style="color: #5E5E5E;"># adds ^\.github$ to .Rbuildignore</span></span></code></pre></div></div>
</section>
</section>
<section id="milestones-releases-with-exit-criteria" class="level2">
<h2 class="anchored" data-anchor-id="milestones-releases-with-exit-criteria">Milestones: releases with exit criteria</h2>
<p>In an R package, a milestone is naturally a <strong>release</strong> (<code>v1.3.0</code>), and its description is the release’s <strong>exit criteria</strong>: which issues, and what checks must pass. Closing the milestone is part of cutting the release (<a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html">releases &amp; changelogs</a>). For a Shiny app, a milestone can be a deployment (“UAT build for study X”).</p>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Create labels before forms reference them.</strong> GitHub’s docs don’t say what happens with a missing label, so don’t rely on it. Create the taxonomy first and check that a test issue gets its label.</li>
<li><strong><code>blank_issues_enabled: false</code> doesn’t stop maintainers.</strong> Per GitHub’s docs, users with write access or above still see a “Blank issue (Maintainers only)” option. Only Read/Triage users are limited to the forms. Add <code>contact_links</code> to route questions, for example to Discussions.</li>
<li><strong>Checklists aren’t enforcement.</strong> The PR template reminds; CI enforces (<code>R CMD check</code>, <a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html">CI with GitHub Actions</a>). Don’t rely on ticked boxes.</li>
<li><strong>Don’t over-ask.</strong> Every required field is friction. Keep bug forms to what you truly need.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>GitHub</strong></p>
<ul>
<li><strong>Issue forms syntax (documented as public preview)</strong>: <a href="https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-issue-forms">GitHub Docs: Syntax for issue forms</a></li>
<li><strong>Configuring issue templates (<code>blank_issues_enabled</code>; write-access users still see “Blank issue (Maintainers only)”)</strong>: <a href="https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository">GitHub Docs: Configuring issue templates for your repository</a></li>
<li><strong>Milestones</strong>: <a href="https://docs.github.com/en/issues/using-labels-and-milestones-to-track-work/about-milestones">GitHub Docs: About milestones</a></li>
<li><strong>Labels</strong>: <a href="https://docs.github.com/en/issues/using-labels-and-milestones-to-track-work/managing-labels">GitHub Docs: Managing labels</a></li>
<li><strong><code>gh label create</code></strong>: <a href="https://cli.github.com/manual/gh_label_create">cli.github.com/manual/gh_label_create</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>use_tidy_github()</code>, <code>use_github_labels()</code>, <code>use_tidy_github_labels()</code>, <code>use_build_ignore()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
<li><strong>reprex</strong>: <a href="https://reprex.tidyverse.org/">reprex.tidyverse.org</a></li>
<li><strong>sessioninfo</strong>: <a href="https://sessioninfo.r-lib.org/">sessioninfo.r-lib.org</a></li>
<li><strong>shinytest2</strong>: <a href="https://rstudio.github.io/shinytest2/">rstudio.github.io/shinytest2</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Linked every template file and showed it on the page.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 8 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 7</span><span class="site-related-card__title">Secrets management</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 9</span><span class="site-related-card__title">Releases &amp; changelogs</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/adrs-and-evidence/index.html" class="site-link-row" title="Record architectural decisions with ADRs and verify technical documentation against upstream evidence."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">ADRs &amp; evidence: record decisions, verify docs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/index.html" class="site-link-row" title="The mascot package is now on CRAN: add mood-driven characters to Shiny apps and Quarto pages, with visible status text, speech bubbles, click menus and reduced-motion support."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">mascot is on CRAN: live, mood-driven mascots for Shiny and Quarto</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/index.html" class="site-link-row" title="Declare external packages in DESCRIPTION Imports and Suggests, call functions through pkg::fun() or @importFrom, and guard optional dependencies cleanly."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Dependencies: DESCRIPTION and NAMESPACE</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Git</category>
  <category>R packages</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/issue-forms-pr-templates/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Keyless deploys: let CI prove who it is (OIDC)</title>
  <link>https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Deploying code from CI to cloud providers traditionally begins with a dangerous ritual:</p>
<ol type="1">
<li>Generate a service account in your cloud console.</li>
<li>Download a long-lived credential file (such as a Google Cloud JSON service account key or an AWS access key pair).</li>
<li>Paste that JSON blob into GitHub repository secrets (<code>GCP_SA_KEY</code>).</li>
<li>Hope nobody ever logs it, forks the repo, or compromises an action that reads it.</li>
</ol>
<p>This practice carries severe operational and compliance liabilities:</p>
<ul>
<li><strong>No built-in expiration.</strong> A service account JSON key never expires. If an action dumps environment variables or a malicious dependency exfiltrates the secret, the key remains valid until someone manually notices and revokes it.</li>
<li><strong>Rotation debt.</strong> Rotating keys across multiple repositories is tedious, so teams rarely do it. In GxP environments, static shared keys weaken the audit trail because any system holding the key appears identical in access logs.</li>
<li><strong>Accidental exposure.</strong> A single misplaced <code>echo</code> statement or debugging chunk in an R Markdown or Quarto document can print environment variables into build logs, exposing the entire key (see <a href="https://insightsurge-dev.web.app/posts/secret-scanning/index.html">secret scanning</a>).</li>
</ul>
<p>The solution is to <strong>eliminate static keys entirely</strong>. Instead of storing a secret in GitHub, let GitHub cryptographically prove its identity to the cloud on every single run.</p>
</section>
<section id="the-web-repo-way-workload-identity-federation" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-workload-identity-federation">The web-repo way: Workload Identity Federation</h2>
<p>Modern cloud architectures use <strong>OpenID Connect (OIDC)</strong> and <strong>Workload Identity Federation (WIF)</strong>.</p>
<section id="how-oidc-authentication-works" class="level3">
<h3 class="anchored" data-anchor-id="how-oidc-authentication-works">How OIDC authentication works</h3>
<ol type="1">
<li>When a workflow job starts, GitHub’s OIDC token service generates a signed, short-lived JSON Web Token (JWT) describing the workflow (the repository, the commit, the branch, and the triggering event).</li>
<li>The GitHub Action sends this token to Google Cloud’s Security Token Service (STS).</li>
<li>Google Cloud validates the token’s cryptographic signature using GitHub’s published signing keys (OIDC discovery/JWKS at the issuer: <code>https://token.actions.githubusercontent.com</code>).</li>
<li>If the token claims match the configured trust rules, Google exchanges the GitHub token for a temporary, short-lived (by default about an hour) Google Cloud access token.</li>
<li>The workflow deploys using that short-lived token. When the job finishes, the token expires automatically.</li>
</ol>
</section>
<section id="configuring-keyless-federation-in-google-cloud" class="level3">
<h3 class="anchored" data-anchor-id="configuring-keyless-federation-in-google-cloud">Configuring keyless federation in Google Cloud</h3>
<p>In Google Cloud, we configure a Workload Identity Pool and an OIDC Provider pinned strictly to the repository:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="va" style="color: #111111;">PROJECT_ID</span><span class="op" style="color: #5E5E5E;">=</span>my-project</span>
<span id="cb1-2"><span class="va" style="color: #111111;">PROJECT_NUMBER</span><span class="op" style="color: #5E5E5E;">=</span><span class="va" style="color: #111111;">$(</span><span class="ex" style="color: null;">gcloud</span> projects describe <span class="va" style="color: #111111;">$PROJECT_ID</span> <span class="at" style="color: #657422;">--format</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">'value(projectNumber)'</span><span class="va" style="color: #111111;">)</span></span>
<span id="cb1-3"><span class="va" style="color: #111111;">SA</span><span class="op" style="color: #5E5E5E;">=</span>gh-deploy@<span class="va" style="color: #111111;">$PROJECT_ID</span>.iam.gserviceaccount.com</span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="co" style="color: #5E5E5E;"># 1. Create the pool and GitHub OIDC provider</span></span>
<span id="cb1-6"><span class="ex" style="color: null;">gcloud</span> iam workload-identity-pools create github <span class="at" style="color: #657422;">--project</span><span class="op" style="color: #5E5E5E;">=</span><span class="va" style="color: #111111;">$PROJECT_ID</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-7">  <span class="at" style="color: #657422;">--location</span><span class="op" style="color: #5E5E5E;">=</span>global <span class="at" style="color: #657422;">--display-name</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"GitHub Actions"</span></span>
<span id="cb1-8"></span>
<span id="cb1-9"><span class="ex" style="color: null;">gcloud</span> iam workload-identity-pools providers create-oidc playbook <span class="at" style="color: #657422;">--project</span><span class="op" style="color: #5E5E5E;">=</span><span class="va" style="color: #111111;">$PROJECT_ID</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-10">  <span class="at" style="color: #657422;">--location</span><span class="op" style="color: #5E5E5E;">=</span>global <span class="at" style="color: #657422;">--workload-identity-pool</span><span class="op" style="color: #5E5E5E;">=</span>github <span class="at" style="color: #657422;">--display-name</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"my-site"</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-11">  <span class="at" style="color: #657422;">--issuer-uri</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"https://token.actions.githubusercontent.com"</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-12">  <span class="at" style="color: #657422;">--attribute-mapping</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"google.subject=assertion.sub,attribute.repository_id=assertion.repository_id,attribute.repository_owner_id=assertion.repository_owner_id"</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-13">  <span class="at" style="color: #657422;">--attribute-condition</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"assertion.repository_owner_id=='&lt;OWNER_ID&gt;' &amp;&amp; assertion.repository_id=='&lt;REPO_ID&gt;'"</span></span>
<span id="cb1-14"></span>
<span id="cb1-15"><span class="co" style="color: #5E5E5E;"># 2. Grant minimal IAM roles to a dedicated deployment service account</span></span>
<span id="cb1-16"><span class="ex" style="color: null;">gcloud</span> iam service-accounts create gh-deploy <span class="at" style="color: #657422;">--project</span><span class="op" style="color: #5E5E5E;">=</span><span class="va" style="color: #111111;">$PROJECT_ID</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-17">  <span class="at" style="color: #657422;">--display-name</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"GitHub deploy: my-site"</span></span>
<span id="cb1-18"></span>
<span id="cb1-19"><span class="ex" style="color: null;">gcloud</span> projects add-iam-policy-binding <span class="va" style="color: #111111;">$PROJECT_ID</span> <span class="at" style="color: #657422;">--member</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"serviceAccount:</span><span class="va" style="color: #111111;">$SA</span><span class="st" style="color: #20794D;">"</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-20">  <span class="at" style="color: #657422;">--role</span><span class="op" style="color: #5E5E5E;">=</span>roles/firebasehosting.admin</span>
<span id="cb1-21"><span class="ex" style="color: null;">gcloud</span> projects add-iam-policy-binding <span class="va" style="color: #111111;">$PROJECT_ID</span> <span class="at" style="color: #657422;">--member</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"serviceAccount:</span><span class="va" style="color: #111111;">$SA</span><span class="st" style="color: #20794D;">"</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-22">  <span class="at" style="color: #657422;">--role</span><span class="op" style="color: #5E5E5E;">=</span>roles/serviceusage.apiKeysViewer</span>
<span id="cb1-23"></span>
<span id="cb1-24"><span class="co" style="color: #5E5E5E;"># 3. Allow workflows matching our repository ID to impersonate the service account</span></span>
<span id="cb1-25"><span class="ex" style="color: null;">gcloud</span> iam service-accounts add-iam-policy-binding <span class="va" style="color: #111111;">$SA</span> <span class="at" style="color: #657422;">--project</span><span class="op" style="color: #5E5E5E;">=</span><span class="va" style="color: #111111;">$PROJECT_ID</span> <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-26">  <span class="at" style="color: #657422;">--role</span><span class="op" style="color: #5E5E5E;">=</span>roles/iam.workloadIdentityUser <span class="dt" style="color: #AD0000;">\</span></span>
<span id="cb1-27">  <span class="at" style="color: #657422;">--member</span><span class="op" style="color: #5E5E5E;">=</span><span class="st" style="color: #20794D;">"principalSet://iam.googleapis.com/projects/</span><span class="va" style="color: #111111;">$PROJECT_NUMBER</span><span class="st" style="color: #20794D;">/locations/global/workloadIdentityPools/github/attribute.repository_id/&lt;REPO_ID&gt;"</span></span></code></pre></div></div>
<p>Notice the attribute condition:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb2-1"><span class="ex" style="color: null;">assertion.repository_owner_id</span> == <span class="st" style="color: #20794D;">'&lt;OWNER_ID&gt;'</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">&amp;&amp;</span> <span class="ex" style="color: null;">assertion.repository_id</span> == <span class="st" style="color: #20794D;">'&lt;REPO_ID&gt;'</span></span></code></pre></div></div>
<p>We pin to GitHub’s <strong>numeric repository and owner IDs</strong> rather than the string repository name. If the repository or organization is later renamed, the identity assertion cannot be hijacked or broken.</p>
</section>
<section id="the-github-actions-workflow" class="level3">
<h3 class="anchored" data-anchor-id="the-github-actions-workflow">The GitHub Actions workflow</h3>
<p>In <code>.github/workflows/quarto.yml</code>, the job requests an OIDC token by declaring <code>id-token: write</code> permissions, then uses <code>google-github-actions/auth@v3</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb3-1"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">contents</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read</span></span>
<span id="cb3-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">id-token</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> write</span><span class="co" style="color: #5E5E5E;">          # Required for requesting the GitHub OIDC JWT</span></span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-6"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> actions/checkout@v7</span></span>
<span id="cb3-7"></span>
<span id="cb3-8"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Authenticate to Google Cloud (keyless)</span></span>
<span id="cb3-9"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">if</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> env.DEPLOY_ENABLED == 'true'</span></span>
<span id="cb3-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> google-github-actions/auth@v3</span></span>
<span id="cb3-11"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb3-12"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">workload_identity_provider</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }}</span></span>
<span id="cb3-13"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">service_account</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ vars.GCP_SERVICE_ACCOUNT }}</span></span>
<span id="cb3-14"></span>
<span id="cb3-15"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> Deploy site</span></span>
<span id="cb3-16"><span class="fu" style="color: #4758AB;">    run</span><span class="kw" style="color: #003B4F;
font-weight: bold;">: </span><span class="ch" style="color: #20794D;">|</span></span>
<span id="cb3-17">      npx --yes "$FIREBASE_TOOLS" deploy --only hosting \</span>
<span id="cb3-18">        --project "${{ vars.FIREBASE_PROJECT_ID }}"</span></code></pre></div></div>
</section>
<section id="variables-not-secrets" class="level3">
<h3 class="anchored" data-anchor-id="variables-not-secrets">Variables, not secrets</h3>
<p>Notice the workflow syntax: <code>${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }}</code>.</p>
<p>Because Workload Identity Federation uses cryptographic attestation rather than shared passwords, the provider URI, service account email, and project ID are <strong>public identifiers, not secrets</strong>. They are stored in repository variables, visible in plain text in the repo settings. An attacker who copies those values cannot authenticate from their own machine or from another repository because Google STS verifies that the requesting JWT originates from our specific GitHub repository ID.</p>
</section>
<section id="why-not-firebases-official-github-action" class="level3">
<h3 class="anchored" data-anchor-id="why-not-firebases-official-github-action">Why not Firebase’s official GitHub Action?</h3>
<p>The official Firebase deployment action (<code>FirebaseExtended/action-hosting-deploy</code>) requires users to paste a service account JSON key into GitHub Secrets (<code>FIREBASE_SERVICE_ACCOUNT_...</code>).</p>
<p>Our secrets standard forbids JSON keys (see <a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html">secrets management</a>). Instead, we authenticate keylessly via <code>google-github-actions/auth@v3</code>, which writes a short-lived <strong>credential configuration</strong> file (external account, no private key) and points <code>GOOGLE_APPLICATION_CREDENTIALS</code> at it. We then invoke <code>firebase-tools</code> directly using <code>npx</code>. The Firebase CLI automatically picks up the temporary credentials.</p>
</section>
</section>
<section id="the-r-way-an-analogy-for-r-developers" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-an-analogy-for-r-developers">The R way: an analogy for R developers</h2>
<p>For developers accustomed to R and Shiny, OIDC authentication is the difference between writing your database password into a <code>.Renviron</code> file versus authenticating through your organisation’s Single Sign-On (SSO) system.</p>
<ul>
<li><strong>The static key approach:</strong> Copying a static API token into <code>.Renviron</code> or <code>.Renviron.site</code>. If that laptop or server is compromised, the token remains valid indefinitely.</li>
<li><strong>The OIDC approach:</strong> When you log into an enterprise RStudio Server or Posit Workbench instance via SAML/OIDC, the identity provider checks your credentials, confirms your group memberships, and issues a temporary session token. No service password is typed into R, and access revokes automatically when the session closes.</li>
</ul>
<section id="cloud-and-platform-support" class="level3">
<h3 class="anchored" data-anchor-id="cloud-and-platform-support">Cloud and platform support</h3>
<p>GitHub provides native OIDC token generation for the three major cloud providers: - <strong>Google Cloud:</strong> Workload Identity Federation (used here). - <strong>Amazon Web Services (AWS):</strong> IAM OpenID Connect identity providers and role assumption (<code>aws-actions/configure-aws-credentials</code>). - <strong>Microsoft Azure:</strong> Azure AD / Entra ID federated credentials (<code>azure/login</code>).</p>
</section>
<section id="what-about-posit-connect-and-shinyapps.io" class="level3">
<h3 class="anchored" data-anchor-id="what-about-posit-connect-and-shinyapps.io">What about Posit Connect and shinyapps.io?</h3>
<p>When deploying Shiny applications or Quarto reports to hosting platforms: - <strong>Cloud-native targets:</strong> Targets you reach through a cloud’s own IAM (e.g.&nbsp;deploying to Cloud Run) can use the same keyless pattern. - <strong>Dedicated hosting platforms:</strong> Posit Connect and shinyapps.io commonly authenticate deploys with API keys; check your platform’s docs for federation support. If federation is unavailable, follow strict secret discipline (see <a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html">secrets management</a>): create a scoped, minimally privileged API key, store it in GitHub Secrets, and implement a regular rotation schedule.</p>
</section>
</section>
<section id="pitfalls-we-hit" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-we-hit">Pitfalls we hit</h2>
<ul>
<li><strong>Missing <code>id-token: write</code> permission.</strong> If your GitHub Actions workflow omits <code>permissions: id-token: write</code>, GitHub will not provide a token. The auth step fails because no OIDC token is available.</li>
<li><strong>Pinning repository names instead of IDs.</strong> Trusting <code>assertion.repository == "org/repo"</code> is vulnerable if a repository is renamed or an account is transferred. Always pin <code>assertion.repository_id</code> using the immutable numeric identifier.</li>
<li><strong>Over-privileged service accounts.</strong> Assigning <code>roles/owner</code> or <code>roles/editor</code> to the CI service account breaks the principle of least privilege. Our service account receives only <code>roles/firebasehosting.admin</code> and <code>roles/serviceusage.apiKeysViewer</code>.</li>
<li><strong>Assuming third-party actions support keyless auth.</strong> Many legacy GitHub Actions still expect a static token or JSON secret. Check action documentation before adopting it; running the underlying CLI tool directly via <code>npx</code> or shell scripts is often cleaner.</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
</ul>
</div>
</div>
</div>



</section>
<div class="site-related">
<section id="also-in" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="also-in">Also in</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-link-row" title="Build the everyday practices around R code: safe identities, version control, CI, releases, dependencies and decisions. Each part connects a web-repo practice to work in an R package or Shiny app."><span class="is-card__eyebrow site-link-row__label">Series · 16 parts</span><span class="site-link-row__title">Foundations series</span></a></li>
</ul>
</div>
</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html" class="site-link-row" title="Separate configuration names in version control from secrets stored in vaults and environment variables."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Secrets management</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html" class="site-link-row" title="Run R CMD check, tests, and link validation automatically on clean GitHub Actions runners with pinned dependencies."><span class="is-card__eyebrow site-link-row__label">Builds on</span><span class="site-link-row__title">CI with GitHub Actions</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
</ul>
</div>
</section>
</div>


 ]]></description>
  <category>Security</category>
  <category>CI/CD</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>One owner, two models: delegating to a second AI and verifying it</title>
  <link>https://insightsurge-dev.web.app/posts/two-model-workflow/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Relying on a single AI model for complex software engineering creates subtle failure modes:</p>
<ol type="1">
<li><strong>Context saturation and drift.</strong> Long-running coding sessions accumulate numerous turns. Over time, the model loses sight of original architectural constraints, begins making assumptions, and glosses over breaking changes.</li>
<li><strong>Confirmation bias and echo chambers.</strong> When the same model that wrote a piece of code is asked to review or test it, it frequently confirms its own initial assumptions rather than catching edge cases.</li>
<li><strong>The loss of accountability.</strong> Handing complete control to autonomous agentic workflows violates fundamental engineering governance. In regulated environments (such as GxP clinical analytics), every code change must be attributable to a qualified practitioner who understands and verifies the work.</li>
</ol>
<p>To achieve high velocity without compromising rigor, we use a <strong>two-model workflow</strong>: an <strong>Owner</strong> model that directs, reviews, and executes outward actions, paired with one or more <strong>Delegate</strong> model sessions that perform focused research, drafting, and analysis under strict constraints.</p>
</section>
<section id="the-delegation-pattern-owner-and-delegate" class="level2">
<h2 class="anchored" data-anchor-id="the-delegation-pattern-owner-and-delegate">The delegation pattern: Owner and Delegate</h2>
<p>The workflow establishes a clear division of responsibility between two distinct AI models (in our practice, delegating to Gemini with Claude acting as owner):</p>
<pre class="mermaid"><code>flowchart TD
    Human["Named Human Engineer"] --&gt; Owner["Owner AI (Claude)"]
    Owner --&gt;|"Written Brief &amp; Constraints"| Delegate["Delegate AI (Gemini)"]
    Delegate --&gt;|"Structured Digest"| Owner
    Owner --&gt;|"Re-opens files, verifies claims"| Review{"Verification Gate"}
    Review --&gt;|"Pass"| Actions["Git Commit, Push, Merge, Deploy"]
    Review --&gt;|"Nuance missed / Fail"| Revise["Refine or Reject"]</code></pre>
<section id="the-brief-explicit-scope-and-acceptance-checks" class="level3">
<h3 class="anchored" data-anchor-id="the-brief-explicit-scope-and-acceptance-checks">1. The brief: explicit scope and acceptance checks</h3>
<p>Delegation begins with a structured markdown brief (such as <code>dev/handoffs/playbook-site/research/gemini-brief.md</code>, following our pattern for <a href="https://insightsurge-dev.web.app/posts/handoffs-agentic-context/index.html">handoffs and agentic context</a>). The brief defines: - <strong>Strict file ownership:</strong> Explicit directories the delegate may modify, with all other repository files designated read-only. - <strong>Hard constraints:</strong> Specific forbidden commands (no <code>git commit</code>, <code>git push</code>, or package installations) and strict style guidelines (no marketing hype, no unverified claims). - <strong>Verifiable facts:</strong> Exact evidence from repository configuration and official documentation that the delegate may cite.</p>
</section>
<section id="the-output-contract-digests-not-transcripts" class="level3">
<h3 class="anchored" data-anchor-id="the-output-contract-digests-not-transcripts">2. The output contract: digests, not transcripts</h3>
<p>Delegates are never permitted to dump raw session transcripts or full file contents into the owner’s context. The delegate must conclude with a <strong>compact digest</strong>: - Files created or modified; - Decisions made and rationale; - Unverified items flagged explicitly with <code>&lt;!-- UNVERIFIED: ... --&gt;</code>; - Open questions or discrepancies found.</p>
</section>
<section id="the-owner-retains-outward-actions" class="level3">
<h3 class="anchored" data-anchor-id="the-owner-retains-outward-actions">3. The owner retains outward actions</h3>
<p>The delegate never touches outward-facing tools. The owner model (under human supervision) reviews the diffs, runs test suites, builds the documentation, and executes git operations.</p>
</section>
</section>
<section id="evidence-from-our-own-work" class="level2">
<h2 class="anchored" data-anchor-id="evidence-from-our-own-work">Evidence from our own work</h2>
<p>We applied this two-model workflow to two real engineering challenges in our repositories.</p>
<section id="case-1-dependabot-pr-triage" class="level3">
<h3 class="anchored" data-anchor-id="case-1-dependabot-pr-triage">Case 1: Dependabot PR triage</h3>
<p>When automated dependency PRs arrived on our website repository, we assigned Gemini to analyse three separate pull requests and produce a triage recommendation:</p>
<ol type="1">
<li><strong>React 19.3.0:</strong> Gemini verified that Next.js 16.3 declared a peer dependency range of <code>^19.0.0</code>, confirming that the minor version bump was safe. Recommendation: <em>Merge</em>.</li>
<li><strong><code>@types/node</code> 26.x:</strong> Gemini verified that our runtime environment was pinned to Node 24 (<code>.nvmrc</code> and <code>package.json</code>). While CI passed and no type mismatches were observed, the types should match the Node 24 runtime so code cannot start using Node 26 APIs the runtime lacks. Recommendation: <em>Close and add a semver-major ignore rule in <code>.github/dependabot.yml</code></em>.</li>
<li><strong>TypeScript 7.x:</strong> Gemini verified that Next.js 16.3 bundled official documentation for TypeScript 7 compatibility. Recommendation: <em>Merge</em>.</li>
</ol>
<p><strong>The verification step:</strong> The owner did not simply accept the summary. Claude re-opened every cited file, inspected the diffs, and checked the bundled Next.js documentation.</p>
<p>In doing so, Claude noted a nuance that Gemini had glossed over: running the project’s own <code>tsc</code> is Next 16.3’s default, and the related config page (<code>useTypeScriptCli</code>) is labelled experimental. The triage was accepted with this caveat recorded in the PR description.</p>
</section>
<section id="case-2-playbook-documentation-migration" class="level3">
<h3 class="anchored" data-anchor-id="case-2-playbook-documentation-migration">Case 2: Playbook documentation migration</h3>
<p>Migrating our engineering playbook from legacy topic folders to a modern blog structure was split across five delegate sessions: - A <strong>research session</strong> explored Quarto visual themes and listing options; - A <strong>migrate session</strong> moved files and restructured navigation; - An <strong>articles session</strong> drafted new technical content in <code>drafts/</code>; - An <strong>editor/categories session</strong> finalised copy and unified metadata taxonomy; - A <strong>theme/bslib session</strong> integrated shared branding.</p>
<p>Each session operated under the shared brief (<code>gemini-brief.md</code>). Claude reviewed each phase, rendered the site locally, ran offline link checks, performed browser checks, and committed the verified diffs via pull request. The no-git and no-push constraints were enforced through the explicit brief and owner review rather than technical sandboxing.</p>
</section>
</section>
<section id="the-gxp-link-attributability-and-the-four-eyes-principle" class="level2">
<h2 class="anchored" data-anchor-id="the-gxp-link-attributability-and-the-four-eyes-principle">The GxP link: Attributability and the four-eyes principle</h2>
<p>In GxP regulated industries, data integrity rests on the <strong>ALCOA+</strong> principles, where the <strong>A</strong> stands for <strong>Attributable</strong>: every decision, code change, and clinical analysis must be directly traced to a responsible individual.</p>
<p>An AI model cannot be a regulated legal entity. It cannot sign off on a statistical analysis plan, approve a production release, or testify to an auditor.</p>
<p>The two-model workflow mirrors the traditional <strong>four-eyes principle</strong> (independent technical review) standard in clinical programming: - <strong>First pair of eyes (Delegate):</strong> Performs the heavy lifting—drafting code, researching dependency changelogs, and synthesizing test results. - <strong>Second pair of eyes (Owner &amp; Named Human):</strong> Independently re-opens the primary evidence, verifies the findings against official standards, challenges edge cases, and takes personal responsibility for committing the change.</p>
<p>By keeping the owner accountable for verification and outward actions, teams can leverage the speed of generative AI while keeping changes reviewable and attributable (capturing decisions as described in <a href="https://insightsurge-dev.web.app/posts/adrs-and-evidence/index.html">ADRs and evidence</a>).</p>
</section>
<section id="pitfalls-we-hit" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls-we-hit">Pitfalls we hit</h2>
<ul>
<li><strong>The summary trap.</strong> Trusting a delegate’s polished summary without re-opening the primary source files. If the delegate misinterprets a release note or misses an experimental flag, the owner inherits the error.</li>
<li><strong>Instructions are not technical isolation.</strong> Prompts and briefs that instruct delegates not to run <code>git push</code> or modify credentials rely on compliance, not enforcement. For stronger boundaries, run delegates in an isolated sandbox or git worktree without write credentials.</li>
<li><strong>Overlapping file ownership.</strong> Allowing multiple parallel AI sessions to edit the same files leads to merge conflicts and overwritten context. Enforce strict, non-overlapping directory boundaries.</li>
<li><strong>Context dumping.</strong> Pasting full agent chat transcripts into the owner session rapidly bloats context windows and degrades reasoning performance. Enforce compact, bulleted digests.</li>
<li><strong>Leaking execution authority.</strong> Giving subagents permission to run <code>git push</code>, publish packages, or close PRs bypasses the verification gate. Outward actions must belong exclusively to the owner.</li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
</ul>
</div>
</div>
</div>



</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor site-related">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/handoffs-agentic-context/index.html" class="site-link-row" title="Provide AI coding agents with durable project instructions and concise handoffs instead of endless chat history."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Handoffs &amp; agentic context</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/test-your-guardrails/index.html" class="site-link-row" title="Challenge CI checks and pre-commit hooks deliberately with failing test PRs to prove guardrails work."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Test your guardrails: probe PRs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/adrs-and-evidence/index.html" class="site-link-row" title="Record architectural decisions with ADRs and verify technical documentation against upstream evidence."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">ADRs &amp; evidence: record decisions, verify docs</span></a></li>
</ul>
</div>
</section>


 ]]></description>
  <category>Agentic AI</category>
  <category>GxP</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/two-model-workflow/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Pre-commit hooks, formatting &amp; linting</title>
  <link>https://insightsurge-dev.web.app/posts/hooks-formatting-linting/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Half the comments on an unformatted PR are about style: spacing, <code>&lt;-</code> vs <code>=</code>, line length. Those are cheap for a machine to fix and expensive for a person to review. Then there are the embarrassing slips: a <code>browser()</code> left in, a file that doesn’t parse, a <code>NAMESPACE</code> out of date.</p>
<p>Three layers solve this. Each one is faster and closer to you than the next:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Layer</th>
<th>Runs</th>
<th>Catches</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Editor</strong> (format on save)</td>
<td>While you type</td>
<td>Style</td>
</tr>
<tr class="even">
<td><strong>Pre-commit hook</strong></td>
<td>On <code>git commit</code>, on staged files</td>
<td>Style, lint, debug leftovers, unparsable files</td>
</tr>
<tr class="odd">
<td><strong>CI</strong></td>
<td>On every PR</td>
<td>Everything, for everyone, with no way to skip</td>
</tr>
</tbody>
</table>
</div>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In our TypeScript project, <code>husky</code> installs git hooks when you run <code>npm install</code>, and <code>lint-staged</code> runs the formatter and linter (Biome) on <strong>staged files only</strong>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript"><span id="cb1-1"><span class="co" style="color: #5E5E5E;">// lint-staged.config.mjs</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;">export</span> <span class="im" style="color: #00769E;">default</span> {</span>
<span id="cb1-3">  <span class="st" style="color: #20794D;">"*.{ts,tsx,js,json,css,md}"</span><span class="op" style="color: #5E5E5E;">:</span> [<span class="st" style="color: #20794D;">"biome check --write --no-errors-on-unmatched"</span>]<span class="op" style="color: #5E5E5E;">,</span></span>
<span id="cb1-4">}<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<p>Design choices worth copying:</p>
<ul>
<li><strong>Only staged files</strong>, so a commit takes about a second, however big the repo.</li>
<li><strong>Auto-fix, then re-stage.</strong> Formatting is fixed, not just reported.</li>
<li><strong>Slow checks stay in CI.</strong> Typecheck, tests and build run on the PR, not on every commit. If a hook is slow, people learn to skip it with <code>--no-verify</code>.</li>
<li><strong>CI re-runs the same checks</strong> (<code>biome ci</code>), because hooks are local and optional.</li>
</ul>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<section id="formatter-air-or-styler" class="level3">
<h3 class="anchored" data-anchor-id="formatter-air-or-styler">Formatter: Air (or styler)</h3>
<p><a href="https://posit-dev.github.io/air/">Air</a> is Posit’s formatter for R. It’s extremely fast, and it’s built into Positron and available for RStudio. <code>styler</code> is the long-standing alternative.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_air</span>()   <span class="co" style="color: #5E5E5E;"># usethis &gt;= 3.2.0: configures the project for Air</span></span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;">air</span> format .          <span class="co" style="color: #5E5E5E;"># format the project</span></span>
<span id="cb3-2"><span class="ex" style="color: null;">air</span> format . <span class="at" style="color: #657422;">--check</span>  <span class="co" style="color: #5E5E5E;"># fail if anything would change (for CI)</span></span></code></pre></div></div>
</section>
<section id="linter-lintr" class="level3">
<h3 class="anchored" data-anchor-id="linter-lintr">Linter: lintr</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">lintr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_lintr</span>(<span class="at" style="color: #657422;">type =</span> <span class="st" style="color: #20794D;">"tidyverse"</span>)   <span class="co" style="color: #5E5E5E;"># writes a .lintr config</span></span>
<span id="cb4-2">lintr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">lint_package</span>()</span></code></pre></div></div>
<p>The linter finds what a formatter can’t: unused variables, <code>T</code>/<code>F</code> instead of <code>TRUE</code>/<code>FALSE</code>, <code>1:length(x)</code>, object names, cyclomatic complexity.</p>
</section>
<section id="pre-commit-hooks-the-precommit-package" class="level3">
<h3 class="anchored" data-anchor-id="pre-commit-hooks-the-precommit-package">Pre-commit hooks: the <code>precommit</code> package</h3>
<p><a href="https://lorenzwalthert.github.io/precommit/"><code>precommit</code></a> brings the <a href="https://pre-commit.com">pre-commit</a> framework to R, with hooks written for R projects. Save <a href="https://insightsurge-dev.web.app/templates/pre-commit/pre-commit-config.yaml"><code>templates/pre-commit/pre-commit-config.yaml</code></a> in your project root as <code>.pre-commit-config.yaml</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb5-1"><span class="fu" style="color: #4758AB;">repos</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-2"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">repo</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> https://github.com/posit-dev/air-pre-commit</span></span>
<span id="cb5-3"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">rev</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="fl" style="color: #AD0000;">0.11.0</span></span>
<span id="cb5-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">hooks</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-5"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> air-format</span></span>
<span id="cb5-6"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">repo</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> https://github.com/lorenzwalthert/precommit</span></span>
<span id="cb5-7"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">rev</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> v0.4.3</span></span>
<span id="cb5-8"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">hooks</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-9"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> parsable-R</span></span>
<span id="cb5-10"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> no-browser-statement</span></span>
<span id="cb5-11"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> no-debug-statement</span></span>
<span id="cb5-12"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> roxygenize</span><span class="co" style="color: #5E5E5E;">          # keep man/ and NAMESPACE in sync</span></span>
<span id="cb5-13"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> deps-in-desc</span><span class="co" style="color: #5E5E5E;">        # every pkg::fn() is declared in DESCRIPTION</span></span>
<span id="cb5-14"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> lintr</span></span>
<span id="cb5-15"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> readme-rmd-rendered</span></span>
<span id="cb5-16"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">repo</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> https://github.com/gitleaks/gitleaks</span><span class="co" style="color: #5E5E5E;">   # see secret scanning</span></span>
<span id="cb5-17"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">rev</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> v8.30.1</span></span>
<span id="cb5-18"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">hooks</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-19"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> gitleaks</span></span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb6-1">precommit<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_precommit</span>()   <span class="co" style="color: #5E5E5E;"># writes the config (if missing) and installs the git hook</span></span></code></pre></div></div>
<p>It relies on the Python <code>pre-commit</code> tool. <code>precommit::install_precommit()</code> can set it up for you.</p>
</section>
<section id="ci-the-gate-nobody-can-skip" class="level3">
<h3 class="anchored" data-anchor-id="ci-the-gate-nobody-can-skip">CI: the gate nobody can skip</h3>
<p><code>r-lib/actions</code> includes <code>lint.yaml</code>, <code>lint-changed-files.yaml</code> and <code>style.yaml</code> examples, and Air has <code>posit-dev/setup-air</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_action</span>(<span class="st" style="color: #20794D;">"lint"</span>)   <span class="co" style="color: #5E5E5E;"># lintr on every PR</span></span>
<span id="cb7-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_action</span>(<span class="at" style="color: #657422;">url =</span> <span class="st" style="color: #20794D;">"https://github.com/posit-dev/setup-air/blob/main/examples/format-check.yaml"</span>)</span></code></pre></div></div>
<p>Air’s <code>format-suggest.yaml</code> example goes one better. It posts the formatting fixes as <strong>suggestions on the PR</strong>, so a contributor without Air can accept them with a click.</p>
</section>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Format the whole repo once, in its own PR,</strong> before switching the check on. Otherwise the first real PR drowns in unrelated diffs.</li>
<li><strong>Hooks aren’t cloned.</strong> Every developer runs <code>precommit::use_precommit()</code> (or <code>npm install</code>) once. Put it in CONTRIBUTING.</li>
<li><strong>Keep hooks fast.</strong> <code>roxygenize</code> is the slow one in big packages; move it to CI if people start skipping hooks.</li>
<li><strong>Pin hook versions</strong> (<code>rev:</code>). Dependabot’s <code>pre-commit</code> ecosystem can keep them current.</li>
<li><strong>Don’t let the hook and CI disagree.</strong> Use the same tool versions and config files for both.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Web-repo tools</strong></p>
<ul>
<li><strong>husky</strong>: <a href="https://typicode.github.io/husky/">typicode.github.io/husky</a></li>
<li><strong>lint-staged</strong>: <a href="https://github.com/lint-staged/lint-staged">github.com/lint-staged/lint-staged</a></li>
<li><strong>Biome</strong>: <a href="https://biomejs.dev/">biomejs.dev</a></li>
</ul>
<p><strong>R tools</strong></p>
<ul>
<li><strong>Air</strong>: <a href="https://posit-dev.github.io/air/">posit-dev.github.io/air</a></li>
<li><strong>styler</strong>: <a href="https://styler.r-lib.org/">styler.r-lib.org</a></li>
<li><strong>lintr</strong>: <a href="https://lintr.r-lib.org/">lintr.r-lib.org</a></li>
<li><strong>precommit</strong>: <a href="https://lorenzwalthert.github.io/precommit/">lorenzwalthert.github.io/precommit</a></li>
<li><strong>pre-commit framework</strong>: <a href="https://pre-commit.com/">pre-commit.com</a></li>
<li><strong>posit-dev/air-pre-commit</strong>: <a href="https://github.com/posit-dev/air-pre-commit">github.com/posit-dev/air-pre-commit</a></li>
<li><strong>gitleaks pre-commit hook</strong>: <a href="https://github.com/gitleaks/gitleaks">github.com/gitleaks/gitleaks</a></li>
<li><strong>r-lib/actions</strong> (<code>lint.yaml</code>, <code>lint-changed-files.yaml</code>, <code>style.yaml</code>): <a href="https://github.com/r-lib/actions/tree/v2/examples">github.com/r-lib/actions</a></li>
<li><strong>posit-dev/setup-air</strong>: <a href="https://github.com/posit-dev/setup-air">github.com/posit-dev/setup-air</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>use_air()</code>, <code>use_github_action()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Moved the pre-commit configuration into a reusable template.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 4 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 3</span><span class="site-related-card__title">Conventional commits &amp; PR title checks</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 5</span><span class="site-related-card__title">CI with GitHub Actions</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html" class="site-link-row" title="Set up testthat 3rd edition, structure unit tests with expectations, run them locally and in CI, and build reproducible verification suites."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">testthat essentials</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/index.html" class="site-link-row" title="Move reusable analysis helpers from sourced scripts into a minimal R package, and replace workspace pollution with the devtools::load_all() loop."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">From scripts to a package</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="site-link-row" title="Use the R package development loop, read R CMD check diagnostics, and fix four recurring problems."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">The package development loop and R CMD check</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/hooks-formatting-linting/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Property-based testing in R</title>
  <link>https://insightsurge-dev.web.app/posts/property-based-testing/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>In <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html">the first post in this series</a>, we wrote unit tests with explicit expectations. For a function, we typically pick a normal input, a boundary case, and perhaps an <code>NA</code>.</p>
<p>Consider a function that categorises patient ages into clinical reporting groups:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1">classify_age <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb1-2">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">case_when</span>(</span>
<span id="cb1-3">    <span class="fu" style="color: #4758AB;">is.na</span>(age) <span class="sc" style="color: #5E5E5E;">~</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb1-4">    age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&lt; 18"</span>,</span>
<span id="cb1-5">    age <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"18-64"</span>,</span>
<span id="cb1-6">    age <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&gt;= 65"</span></span>
<span id="cb1-7">  )</span>
<span id="cb1-8">}</span></code></pre></div></div>
<p>A standard test suite checks it against hand-picked values:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"classify_age() categorises hand-picked examples"</span>, {</span>
<span id="cb2-2">  <span class="fu" style="color: #4758AB;">expect_identical</span>(<span class="fu" style="color: #4758AB;">classify_age</span>(<span class="dv" style="color: #AD0000;">10</span>), <span class="st" style="color: #20794D;">"&lt; 18"</span>)</span>
<span id="cb2-3">  <span class="fu" style="color: #4758AB;">expect_identical</span>(<span class="fu" style="color: #4758AB;">classify_age</span>(<span class="dv" style="color: #AD0000;">30</span>), <span class="st" style="color: #20794D;">"18-64"</span>)</span>
<span id="cb2-4">  <span class="fu" style="color: #4758AB;">expect_identical</span>(<span class="fu" style="color: #4758AB;">classify_age</span>(<span class="dv" style="color: #AD0000;">70</span>), <span class="st" style="color: #20794D;">"&gt;= 65"</span>)</span>
<span id="cb2-5">})</span></code></pre></div></div>
<p>These assertions pass. But example-based tests only cover cases you thought to write down: if a developer wrote <code>age &gt; 18 &amp; age &lt; 65</code> instead of <code>age &gt;= 18 &amp; age &lt; 65</code>, this suite still passes, because nobody tested 18 exactly. The same blind spot hides off-by-one boundaries, extreme inputs, and silent <code>NA</code>s.</p>
<p>Property-based testing inverts the relationship: instead of specific inputs and expected outputs, you define <strong>universal properties</strong> that must hold for any valid input, and let a generator search for counterexamples.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In web development and systems programming, property-based testing goes back to Haskell’s <a href="https://hackage.haskell.org/package/QuickCheck">QuickCheck</a> (Claessen and Hughes, 2000) and is now widely used:</p>
<ul>
<li><strong>Python:</strong> <a href="https://hypothesis.readthedocs.io/">Hypothesis</a> generates data, detects edge cases, and shrinks failures to minimal examples.</li>
<li><strong>JavaScript and TypeScript:</strong> <a href="https://fast-check.dev/">fast-check</a> tests API boundaries and state machines across generated inputs:</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb3-1"><span class="im" style="color: #00769E;">import</span> fc <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"fast-check"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb3-2"><span class="im" style="color: #00769E;">import</span> { formatAgeGroup } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"./format"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb3-3"></span>
<span id="cb3-4">fc<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">assert</span>(</span>
<span id="cb3-5">  fc<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">property</span>(fc<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">integer</span>({ min<span class="op" style="color: #5E5E5E;">:</span> <span class="dv" style="color: #AD0000;">0</span><span class="op" style="color: #5E5E5E;">,</span> max<span class="op" style="color: #5E5E5E;">:</span> <span class="dv" style="color: #AD0000;">120</span> })<span class="op" style="color: #5E5E5E;">,</span> (age) <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span></span>
<span id="cb3-6">    [<span class="st" style="color: #20794D;">"&lt; 18"</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">"18-64"</span><span class="op" style="color: #5E5E5E;">,</span> <span class="st" style="color: #20794D;">"&gt;= 65"</span>]<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">includes</span>(<span class="fu" style="color: #4758AB;">formatAgeGroup</span>(age))</span>
<span id="cb3-7">  )</span>
<span id="cb3-8">)<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<p>Web repositories rely on this for parsers, serializers, and business rules where bad input could cause silent corruption or crashes.</p>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In R, <a href="https://cran.r-project.org/package=quickcheck">{quickcheck}</a> (built on <a href="https://cran.r-project.org/package=hedgehog">{hedgehog}</a>) integrates property-based testing directly with <a href="https://testthat.r-lib.org/">{testthat}</a>.</p>
<section id="properties-versus-examples" class="level3">
<h3 class="anchored" data-anchor-id="properties-versus-examples">Properties versus examples</h3>
<p>An example test asserts one concrete value (“when <code>age</code> is 30, the result is <code>'18-64'</code>”). A property test asserts a universal truth across the whole domain: “for any non-missing integer <code>age</code> from 0 to 100, the result is never missing and always in <code>c('&lt; 18', '18-64', '&gt;= 65')</code>.”</p>
</section>
<section id="generators-defining-input-domains" class="level3">
<h3 class="anchored" data-anchor-id="generators-defining-input-domains">Generators: defining input domains</h3>
<p><code>{quickcheck}</code> provides composable generators for specific types and shapes, inspectable via <code>quickcheck::show_example()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;">library</span>(quickcheck)</span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;"># Inspect generated values</span></span>
<span id="cb4-4"><span class="fu" style="color: #4758AB;">set.seed</span>(<span class="dv" style="color: #AD0000;">42</span>)</span>
<span id="cb4-5">quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">show_example</span>(quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">100</span>L))</span>
<span id="cb4-6">quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">show_example</span>(quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">character_alphanumeric</span>())</span></code></pre></div></div>
<p>Used later in this post:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Generator</th>
<th>Data produced</th>
<th>Key arguments</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>integer_()</code></td>
<td>Integer vectors</td>
<td><code>len = c(1L, 10L)</code>, <code>any_na = FALSE</code></td>
</tr>
<tr class="even">
<td><code>integer_bounded()</code></td>
<td>Bounded integer vectors</td>
<td><code>left</code>, <code>right</code>, <code>len = c(1L, 10L)</code></td>
</tr>
<tr class="odd">
<td><code>double_bounded()</code></td>
<td>Bounded double vectors</td>
<td><code>left</code>, <code>right</code>, <code>len = c(1L, 10L)</code></td>
</tr>
<tr class="even">
<td><code>data_frame_()</code></td>
<td>Data frames from column generators</td>
<td><code>...</code>, <code>rows = c(1L, 10L)</code></td>
</tr>
</tbody>
</table>
</div>
<p><code>{quickcheck}</code> also exports <code>numeric_()</code>, <code>character_()</code>, <code>factor_()</code>, and <code>tibble_()</code> for other shapes.</p>
</section>
<section id="evaluating-properties-with-quickcheckfor_all" class="level3">
<h3 class="anchored" data-anchor-id="evaluating-properties-with-quickcheckfor_all">Evaluating properties with <code>quickcheck::for_all()</code></h3>
<p>The workhorse of <code>{quickcheck}</code> is <code>for_all()</code>, connecting generators to an expectation function:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1">quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb5-2">  ...,</span>
<span id="cb5-3">  property,</span>
<span id="cb5-4">  <span class="at" style="color: #657422;">tests =</span> <span class="fu" style="color: #4758AB;">getOption</span>(<span class="st" style="color: #20794D;">"quickcheck.tests"</span>, <span class="dv" style="color: #AD0000;">100</span>L),</span>
<span id="cb5-5">  <span class="at" style="color: #657422;">shrinks =</span> <span class="fu" style="color: #4758AB;">getOption</span>(<span class="st" style="color: #20794D;">"quickcheck.shrinks"</span>, <span class="dv" style="color: #AD0000;">100</span>L),</span>
<span id="cb5-6">  <span class="at" style="color: #657422;">discards =</span> <span class="fu" style="color: #4758AB;">getOption</span>(<span class="st" style="color: #20794D;">"quickcheck.discards"</span>, <span class="dv" style="color: #AD0000;">100</span>L)</span>
<span id="cb5-7">)</span></code></pre></div></div>
<p>By default, <code>for_all()</code> runs <strong>100 iterations</strong>, drawing samples from the named generators and passing them to <code>property</code>; if an expectation fails, <code>{quickcheck}</code> stops and begins shrinking.</p>
<p>Evaluated across the generated inputs:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"classify_age() produces valid categories for any valid age"</span>, {</span>
<span id="cb6-2">  allowed_levels <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"&lt; 18"</span>, <span class="st" style="color: #20794D;">"18-64"</span>, <span class="st" style="color: #20794D;">"&gt;= 65"</span>)</span>
<span id="cb6-3"></span>
<span id="cb6-4">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_seed</span>(<span class="dv" style="color: #AD0000;">42</span>)</span>
<span id="cb6-5">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb6-6">    <span class="at" style="color: #657422;">age =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">100</span>L),</span>
<span id="cb6-7">    <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb6-8">      res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">classify_age</span>(age)</span>
<span id="cb6-9">      <span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(res)))</span>
<span id="cb6-10">      <span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(res <span class="sc" style="color: #5E5E5E;">%in%</span> allowed_levels))</span>
<span id="cb6-11">    }</span>
<span id="cb6-12">  )</span>
<span id="cb6-13">})</span></code></pre></div></div>
<p>Because <code>classify_age()</code> handles every boundary, all 100 iterations pass quietly.</p>
</section>
</section>
<section id="shrinking-finding-the-minimal-counterexample" class="level2">
<h2 class="anchored" data-anchor-id="shrinking-finding-the-minimal-counterexample">Shrinking: finding the minimal counterexample</h2>
<p>Suppose a developer writes <code>classify_age_buggy()</code>, accidentally using <code>age &gt; 18</code> instead of <code>age &gt;= 18</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">classify_age_buggy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb7-2">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">case_when</span>(</span>
<span id="cb7-3">    <span class="fu" style="color: #4758AB;">is.na</span>(age) <span class="sc" style="color: #5E5E5E;">~</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb7-4">    age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&lt; 18"</span>,</span>
<span id="cb7-5">    age <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"18-64"</span>, <span class="co" style="color: #5E5E5E;"># Planted edge-case bug: misses age == 18</span></span>
<span id="cb7-6">    age <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&gt;= 65"</span></span>
<span id="cb7-7">  )</span>
<span id="cb7-8">}</span></code></pre></div></div>
<p>A generator produces a multi-element vector each run; when one element is <code>18</code>, buried among noise, the property fails without saying which value mattered.</p>
<p><strong>Shrinking</strong> answers that: <code>{quickcheck}</code> delegates to <code>{hedgehog}</code>, which retries smaller inputs — shorter vectors, numbers pulled toward 0 — until only the smallest failing input remains.</p>
<p>Running <code>for_all()</code> against <code>classify_age_buggy()</code>, the property fails and shrinks:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"the property detects the missing boundary condition at age 18"</span>, {</span>
<span id="cb8-2">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_seed</span>(<span class="dv" style="color: #AD0000;">42</span>)</span>
<span id="cb8-3">  <span class="fu" style="color: #4758AB;">expect_failure</span>(</span>
<span id="cb8-4">    quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb8-5">      <span class="at" style="color: #657422;">age =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">100</span>L),</span>
<span id="cb8-6">      <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb8-7">        res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">classify_age_buggy</span>(age)</span>
<span id="cb8-8">        <span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(res)))</span>
<span id="cb8-9">      }</span>
<span id="cb8-10">    )</span>
<span id="cb8-11">  )</span>
<span id="cb8-12">})</span></code></pre></div></div>
<p>Evaluated directly without <code>expect_failure()</code>, the report highlights the exact shrunk counterexample:</p>
<pre class="text"><code>Error: Falsifiable after 36 tests, and 9 shrinks
&lt;expectation_failure/expectation/error/condition&gt;
Expected `all(!is.na(res))` to be TRUE.
Differences:
`actual`:   FALSE
`expected`: TRUE

Counterexample:
$age
[1] 18</code></pre>
<p>36 test iterations turned up an input containing <code>18</code>; 9 shrink steps then stripped away every unrelated number and element until only that boundary value remained — the exact input that broke the logic, instead of an unwieldy failure log.</p>
</section>
<section id="four-properties-worth-testing" class="level2">
<h2 class="anchored" data-anchor-id="four-properties-worth-testing">Four properties worth testing</h2>
<p>Four recurring patterns cover most data processing and package functions:</p>
<section id="invariants-structural-properties" class="level3">
<h3 class="anchored" data-anchor-id="invariants-structural-properties">1 · Invariants (structural properties)</h3>
<p>Invariants must hold for any valid input — a standard deviation is never negative, deriving a column never changes the row count, categorisation never leaves the controlled domain:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"square root maintains non-negativity"</span>, {</span>
<span id="cb10-2">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb10-3">    <span class="at" style="color: #657422;">x =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">double_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>, <span class="dv" style="color: #AD0000;">1000</span>),</span>
<span id="cb10-4">    <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) {</span>
<span id="cb10-5">      s <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sqrt</span>(x)</span>
<span id="cb10-6">      <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">length</span>(s), <span class="fu" style="color: #4758AB;">length</span>(x))</span>
<span id="cb10-7">      <span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(s <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">0</span>))</span>
<span id="cb10-8">    },</span>
<span id="cb10-9">    <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">25</span>L</span>
<span id="cb10-10">  )</span>
<span id="cb10-11">})</span></code></pre></div></div>
</section>
<section id="round-trips-symmetry" class="level3">
<h3 class="anchored" data-anchor-id="round-trips-symmetry">2 · Round trips (symmetry)</h3>
<p>Convert data to another format and back, and you should recover the original value:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"integer to character round-trips identically"</span>, {</span>
<span id="cb11-2">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb11-3">    <span class="at" style="color: #657422;">x =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_</span>(),</span>
<span id="cb11-4">    <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) {</span>
<span id="cb11-5">      <span class="fu" style="color: #4758AB;">expect_identical</span>(<span class="fu" style="color: #4758AB;">as.integer</span>(<span class="fu" style="color: #4758AB;">as.character</span>(x)), x)</span>
<span id="cb11-6">    },</span>
<span id="cb11-7">    <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">25</span>L</span>
<span id="cb11-8">  )</span>
<span id="cb11-9">})</span></code></pre></div></div>
<p>Round-trip properties suit serializers, date-time formatters, and encoder-decoder pipelines.</p>
</section>
<section id="idempotence-stability-under-repetition" class="level3">
<h3 class="anchored" data-anchor-id="idempotence-stability-under-repetition">3 · Idempotence (stability under repetition)</h3>
<p>An idempotent operation gives the same result applied once or many times (<code>f(f(x)) == f(x)</code>):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"sorting is idempotent"</span>, {</span>
<span id="cb12-2">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb12-3">    <span class="at" style="color: #657422;">x =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_</span>(),</span>
<span id="cb12-4">    <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) {</span>
<span id="cb12-5">      <span class="fu" style="color: #4758AB;">expect_identical</span>(<span class="fu" style="color: #4758AB;">sort</span>(<span class="fu" style="color: #4758AB;">sort</span>(x)), <span class="fu" style="color: #4758AB;">sort</span>(x))</span>
<span id="cb12-6">    },</span>
<span id="cb12-7">    <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">25</span>L</span>
<span id="cb12-8">  )</span>
<span id="cb12-9">})</span></code></pre></div></div>
<p>Idempotence suits data cleaning, string trimming, and deduplication routines.</p>
</section>
<section id="reference-implementation-comparison-oracle-testing" class="level3">
<h3 class="anchored" data-anchor-id="reference-implementation-comparison-oracle-testing">4 · Reference implementation comparison (oracle testing)</h3>
<p>When you rewrite a function for speed, verify it against a trusted reference implementation — here, base R’s <code>cut()</code>, run against both integer and double ages:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">reference_age <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb13-2">  <span class="fu" style="color: #4758AB;">as.character</span>(<span class="fu" style="color: #4758AB;">cut</span>(</span>
<span id="cb13-3">    age,</span>
<span id="cb13-4">    <span class="at" style="color: #657422;">breaks =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="sc" style="color: #5E5E5E;">-</span><span class="cn" style="color: #8f5902;">Inf</span>, <span class="dv" style="color: #AD0000;">18</span>, <span class="dv" style="color: #AD0000;">65</span>, <span class="cn" style="color: #8f5902;">Inf</span>),</span>
<span id="cb13-5">    <span class="at" style="color: #657422;">right =</span> <span class="cn" style="color: #8f5902;">FALSE</span>,</span>
<span id="cb13-6">    <span class="at" style="color: #657422;">labels =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"&lt; 18"</span>, <span class="st" style="color: #20794D;">"18-64"</span>, <span class="st" style="color: #20794D;">"&gt;= 65"</span>)</span>
<span id="cb13-7">  ))</span>
<span id="cb13-8">}</span>
<span id="cb13-9"></span>
<span id="cb13-10">check_reference <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) <span class="fu" style="color: #4758AB;">expect_identical</span>(<span class="fu" style="color: #4758AB;">classify_age</span>(age), <span class="fu" style="color: #4758AB;">reference_age</span>(age))</span>
<span id="cb13-11"></span>
<span id="cb13-12"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"classify_age() matches reference cut() implementation"</span>, {</span>
<span id="cb13-13">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(<span class="at" style="color: #657422;">age =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">100</span>L), <span class="at" style="color: #657422;">property =</span> check_reference, <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">25</span>L)</span>
<span id="cb13-14">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(<span class="at" style="color: #657422;">age =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">double_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>, <span class="dv" style="color: #AD0000;">100</span>), <span class="at" style="color: #657422;">property =</span> check_reference, <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">25</span>L)</span>
<span id="cb13-15">})</span></code></pre></div></div>
<p>Even a slower, less readable reference gives high confidence when your optimized code matches it across many random inputs.</p>
</section>
</section>
<section id="derivation-invariants-in-clinical-data" class="level2">
<h2 class="anchored" data-anchor-id="derivation-invariants-in-clinical-data">Derivation invariants in clinical data</h2>
<p>In clinical reporting (ADaM derivations), errors here can silently corrupt downstream tables, listings, and figures (TFLs). Property-based testing verifies derivation functions systematically.</p>
<p>Consider a derivation that appends an age group column (<code>AGEGR1</code>) to a clinical data frame:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">derive_age_group <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data, <span class="at" style="color: #657422;">age_col =</span> <span class="st" style="color: #20794D;">"AGE"</span>, <span class="at" style="color: #657422;">new_col =</span> <span class="st" style="color: #20794D;">"AGEGR1"</span>) {</span>
<span id="cb14-2">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.data.frame</span>(data)) {</span>
<span id="cb14-3">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`data` must be a data frame."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb14-4">  }</span>
<span id="cb14-5">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>age_col <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">names</span>(data)) {</span>
<span id="cb14-6">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Column `%s` not found in `data`."</span>, age_col), <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb14-7">  }</span>
<span id="cb14-8">  data[[new_col]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">classify_age</span>(data[[age_col]])</span>
<span id="cb14-9">  data</span>
<span id="cb14-10">}</span></code></pre></div></div>
<p>This derivation must satisfy three properties: <strong>row preservation</strong> (no rows added or dropped, even on empty or single-row data frames), <strong>missingness preservation</strong> (a non-missing <code>AGE</code> never yields a missing <code>AGEGR1</code>), and <strong>controlled terminology</strong> (derived values match the allowed study protocol levels).</p>
<p>We can express these as a property test using <code>quickcheck::data_frame_()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"derive_age_group() preserves rows and missingness across random data frames"</span>, {</span>
<span id="cb15-2">  allowed_levels <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"&lt; 18"</span>, <span class="st" style="color: #20794D;">"18-64"</span>, <span class="st" style="color: #20794D;">"&gt;= 65"</span>)</span>
<span id="cb15-3"></span>
<span id="cb15-4">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb15-5">    <span class="at" style="color: #657422;">df =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">data_frame_</span>(</span>
<span id="cb15-6">      <span class="at" style="color: #657422;">AGE =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">100</span>L, <span class="at" style="color: #657422;">any_na =</span> <span class="cn" style="color: #8f5902;">FALSE</span>),</span>
<span id="cb15-7">      <span class="at" style="color: #657422;">rows =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">20</span>L)</span>
<span id="cb15-8">    ),</span>
<span id="cb15-9">    <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(df) {</span>
<span id="cb15-10">      res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">derive_age_group</span>(df)</span>
<span id="cb15-11">      <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">nrow</span>(res), <span class="fu" style="color: #4758AB;">nrow</span>(df))</span>
<span id="cb15-12">      <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">is.na</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1), <span class="fu" style="color: #4758AB;">is.na</span>(df<span class="sc" style="color: #5E5E5E;">$</span>AGE))</span>
<span id="cb15-13">      <span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1 <span class="sc" style="color: #5E5E5E;">%in%</span> allowed_levels))</span>
<span id="cb15-14">    },</span>
<span id="cb15-15">    <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">25</span>L</span>
<span id="cb15-16">  )</span>
<span id="cb15-17">})</span></code></pre></div></div>
<p>We can also verify the derivation on real CDISC data from <a href="https://pharmaverse.github.io/pharmaverseadam/">{pharmaverseadam}</a>. This runs over every subject in ADSL, not just the safety population (<code>SAFFL == "Y"</code>), since row and missingness preservation are properties of the derivation, not of a particular analysis subset:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"derive_age_group() processes clinical adsl dataset cleanly"</span>, {</span>
<span id="cb16-2">  data <span class="ot" style="color: #003B4F;">&lt;-</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl</span>
<span id="cb16-3">  res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">derive_age_group</span>(data)</span>
<span id="cb16-4"></span>
<span id="cb16-5">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">nrow</span>(res), <span class="fu" style="color: #4758AB;">nrow</span>(data))</span>
<span id="cb16-6">  <span class="fu" style="color: #4758AB;">expect_false</span>(<span class="fu" style="color: #4758AB;">any</span>(<span class="fu" style="color: #4758AB;">is.na</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1)))</span>
<span id="cb16-7">  <span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1 <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"&lt; 18"</span>, <span class="st" style="color: #20794D;">"18-64"</span>, <span class="st" style="color: #20794D;">"&gt;= 65"</span>)))</span>
<span id="cb16-8">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">sum</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1 <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"18-64"</span>), <span class="dv" style="color: #AD0000;">42</span>)</span>
<span id="cb16-9">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">sum</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1 <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"&gt;= 65"</span>), <span class="dv" style="color: #AD0000;">264</span>)</span>
<span id="cb16-10">})</span></code></pre></div></div>
</section>
<section id="limitations-performance-and-reproducibility" class="level2">
<h2 class="anchored" data-anchor-id="limitations-performance-and-reproducibility">Limitations, performance, and reproducibility</h2>
<p>Property-based testing finds defects example-based tests miss, but it has trade-offs:</p>
<section id="execution-time" class="level3">
<h3 class="anchored" data-anchor-id="execution-time">1 · Execution time</h3>
<p>Running 100 iterations per property adds up across a large suite. <code>for_all()</code>’s <code>tests</code> argument defaults to <code>getOption("quickcheck.tests", 100L)</code>; a project can lower it locally and raise it in CI by setting the option once, e.g.&nbsp;in a <code>tests/testthat/setup.R</code> file:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1"><span class="fu" style="color: #4758AB;">options</span>(<span class="at" style="color: #657422;">quickcheck.tests =</span> <span class="dv" style="color: #AD0000;">20</span>L)</span></code></pre></div></div>
<p>Save property tests for core transformations and parsers, not trivial getters.</p>
</section>
<section id="generator-design" class="level3">
<h3 class="anchored" data-anchor-id="generator-design">2 · Generator design</h3>
<p>A property test is only as good as its generator: one producing only positive integers will never surface issues with negative numbers or <code>NA</code>. Realistic, constrained clinical generators take deliberate thought.</p>
</section>
<section id="randomness-and-reproducibility" class="level3">
<h3 class="anchored" data-anchor-id="randomness-and-reproducibility">3 · Randomness and reproducibility</h3>
<p>Because <code>{quickcheck}</code> generates random values on each run, an unseeded test could pass locally yet fail in CI on a rare combination.</p>
<p>To keep test runs deterministic:</p>
<ul>
<li><strong>Set seeds with <code>withr::local_seed()</code>:</strong> As in <a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/index.html">the previous post’s fixtures</a>, prefer it over bare <code>set.seed()</code> inside <code>test_that()</code> blocks — it restores the prior RNG state on exit, so one test’s seed can’t leak into the next.</li>
<li><strong>Turn counterexamples into permanent unit tests:</strong> Whenever a property test catches a bug, take the shrunk counterexample (such as <code>18L</code>) and write it as an explicit <code>expect_identical()</code> test. This preserves the regression check even if generator settings change later.</li>
</ul>
</section>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/property-based-testing/scripts/property-demo.R">View <code>property-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/property-based-testing/scripts/property-demo.R" download="property-demo.R">Download</a></p>
<p>Runs a planted boundary bug in clinical age grouping, demonstrates the failing property test with its shrunk counterexample, and validates the corrected derivation. Its properties are themselves tested, including that the property fails on the buggy function. Requires <code>{quickcheck}</code>, <code>{testthat}</code> and <code>{dplyr}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>property-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><span class="co" style="color: #5E5E5E;"># Property-based testing demo: detects an edge-case boundary bug in clinical age grouping</span></span>
<span id="cb18-2"><span class="co" style="color: #5E5E5E;"># using quickcheck::for_all() and shrinks the failing input to the minimal counterexample.</span></span>
<span id="cb18-3"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb18-4"><span class="co" style="color: #5E5E5E;"># Run with:</span></span>
<span id="cb18-5"><span class="co" style="color: #5E5E5E;">#   Rscript property-demo.R</span></span>
<span id="cb18-6"></span>
<span id="cb18-7"><span class="fu" style="color: #4758AB;">library</span>(quickcheck)</span>
<span id="cb18-8"><span class="fu" style="color: #4758AB;">library</span>(testthat)</span>
<span id="cb18-9"></span>
<span id="cb18-10"><span class="co" style="color: #5E5E5E;">#' Classify age into standard clinical categories (buggy version)</span></span>
<span id="cb18-11"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-12"><span class="co" style="color: #5E5E5E;">#' @param age Numeric or integer vector of patient ages.</span></span>
<span id="cb18-13"><span class="co" style="color: #5E5E5E;">#' @return Character vector with categories "&lt; 18", "18-64", or "&gt;= 65".</span></span>
<span id="cb18-14">classify_age_buggy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb18-15">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">case_when</span>(</span>
<span id="cb18-16">    <span class="fu" style="color: #4758AB;">is.na</span>(age) <span class="sc" style="color: #5E5E5E;">~</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb18-17">    age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&lt; 18"</span>,</span>
<span id="cb18-18">    age <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"18-64"</span>, <span class="co" style="color: #5E5E5E;"># Planted edge-case bug: strict &gt; drops age == 18</span></span>
<span id="cb18-19">    age <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&gt;= 65"</span></span>
<span id="cb18-20">  )</span>
<span id="cb18-21">}</span>
<span id="cb18-22"></span>
<span id="cb18-23"><span class="co" style="color: #5E5E5E;">#' Classify age into standard clinical categories (fixed version)</span></span>
<span id="cb18-24"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-25"><span class="co" style="color: #5E5E5E;">#' @param age Numeric or integer vector of patient ages.</span></span>
<span id="cb18-26"><span class="co" style="color: #5E5E5E;">#' @return Character vector with categories "&lt; 18", "18-64", or "&gt;= 65".</span></span>
<span id="cb18-27">classify_age_fixed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb18-28">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">case_when</span>(</span>
<span id="cb18-29">    <span class="fu" style="color: #4758AB;">is.na</span>(age) <span class="sc" style="color: #5E5E5E;">~</span> <span class="cn" style="color: #8f5902;">NA_character_</span>,</span>
<span id="cb18-30">    age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&lt; 18"</span>,</span>
<span id="cb18-31">    age <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">18</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> age <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"18-64"</span>,</span>
<span id="cb18-32">    age <span class="sc" style="color: #5E5E5E;">&gt;=</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&gt;= 65"</span></span>
<span id="cb18-33">  )</span>
<span id="cb18-34">}</span>
<span id="cb18-35"></span>
<span id="cb18-36"><span class="co" style="color: #5E5E5E;">#' Derive age group in an ADaM-style dataset</span></span>
<span id="cb18-37"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-38"><span class="co" style="color: #5E5E5E;">#' @param data A data frame containing patient records.</span></span>
<span id="cb18-39"><span class="co" style="color: #5E5E5E;">#' @param age_col Name of the numeric age column (default "AGE").</span></span>
<span id="cb18-40"><span class="co" style="color: #5E5E5E;">#' @param new_col Name of the derived column to create (default "AGEGR1").</span></span>
<span id="cb18-41"><span class="co" style="color: #5E5E5E;">#' @param classify Classification function to use (default classify_age_fixed).</span></span>
<span id="cb18-42"><span class="co" style="color: #5E5E5E;">#' @return Data frame with the derived age group column appended.</span></span>
<span id="cb18-43">derive_age_group <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb18-44">  data,</span>
<span id="cb18-45">  <span class="at" style="color: #657422;">age_col =</span> <span class="st" style="color: #20794D;">"AGE"</span>,</span>
<span id="cb18-46">  <span class="at" style="color: #657422;">new_col =</span> <span class="st" style="color: #20794D;">"AGEGR1"</span>,</span>
<span id="cb18-47">  <span class="at" style="color: #657422;">classify =</span> classify_age_fixed</span>
<span id="cb18-48">) {</span>
<span id="cb18-49">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.data.frame</span>(data)) {</span>
<span id="cb18-50">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`data` must be a data frame."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb18-51">  }</span>
<span id="cb18-52">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span>age_col <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">names</span>(data)) {</span>
<span id="cb18-53">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Column `%s` not found in `data`."</span>, age_col), <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb18-54">  }</span>
<span id="cb18-55">  data[[new_col]] <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">classify</span>(data[[age_col]])</span>
<span id="cb18-56">  data</span>
<span id="cb18-57">}</span>
<span id="cb18-58"></span>
<span id="cb18-59"><span class="co" style="color: #5E5E5E;">#' Convenience wrapper: derive age group using buggy classifier</span></span>
<span id="cb18-60"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-61"><span class="co" style="color: #5E5E5E;">#' @param data A data frame containing patient records.</span></span>
<span id="cb18-62"><span class="co" style="color: #5E5E5E;">#' @param age_col Name of the numeric age column.</span></span>
<span id="cb18-63"><span class="co" style="color: #5E5E5E;">#' @param new_col Name of the derived column to create.</span></span>
<span id="cb18-64"><span class="co" style="color: #5E5E5E;">#' @return Data frame with derived age group.</span></span>
<span id="cb18-65">derive_age_group_buggy <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data, <span class="at" style="color: #657422;">age_col =</span> <span class="st" style="color: #20794D;">"AGE"</span>, <span class="at" style="color: #657422;">new_col =</span> <span class="st" style="color: #20794D;">"AGEGR1"</span>) {</span>
<span id="cb18-66">  <span class="fu" style="color: #4758AB;">derive_age_group</span>(</span>
<span id="cb18-67">    data,</span>
<span id="cb18-68">    <span class="at" style="color: #657422;">age_col =</span> age_col,</span>
<span id="cb18-69">    <span class="at" style="color: #657422;">new_col =</span> new_col,</span>
<span id="cb18-70">    <span class="at" style="color: #657422;">classify =</span> classify_age_buggy</span>
<span id="cb18-71">  )</span>
<span id="cb18-72">}</span>
<span id="cb18-73"></span>
<span id="cb18-74"><span class="co" style="color: #5E5E5E;">#' Convenience wrapper: derive age group using fixed classifier</span></span>
<span id="cb18-75"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-76"><span class="co" style="color: #5E5E5E;">#' @param data A data frame containing patient records.</span></span>
<span id="cb18-77"><span class="co" style="color: #5E5E5E;">#' @param age_col Name of the numeric age column.</span></span>
<span id="cb18-78"><span class="co" style="color: #5E5E5E;">#' @param new_col Name of the derived column to create.</span></span>
<span id="cb18-79"><span class="co" style="color: #5E5E5E;">#' @return Data frame with derived age group.</span></span>
<span id="cb18-80">derive_age_group_fixed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data, <span class="at" style="color: #657422;">age_col =</span> <span class="st" style="color: #20794D;">"AGE"</span>, <span class="at" style="color: #657422;">new_col =</span> <span class="st" style="color: #20794D;">"AGEGR1"</span>) {</span>
<span id="cb18-81">  <span class="fu" style="color: #4758AB;">derive_age_group</span>(</span>
<span id="cb18-82">    data,</span>
<span id="cb18-83">    <span class="at" style="color: #657422;">age_col =</span> age_col,</span>
<span id="cb18-84">    <span class="at" style="color: #657422;">new_col =</span> new_col,</span>
<span id="cb18-85">    <span class="at" style="color: #657422;">classify =</span> classify_age_fixed</span>
<span id="cb18-86">  )</span>
<span id="cb18-87">}</span>
<span id="cb18-88"></span>
<span id="cb18-89"><span class="co" style="color: #5E5E5E;">#' Run property test for age classification</span></span>
<span id="cb18-90"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-91"><span class="co" style="color: #5E5E5E;">#' Invariant: every valid, non-missing integer age between 0 and 100 must produce</span></span>
<span id="cb18-92"><span class="co" style="color: #5E5E5E;">#' a non-missing classification belonging to the allowed clinical levels.</span></span>
<span id="cb18-93"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-94"><span class="co" style="color: #5E5E5E;">#' @param classify_fn Function under test.</span></span>
<span id="cb18-95"><span class="co" style="color: #5E5E5E;">#' @param tests Number of random iterations (default 100L).</span></span>
<span id="cb18-96"><span class="co" style="color: #5E5E5E;">#' @param seed Random seed for reproducible generation.</span></span>
<span id="cb18-97"><span class="co" style="color: #5E5E5E;">#' @return The expectation result from for_all().</span></span>
<span id="cb18-98">test_age_property <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(classify_fn, <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">100</span>L, <span class="at" style="color: #657422;">seed =</span> <span class="dv" style="color: #AD0000;">42</span>L) {</span>
<span id="cb18-99">  <span class="fu" style="color: #4758AB;">set.seed</span>(seed)</span>
<span id="cb18-100">  allowed_levels <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"&lt; 18"</span>, <span class="st" style="color: #20794D;">"18-64"</span>, <span class="st" style="color: #20794D;">"&gt;= 65"</span>)</span>
<span id="cb18-101">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb18-102">    <span class="at" style="color: #657422;">age =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">100</span>L),</span>
<span id="cb18-103">    <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(age) {</span>
<span id="cb18-104">      res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">classify_fn</span>(age)</span>
<span id="cb18-105">      testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(res)))</span>
<span id="cb18-106">      testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(res <span class="sc" style="color: #5E5E5E;">%in%</span> allowed_levels))</span>
<span id="cb18-107">    },</span>
<span id="cb18-108">    <span class="at" style="color: #657422;">tests =</span> tests</span>
<span id="cb18-109">  )</span>
<span id="cb18-110">}</span>
<span id="cb18-111"></span>
<span id="cb18-112"><span class="co" style="color: #5E5E5E;">#' Run property test for tabular derivation</span></span>
<span id="cb18-113"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-114"><span class="co" style="color: #5E5E5E;">#' Invariants:</span></span>
<span id="cb18-115"><span class="co" style="color: #5E5E5E;">#' 1. Row count is preserved: nrow(result) == nrow(data)</span></span>
<span id="cb18-116"><span class="co" style="color: #5E5E5E;">#' 2. Completeness: is.na(result$AGEGR1) == is.na(data$AGE)</span></span>
<span id="cb18-117"><span class="co" style="color: #5E5E5E;">#' 3. Domain: all non-NA derived values belong to the allowed levels</span></span>
<span id="cb18-118"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb18-119"><span class="co" style="color: #5E5E5E;">#' @param derive_fn Derivation function under test.</span></span>
<span id="cb18-120"><span class="co" style="color: #5E5E5E;">#' @param tests Number of random iterations (default 100L).</span></span>
<span id="cb18-121"><span class="co" style="color: #5E5E5E;">#' @param seed Random seed for reproducible generation.</span></span>
<span id="cb18-122"><span class="co" style="color: #5E5E5E;">#' @return The expectation result from for_all().</span></span>
<span id="cb18-123">test_derivation_property <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(derive_fn, <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">100</span>L, <span class="at" style="color: #657422;">seed =</span> <span class="dv" style="color: #AD0000;">42</span>L) {</span>
<span id="cb18-124">  <span class="fu" style="color: #4758AB;">set.seed</span>(seed)</span>
<span id="cb18-125">  allowed_levels <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"&lt; 18"</span>, <span class="st" style="color: #20794D;">"18-64"</span>, <span class="st" style="color: #20794D;">"&gt;= 65"</span>)</span>
<span id="cb18-126">  quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">for_all</span>(</span>
<span id="cb18-127">    <span class="at" style="color: #657422;">df =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">data_frame_</span>(</span>
<span id="cb18-128">      <span class="at" style="color: #657422;">AGE =</span> quickcheck<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">integer_bounded</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">100</span>L, <span class="at" style="color: #657422;">any_na =</span> <span class="cn" style="color: #8f5902;">FALSE</span>),</span>
<span id="cb18-129">      <span class="at" style="color: #657422;">rows =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="dv" style="color: #AD0000;">0</span>L, <span class="dv" style="color: #AD0000;">25</span>L)</span>
<span id="cb18-130">    ),</span>
<span id="cb18-131">    <span class="at" style="color: #657422;">property =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(df) {</span>
<span id="cb18-132">      res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">derive_fn</span>(df)</span>
<span id="cb18-133">      testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">nrow</span>(res), <span class="fu" style="color: #4758AB;">nrow</span>(df))</span>
<span id="cb18-134">      testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">is.na</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1), <span class="fu" style="color: #4758AB;">is.na</span>(df<span class="sc" style="color: #5E5E5E;">$</span>AGE))</span>
<span id="cb18-135">      valid_vals <span class="ot" style="color: #003B4F;">&lt;-</span> res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(res<span class="sc" style="color: #5E5E5E;">$</span>AGEGR1)]</span>
<span id="cb18-136">      testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">all</span>(valid_vals <span class="sc" style="color: #5E5E5E;">%in%</span> allowed_levels))</span>
<span id="cb18-137">    },</span>
<span id="cb18-138">    <span class="at" style="color: #657422;">tests =</span> tests</span>
<span id="cb18-139">  )</span>
<span id="cb18-140">}</span>
<span id="cb18-141"></span>
<span id="cb18-142"><span class="co" style="color: #5E5E5E;"># Run demo when executed as a standalone script</span></span>
<span id="cb18-143"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb18-144">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-145">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Step 1: Testing classify_age_buggy() with quickcheck</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-146">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-147">  <span class="fu" style="color: #4758AB;">tryCatch</span>(</span>
<span id="cb18-148">    <span class="fu" style="color: #4758AB;">test_age_property</span>(classify_age_buggy, <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">100</span>L, <span class="at" style="color: #657422;">seed =</span> <span class="dv" style="color: #AD0000;">42</span>L),</span>
<span id="cb18-149">    <span class="at" style="color: #657422;">error =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(e) {</span>
<span id="cb18-150">      <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Caught property failure:</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, <span class="fu" style="color: #4758AB;">conditionMessage</span>(e), <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-151">    }</span>
<span id="cb18-152">  )</span>
<span id="cb18-153"></span>
<span id="cb18-154">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-155">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Step 2: Testing classify_age_fixed() with quickcheck</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-156">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-157">  fixed_res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">test_age_property</span>(classify_age_fixed, <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">100</span>L, <span class="at" style="color: #657422;">seed =</span> <span class="dv" style="color: #AD0000;">42</span>L)</span>
<span id="cb18-158">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Result:"</span>, <span class="fu" style="color: #4758AB;">class</span>(fixed_res)[<span class="dv" style="color: #AD0000;">1</span>], <span class="st" style="color: #20794D;">"(passed all 100 random tests)</span><span class="sc" style="color: #5E5E5E;">\n\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-159"></span>
<span id="cb18-160">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-161">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Step 3: Testing derive_age_group_fixed() on random data frames</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-162">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"=======================================================</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-163">  df_res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">test_derivation_property</span>(</span>
<span id="cb18-164">    derive_age_group_fixed,</span>
<span id="cb18-165">    <span class="at" style="color: #657422;">tests =</span> <span class="dv" style="color: #AD0000;">100</span>L,</span>
<span id="cb18-166">    <span class="at" style="color: #657422;">seed =</span> <span class="dv" style="color: #AD0000;">42</span>L</span>
<span id="cb18-167">  )</span>
<span id="cb18-168">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Result:"</span>, <span class="fu" style="color: #4758AB;">class</span>(df_res)[<span class="dv" style="color: #AD0000;">1</span>], <span class="st" style="color: #20794D;">"(all tabular invariants hold)</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb18-169">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>quickcheck</strong>: <a href="https://cran.r-project.org/package=quickcheck">CRAN</a></li>
<li><strong>hedgehog</strong>: <a href="https://cran.r-project.org/package=hedgehog">CRAN</a></li>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>withr</strong>: <a href="https://withr.r-lib.org/">withr.r-lib.org</a></li>
<li><strong>dplyr</strong>: <a href="https://dplyr.tidyverse.org/">dplyr.tidyverse.org</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
</ul>
<p><strong>Property-based testing outside R</strong></p>
<ul>
<li><strong>QuickCheck</strong> (Haskell; Claessen and Hughes, 2000): <a href="https://hackage.haskell.org/package/QuickCheck">hackage.haskell.org/package/QuickCheck</a></li>
<li><strong>Hypothesis</strong> (Python): <a href="https://hypothesis.readthedocs.io/">hypothesis.readthedocs.io</a></li>
<li><strong>fast-check</strong> (JavaScript/TypeScript): <a href="https://fast-check.dev/">fast-check.dev</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-series-nav__series">Testing series · part 6 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 5</span><span class="site-related-card__title">End-to-end Shiny tests with shinytest2</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 7</span><span class="site-related-card__title">Coverage and tests as evidence</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/index.html" class="site-link-row" title="Why independent programming exists in clinical reporting, how risk-based QC structures verification tiers, and how to reconcile datasets and results in R with diffdf."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">QC and double programming with {diffdf}</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/index.html" class="site-link-row" title="Which R packages cover each stage of clinical reporting, from raw data to SDTM, ADaM, TFLs and submission files, and how the stages connect."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">The clinical reporting pipeline in R</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html" class="site-link-row" title="How to build, manipulate, and quality-control Analysis Results Data (ARD) in R with cards and cardx, decoupling computations from presentation."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Analysis Results Data in R with {cards} and {cardx}</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/property-based-testing/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Releases &amp; changelogs</title>
  <link>https://insightsurge-dev.web.app/posts/releases-changelogs/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="why-bother" class="level2">
<h2 class="anchored" data-anchor-id="why-bother">Why bother</h2>
<p>A release answers three questions: <strong>what changed</strong> (NEWS/CHANGELOG), <strong>how big was the change</strong> (the version number), and <strong>what exact code is it</strong> (a git tag). In GxP work a release is also what gets assessed and deployed, so the release notes feed your change-control and validation records.</p>
</section>
<section id="semantic-versioning-in-one-table" class="level2">
<h2 class="anchored" data-anchor-id="semantic-versioning-in-one-table">Semantic versioning in one table</h2>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Bump</th>
<th>When</th>
<th>R package example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>major</strong> <code>2.0.0</code></td>
<td>Existing code can break</td>
<td>Removed <code>km_plot(risk = )</code>; required R ≥ 4.3</td>
</tr>
<tr class="even">
<td><strong>minor</strong> <code>1.3.0</code></td>
<td>New features, nothing breaks</td>
<td>New <code>forest_plot()</code></td>
</tr>
<tr class="odd">
<td><strong>patch</strong> <code>1.2.1</code></td>
<td>Bug fixes only</td>
<td><code>read_adsl()</code> keeps labels again</td>
</tr>
</tbody>
</table>
</div>
<p>R adds a development convention: between releases the version is <code>x.y.z.9000</code> (<code>usethis::use_dev_version()</code>), so a bug report’s <code>sessionInfo()</code> shows the code wasn’t a release.</p>
<p>With <a href="https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/index.html">Conventional Commits</a>, the bump can be <strong>computed</strong>. <code>feat</code> → minor, <code>fix</code> → patch, <code>!</code> or <code>BREAKING CHANGE</code> → major.</p>
</section>
<section id="the-web-repo-way-release-please" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-release-please">The web-repo way: release-please</h2>
<p>Our website uses <a href="https://github.com/googleapis/release-please">release-please</a>. On every push to <code>main</code> it reads the new Conventional Commits and keeps <strong>one release PR</strong> open. That PR bumps <code>package.json</code>, writes <code>CHANGELOG.md</code> grouped by type, and lists what’s coming. Merging it tags the release and creates a GitHub Release.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="co" style="color: #5E5E5E;"># .github/workflows/release-please.yml</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">push</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">branches</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">main</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-6"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">contents</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> write</span></span>
<span id="cb1-7"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull-requests</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> write</span></span>
<span id="cb1-8"><span class="fu" style="color: #4758AB;">jobs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-9"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">release-please</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-10"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">runs-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ubuntu-latest</span></span>
<span id="cb1-11"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-12"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> googleapis/release-please-action@v5</span></span>
<span id="cb1-13"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-14"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">release-type</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> node</span></span></code></pre></div></div>
<p>What we observed:</p>
<ul>
<li>A <code>chore:</code> commit opened <strong>no</strong> release PR. Only <code>feat</code>, <code>fix</code> and breaking changes trigger one.</li>
<li>The repo setting <em>Allow GitHub Actions to create and approve pull requests</em> must be on.</li>
<li>According to GitHub’s docs, PRs opened with the default <code>GITHUB_TOKEN</code> don’t trigger other workflows, so CI won’t run on the release PR unless you use a separate token.</li>
</ul>
<p><strong>For R, release-please doesn’t fit.</strong> Its documented strategies cover Node, Python, Rust, Java, Go and others, but not R. The generic <code>simple</code> strategy bumps a <code>version.txt</code>, which isn’t where R keeps its version (<code>DESCRIPTION</code>).</p>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<section id="usethis-the-manual-but-reliable-path" class="level3">
<h3 class="anchored" data-anchor-id="usethis-the-manual-but-reliable-path"><code>usethis</code>: the manual but reliable path</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_news_md</span>()                 <span class="co" style="color: #5E5E5E;"># once: create NEWS.md</span></span>
<span id="cb2-2"><span class="co" style="color: #5E5E5E;"># ... during development, add a bullet to NEWS.md in each user-facing PR ...</span></span>
<span id="cb2-3">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_release_issue</span>()           <span class="co" style="color: #5E5E5E;"># a GitHub issue with a release checklist</span></span>
<span id="cb2-4">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_version</span>(<span class="st" style="color: #20794D;">"minor"</span>)          <span class="co" style="color: #5E5E5E;"># bump DESCRIPTION + NEWS.md heading, commit</span></span>
<span id="cb2-5">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_github_release</span>()          <span class="co" style="color: #5E5E5E;"># tag + GitHub release from the NEWS.md section</span></span>
<span id="cb2-6">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_dev_version</span>()             <span class="co" style="color: #5E5E5E;"># back to x.y.z.9000</span></span></code></pre></div></div>
</section>
<section id="fledge-news.md-from-commit-messages" class="level3">
<h3 class="anchored" data-anchor-id="fledge-news.md-from-commit-messages"><code>fledge</code>: NEWS.md from commit messages</h3>
<p><a href="https://fledge.cynkra.com"><code>fledge</code></a> (cynkra) builds <code>NEWS.md</code> from your commit history, and optionally bumps <code>DESCRIPTION</code> and tags. Its README says that commits written in <strong>Conventional Commits</strong> syntax get <em>automatically grouped</em> into changelog sections (Bug Fixes, Documentation, …). That makes it a natural partner for <a href="https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/index.html">conventional commits</a>’ squash-merge PR titles.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">fledge<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">update_news</span>()      <span class="co" style="color: #5E5E5E;"># light use: add NEWS.md bullets from commits since the last version</span></span>
<span id="cb3-2">fledge<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">bump_version</span>()     <span class="co" style="color: #5E5E5E;"># full use: NEWS.md + dev version bump + tag, run regularly</span></span>
<span id="cb3-3">fledge<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">finalize_version</span>() <span class="co" style="color: #5E5E5E;"># after hand-editing NEWS.md</span></span></code></pre></div></div>
<p>At release time, follow the steps in <code>vignette("fledge")</code>.</p>
</section>
<section id="what-goes-in-news.md" class="level3">
<h3 class="anchored" data-anchor-id="what-goes-in-news.md">What goes in NEWS.md</h3>
<p>Write for <strong>users</strong>, not for the git log. Say what changed in behaviour, how to migrate, and link the issue:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb4-1"><span class="fu" style="color: #4758AB;"># clinreport 1.3.0</span></span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;">## New features</span></span>
<span id="cb4-4"><span class="ss" style="color: #20794D;">* </span><span class="in" style="color: #5E5E5E;">`forest_plot()`</span> draws subgroup forest plots from an ARD (#57).</span>
<span id="cb4-5"></span>
<span id="cb4-6"><span class="fu" style="color: #4758AB;">## Bug fixes</span></span>
<span id="cb4-7"><span class="ss" style="color: #20794D;">* </span><span class="in" style="color: #5E5E5E;">`read_adsl()`</span> keeps variable labels when reading <span class="in" style="color: #5E5E5E;">`.xpt`</span> files (#61).</span></code></pre></div></div>
</section>
</section>
<section id="tags-and-github-releases" class="level2">
<h2 class="anchored" data-anchor-id="tags-and-github-releases">Tags and GitHub Releases</h2>
<ul>
<li><strong>Tag</strong> every release (<code>v1.3.0</code>). <code>remotes::install_github("org/pkg@v1.3.0")</code> then installs exactly that code, and <code>renv.lock</code> can record it.</li>
<li>A <strong>GitHub Release</strong> attaches notes (and optionally the built tarball) to the tag.</li>
<li>For validation-ready deployments, the tag plus release notes plus CI results for that commit are your evidence of <em>what</em> was assessed.</li>
</ul>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Forgetting the dev version.</strong> A released <code>1.3.0</code> and a work-in-progress <code>1.3.0</code> look identical in <code>sessionInfo()</code>. Always <code>use_dev_version()</code> after releasing.</li>
<li><strong>Changelog written from the git log.</strong> “Merge branch…” is not a release note. Curate it.</li>
<li><strong>Breaking changes hidden in a patch.</strong> If users must change code, it’s a major bump. In 0.x packages, use at least a minor bump and say so loudly.</li>
<li><strong>Retagging.</strong> Never move a published tag. Release a new version instead.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards and tools</strong></p>
<ul>
<li><strong>Semantic Versioning</strong>: <a href="https://semver.org/">semver.org</a></li>
<li><strong>release-please</strong>: <a href="https://github.com/googleapis/release-please">github.com/googleapis/release-please</a></li>
<li><strong>PRs/workflow runs from <code>GITHUB_TOKEN</code> don’t trigger other workflows</strong>: <a href="https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow">GitHub Docs: Triggering a workflow</a></li>
<li><strong>“Allow GitHub Actions to create and approve pull requests” setting</strong>: <a href="https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository">GitHub Docs: Managing GitHub Actions settings for a repository</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>use_news_md()</code>, <code>use_release_issue()</code>, <code>use_version()</code>, <code>use_github_release()</code>, <code>use_dev_version()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
<li><strong>fledge</strong>: <a href="https://fledge.cynkra.com/">fledge.cynkra.com</a></li>
<li><strong>remotes</strong>: <a href="https://remotes.r-lib.org/">remotes.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist. Marked package-dependent usethis and fledge blocks as .norun.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 9 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/issue-forms-pr-templates/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 8</span><span class="site-related-card__title">Issue forms, PR templates, labels &amp; milestones</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 10</span><span class="site-related-card__title">Dependency updates, runtime pinning &amp; package vetting</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/r-submissions-pkglite/index.html" class="site-link-row" title="What the R Consortium R submission pilots to the FDA tested, and how {pkglite} packs R packages into plain text that an eCTD submission can carry."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">R in regulatory submissions and {pkglite}</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="site-link-row" title="How to evaluate open-source R packages for GxP clinical reporting using the R Validation Hub risk-based framework, riskmetric, and documented evidence."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Validation-ready R packages</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/introducing-mascot/index.html" class="site-link-row" title="The mascot package is now on CRAN: add mood-driven characters to Shiny apps and Quarto pages, with visible status text, speech bubbles, click menus and reduced-motion support."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">mascot is on CRAN: live, mood-driven mascots for Shiny and Quarto</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R packages</category>
  <category>GxP</category>
  <category>Git</category>
  <guid>https://insightsurge-dev.web.app/posts/releases-changelogs/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Repo hygiene files</title>
  <link>https://insightsurge-dev.web.app/posts/repo-hygiene-files/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="what-each-file-is-for" class="level2">
<h2 class="anchored" data-anchor-id="what-each-file-is-for">What each file is for</h2>
<p>GitHub recognises several files by name and surfaces them in the UI: on the repo home page, the <em>New issue</em> page, the <em>Security</em> tab, and next to the PR form. Each one answers a question that would otherwise become a message to you.</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>File</th>
<th>Answers</th>
<th>GitHub surfaces it</th>
<th>R helper</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>README</code></td>
<td>What is this, how do I install and use it?</td>
<td>Repo home</td>
<td><code>usethis::use_readme_rmd()</code> / <code>use_readme_md()</code></td>
</tr>
<tr class="even">
<td><code>LICENSE</code></td>
<td>May I use this?</td>
<td>License badge / sidebar</td>
<td><code>use_mit_license()</code>, <code>use_proprietary_license(copyright_holder)</code></td>
</tr>
<tr class="odd">
<td><code>CONTRIBUTING.md</code></td>
<td>How do I set up, branch, commit and get a PR merged?</td>
<td>Link on new issue/PR</td>
<td><code>use_tidy_contributing()</code></td>
</tr>
<tr class="even">
<td><code>SECURITY.md</code></td>
<td>How do I report a vulnerability privately?</td>
<td><em>Security</em> tab</td>
<td>— (write it)</td>
</tr>
<tr class="odd">
<td><code>CODE_OF_CONDUCT.md</code></td>
<td>How do we treat each other?</td>
<td>Community profile</td>
<td><code>use_code_of_conduct(contact)</code></td>
</tr>
<tr class="even">
<td><code>SUPPORT.md</code></td>
<td>Where do I ask questions?</td>
<td>Link on new issue</td>
<td><code>use_tidy_support()</code></td>
</tr>
<tr class="odd">
<td><code>.editorconfig</code></td>
<td>Indentation, line endings, final newline</td>
<td>Editors that support EditorConfig</td>
<td>—</td>
</tr>
<tr class="even">
<td><code>.gitignore</code> / <code>.Rbuildignore</code></td>
<td>What never goes into git / the tarball</td>
<td>—</td>
<td><code>use_git_ignore()</code>, <code>use_build_ignore()</code></td>
</tr>
</tbody>
</table>
</div>
<p>GitHub looks for the community files in the repo <strong>root</strong>, <strong><code>.github/</code></strong> or <strong><code>docs/</code></strong>. In R packages, prefer <code>.github/</code>, which stays out of the build with <code>use_build_ignore(".github")</code>.</p>
</section>
<section id="what-we-wrote-for-the-website" class="level2">
<h2 class="anchored" data-anchor-id="what-we-wrote-for-the-website">What we wrote for the website</h2>
<ul>
<li><strong>CONTRIBUTING.md:</strong> setup (<code>npm install</code> also installs hooks); the branch → Conventional Commit → PR → squash workflow; a table of every check, what it does and where it runs; how releases happen; and the ground rules (no client names or data, no secrets, ADRs for decisions).</li>
<li><strong>SECURITY.md:</strong> “don’t open a public issue”, how to reach the maintainers, a response target, and a link to the secrets standard.</li>
<li><strong>LICENSE:</strong> proprietary, all rights reserved (the repo is private company code).</li>
<li><strong>.editorconfig:</strong> UTF-8, LF line endings, 2-space indent, final newline, and trailing whitespace trimmed (except in Markdown, where two trailing spaces can mean a line break).</li>
<li><strong>.env.example:</strong> every environment variable name, with no values (<a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html">secrets management</a>).</li>
</ul>
</section>
<section id="the-r-version" class="level2">
<h2 class="anchored" data-anchor-id="the-r-version">The R version</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb1-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_readme_rmd</span>()                          <span class="co" style="color: #5E5E5E;"># README.Rmd -&gt; README.md (knit to update)</span></span>
<span id="cb1-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_proprietary_license</span>(<span class="st" style="color: #20794D;">"Acme Analytics"</span>) <span class="co" style="color: #5E5E5E;"># or use_mit_license() for open source</span></span>
<span id="cb1-3">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_tidy_github</span>()                         <span class="co" style="color: #5E5E5E;"># CONTRIBUTING, issue template, SUPPORT, CoC in .github/</span></span>
<span id="cb1-4">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_build_ignore</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">".github"</span>, <span class="st" style="color: #20794D;">".editorconfig"</span>))</span></code></pre></div></div>
<p>A CONTRIBUTING.md for an internal R package should at least say:</p>
<ul>
<li>how to get a working environment (<code>renv::restore()</code>, the R version, <code>precommit::use_precommit()</code>);</li>
<li>the <a href="https://insightsurge-dev.web.app/posts/git-workflow/index.html">branch/PR workflow</a> and the <a href="https://insightsurge-dev.web.app/posts/conventional-commits-pr-titles/index.html">PR-title convention</a>;</li>
<li>what CI checks and how to reproduce it locally (<code>devtools::check()</code>, <code>lintr::lint_package()</code>);</li>
<li>when to add a <code>NEWS.md</code> bullet (<a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html">releases &amp; changelogs</a>);</li>
<li>the data rule: <strong>synthetic or public data only</strong> in code, tests and issues.</li>
</ul>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>README.Rmd drift.</strong> Edit the <code>.Rmd</code>, knit, and commit both. The <code>readme-rmd-rendered</code> pre-commit hook (<a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html">pre-commit hooks, formatting &amp; linting</a>) catches it if you forget.</li>
<li><strong>Copy-pasted CONTRIBUTING from an open-source template</strong> that tells internal colleagues to fork. Tailor it.</li>
<li><strong>A SECURITY.md with no working contact</strong> is worse than none. Keep it current.</li>
<li><strong>Licence ambiguity</strong> on internal code. Say “proprietary” explicitly. No LICENSE file isn’t the same as a clear statement.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>GitHub</strong></p>
<ul>
<li><strong>Community health files (README, LICENSE, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT, SUPPORT)</strong>: <a href="https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/creating-a-default-community-health-file">GitHub Docs: Creating a default community health file</a></li>
<li><strong>About READMEs</strong>: <a href="https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-readmes">GitHub Docs</a></li>
<li><strong>Licensing a repository</strong>: <a href="https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/licensing-a-repository">GitHub Docs</a></li>
<li><strong>Adding a security policy (<code>SECURITY.md</code>)</strong>: <a href="https://docs.github.com/en/code-security/getting-started/adding-a-security-policy-to-your-repository">GitHub Docs</a></li>
<li><strong>Adding a code of conduct</strong>: <a href="https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/adding-a-code-of-conduct-to-your-project">GitHub Docs</a></li>
</ul>
<p><strong>Other</strong></p>
<ul>
<li><strong>EditorConfig</strong>: <a href="https://editorconfig.org/">editorconfig.org</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>use_readme_rmd()</code>, <code>use_mit_license()</code>, <code>use_proprietary_license()</code>, <code>use_tidy_github()</code>, <code>use_code_of_conduct()</code>, <code>use_tidy_support()</code>, <code>use_git_ignore()</code>, <code>use_build_ignore()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist. Marked package-dependent usethis block as .norun.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 13 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/adrs-and-evidence/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 12</span><span class="site-related-card__title">ADRs &amp; evidence: record decisions, verify docs</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/handoffs-agentic-context/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 14</span><span class="site-related-card__title">Handoffs &amp; agentic context</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/issue-forms-pr-templates/index.html" class="site-link-row" title="Use structured issue forms, PR templates, and labels to capture reproducible examples and review criteria up front."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Issue forms, PR templates, labels &amp; milestones</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/releases-changelogs/index.html" class="site-link-row" title="Adopt semantic versioning, readable changelogs, and annotated git tags to support change control."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Releases &amp; changelogs</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/index.html" class="site-link-row" title="Move reusable analysis helpers from sourced scripts into a minimal R package, and replace workspace pollution with the devtools::load_all() loop."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">From scripts to a package</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R packages</category>
  <category>Git</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/repo-hygiene-files/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Secret scanning with gitleaks</title>
  <link>https://insightsurge-dev.web.app/posts/secret-scanning/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Secrets end up in git through ordinary days, not carelessness:</p>
<ul>
<li><code>Sys.setenv(GITHUB_PAT = "ghp_…")</code> typed in the console, saved to <strong><code>.Rhistory</code></strong>, committed;</li>
<li>a project <strong><code>.Renviron</code></strong> committed along with everything else in <code>git add -A</code>;</li>
<li>a Quarto or R Markdown report that printed <code>Sys.getenv()</code> while debugging, saved in <strong><code>_freeze/</code></strong> or the rendered HTML;</li>
<li>a database connection string pasted into a script “just for now”.</li>
</ul>
<p>Once pushed, deleting the file <strong>does not remove the secret</strong>. It stays in history, in every clone and fork, and in GitHub’s references for PRs. We saw this ourselves: after deleting a test branch, its commit was still served by the GitHub API through the closed PR.</p>
<p><strong>The first response to a leak is to rotate the secret, not to rewrite history.</strong></p>
</section>
<section id="what-secret-scanning-does" class="level2">
<h2 class="anchored" data-anchor-id="what-secret-scanning-does">What secret scanning does</h2>
<p>A scanner reads diffs (and optionally the whole history) and matches them against a large built-in set of rules for known token formats. Examples are GitHub PATs (<code>ghp_…</code>), AWS keys, Google API keys and private-key headers. It also checks entropy, which catches random-looking strings. It then fails the build and points at the file and line.</p>
<p><a href="https://github.com/gitleaks/gitleaks">gitleaks</a> is the widely used open-source scanner. It is one Go binary with a GitHub Action and a pre-commit hook.</p>
</section>
<section id="the-web-repo-way-gitleaks-in-ci" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-gitleaks-in-ci">The web-repo way: gitleaks in CI</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="co" style="color: #5E5E5E;"># .github/workflows/gitleaks.yml</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;">on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull_request</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-4"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">push</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">branches</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">main</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb1-6"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-7"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">contents</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read</span></span>
<span id="cb1-8"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull-requests</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> write</span><span class="co" style="color: #5E5E5E;">          # lets it comment on the offending line</span></span>
<span id="cb1-9"><span class="fu" style="color: #4758AB;">jobs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-10"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">scan</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-11"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">runs-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ubuntu-latest</span></span>
<span id="cb1-12"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-13"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> actions/checkout@v7</span></span>
<span id="cb1-14"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-15"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">fetch-depth</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">0</span><span class="co" style="color: #5E5E5E;">        # scan the full history, not just the tip</span></span>
<span id="cb1-16"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> gitleaks/gitleaks-action@v3</span></span>
<span id="cb1-17"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">env</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-18"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">GITHUB_TOKEN</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ secrets.GITHUB_TOKEN }}</span></span>
<span id="cb1-19"><span class="co" style="color: #5E5E5E;">          # GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}   # organisation repos only</span></span></code></pre></div></div>
<p><strong>Licensing, checked in the action’s README (v3):</strong> repos on a <em>personal</em> account need no licence. Repos owned by an <em>organisation</em> need a free licence key from gitleaks.io, stored as the <code>GITLEAKS_LICENSE</code> secret.</p>
<p><strong>Proving it works.</strong> We planted a random, never-valid <code>ghp_</code> token in a throwaway PR. gitleaks failed with rule <code>github-pat</code> and pointed at the exact file. A clean PR passed. Run the same test once in every new repo (<a href="https://insightsurge-dev.web.app/posts/test-your-guardrails/index.html">test your guardrails</a>).</p>
</section>
<section id="why-not-githubs-built-in-secret-scanning" class="level2">
<h2 class="anchored" data-anchor-id="why-not-githubs-built-in-secret-scanning">Why not GitHub’s built-in secret scanning?</h2>
<p>GitHub’s own secret scanning and push protection are <strong>free on public repositories</strong>. On <strong>private</strong> repositories they need the paid <em>GitHub Secret Protection</em> add-on, according to GitHub’s docs at the time of writing. Most internal R packages and Shiny apps are private, so gitleaks in CI is the no-cost baseline. If your organisation already pays for Secret Protection, turn on push protection <em>as well</em>: it blocks the push itself.</p>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<section id="keep-the-usual-suspects-out-of-git" class="level3">
<h3 class="anchored" data-anchor-id="keep-the-usual-suspects-out-of-git">1. Keep the usual suspects out of git</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">git_vaccinate</span>()   <span class="co" style="color: #5E5E5E;"># user-level gitignore: .Rhistory, .Rdata, .httr-oauth, .Rproj.user, .DS_Store, .quarto</span></span></code></pre></div></div>
<div class="callout callout-style-default callout-warning callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Warning</span><code>git_vaccinate()</code> does not ignore <code>.Renviron</code>
</div>
</div>
<div class="callout-body-container callout-body">
<p>We checked the list it writes (<code>usethis</code> 3.1.0). <strong><code>.Renviron</code> isn’t on it</strong>, yet it’s the most likely file to hold a token (<a href="https://insightsurge-dev.web.app/posts/identity-isolation/index.html">identity and environment isolation</a>). Add it yourself, per project:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_git_ignore</span>(<span class="st" style="color: #20794D;">".Renviron"</span>)</span></code></pre></div></div>
</div>
</div>
<p>Better still, never type a secret in the console. Put it in the project <code>.Renviron</code> (<code>usethis::edit_r_environ(scope = "project")</code>, <a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html">secrets management</a>) and read it with <code>Sys.getenv()</code>. Then there’s nothing for <code>.Rhistory</code> to capture.</p>
</section>
<section id="add-the-ci-scan" class="level3">
<h3 class="anchored" data-anchor-id="add-the-ci-scan">2. Add the CI scan</h3>
<p>Copy <a href="https://insightsurge-dev.web.app/templates/github/workflows/gitleaks.yml"><code>templates/github/workflows/gitleaks.yml</code></a> to <code>.github/workflows/</code>. It needs nothing from R, so it works for packages, Shiny apps, Quarto sites and analysis repos alike.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full template: <code>gitleaks.yml</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># Drop into .github/workflows/. Scans the full git history of every PR and push.</span></span>
<span id="cb4-2"><span class="co" style="color: #5E5E5E;"># Personal-account repos need no licence. Organisation repos need a free</span></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;"># GITLEAKS_LICENSE secret from gitleaks.io (uncomment the line below).</span></span>
<span id="cb4-4"><span class="fu" style="color: #4758AB;">name</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> gitleaks</span></span>
<span id="cb4-5"></span>
<span id="cb4-6"><span class="fu" style="color: #4758AB;">on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-7"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull_request</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-8"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">push</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-9"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">branches</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="kw" style="color: #003B4F;
font-weight: bold;">[</span><span class="at" style="color: #657422;">main</span><span class="kw" style="color: #003B4F;
font-weight: bold;">]</span></span>
<span id="cb4-10"></span>
<span id="cb4-11"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-12"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">contents</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> read</span></span>
<span id="cb4-13"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">pull-requests</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> write</span><span class="co" style="color: #5E5E5E;">   # lets the action comment on the offending line</span></span>
<span id="cb4-14"></span>
<span id="cb4-15"><span class="fu" style="color: #4758AB;">jobs</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-16"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">scan</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-17"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">runs-on</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ubuntu-latest</span></span>
<span id="cb4-18"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-19"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> actions/checkout@v7</span></span>
<span id="cb4-20"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-21"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">fetch-depth</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> </span><span class="dv" style="color: #AD0000;">0</span><span class="co" style="color: #5E5E5E;">   # full history, not just the latest commit</span></span>
<span id="cb4-22"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> gitleaks/gitleaks-action@v3</span></span>
<span id="cb4-23"><span class="at" style="color: #657422;">        </span><span class="fu" style="color: #4758AB;">env</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb4-24"><span class="at" style="color: #657422;">          </span><span class="fu" style="color: #4758AB;">GITHUB_TOKEN</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ secrets.GITHUB_TOKEN }}</span></span>
<span id="cb4-25"><span class="co" style="color: #5E5E5E;">          # GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}</span></span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="scan-before-the-commit-exists" class="level3">
<h3 class="anchored" data-anchor-id="scan-before-the-commit-exists">3. Scan before the commit exists</h3>
<p>CI catches a leak <strong>after</strong> it has reached GitHub. We saw that first-hand: our initial pre-commit hook only formatted code, so a planted test token passed pre-commit and was only caught once it reached CI.</p>
<p>To close this gap before commits leave your laptop:</p>
<ul>
<li><strong>In npm/JavaScript repos:</strong> We use <strong>secretlint</strong> configured via <code>lint-staged</code> (<code>"*" : ["secretlint --maskSecrets"]</code>) with <code>@secretlint/secretlint-rule-preset-recommend</code> in <code>.secretlintrc.json</code>. In our probe, staging a fake <code>ghp_</code> token was blocked immediately before the commit existed (<code>[GITHUB_TOKEN] found GitHub Token</code>, masked).</li>
<li><strong>In R repos:</strong> gitleaks ships a hook for the <a href="https://pre-commit.com">pre-commit</a> framework, which R users often run via the <a href="https://lorenzwalthert.github.io/precommit/"><code>precommit</code></a> package:</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># .pre-commit-config.yaml</span></span>
<span id="cb5-2"><span class="fu" style="color: #4758AB;">repos</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-3"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">repo</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> https://github.com/gitleaks/gitleaks</span></span>
<span id="cb5-4"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">rev</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> v8.30.1</span></span>
<span id="cb5-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">hooks</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb5-6"><span class="at" style="color: #657422;">      </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">id</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> gitleaks</span><span class="co" style="color: #5E5E5E;">        # runs: gitleaks git --pre-commit --redact --staged</span></span></code></pre></div></div>
<p>The <code>gitleaks</code> hook builds gitleaks from source with Go (or <code>gitleaks-docker</code> uses a container). Whichever local hook you use, <strong>CI remains the gate</strong>.</p>
</section>
</section>
<section id="false-positives" class="level2">
<h2 class="anchored" data-anchor-id="false-positives">False positives</h2>
<p>Test fixtures sometimes contain things that <em>look</em> like secrets. Two escape hatches, both reviewable in a PR:</p>
<ul>
<li>an inline <code>#gitleaks:allow</code> comment on that line;</li>
<li>a <code>.gitleaksignore</code> file listing the finding’s fingerprint.</li>
</ul>
<p>Never “fix” a finding by disabling the workflow.</p>
</section>
<section id="if-it-fires-on-a-real-secret" class="level2">
<h2 class="anchored" data-anchor-id="if-it-fires-on-a-real-secret">If it fires on a real secret</h2>
<ol type="1">
<li><strong>Rotate or revoke it at the source now.</strong> Assume it’s compromised.</li>
<li>Replace the value wherever it’s legitimately used (<code>.Renviron</code>, Connect env vars, Secret Manager).</li>
<li>Remove it from the code in a normal PR.</li>
<li>Record what leaked, when, and what you rotated. In GxP terms this is a deviation with a CAPA.</li>
</ol>
<p>Rewriting history is optional clean-up. It doesn’t undo the exposure.</p>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Tools</strong></p>
<ul>
<li><strong>gitleaks</strong>: <a href="https://github.com/gitleaks/gitleaks">github.com/gitleaks/gitleaks</a></li>
<li><strong>gitleaks-action licensing (free for personal accounts, licence key for organisations)</strong>: <a href="https://github.com/gitleaks/gitleaks-action">github.com/gitleaks/gitleaks-action</a></li>
<li><strong>secretlint</strong>: <a href="https://github.com/secretlint/secretlint">github.com/secretlint/secretlint</a></li>
<li><strong>pre-commit framework</strong>: <a href="https://pre-commit.com/">pre-commit.com</a></li>
<li><strong>precommit</strong> (R): <a href="https://lorenzwalthert.github.io/precommit/">lorenzwalthert.github.io/precommit</a></li>
</ul>
<p><strong>GitHub’s built-in scanning</strong></p>
<ul>
<li><strong>About secret scanning</strong>: <a href="https://docs.github.com/en/code-security/secret-scanning/introduction/about-secret-scanning">GitHub Docs</a></li>
<li><strong>About push protection</strong>: <a href="https://docs.github.com/en/code-security/secret-scanning/introduction/about-push-protection">GitHub Docs</a></li>
<li><strong>GitHub Secret Protection pricing (free on public repos, paid add-on on private repos)</strong>: <a href="https://docs.github.com/en/code-security/securing-your-organization/understanding-your-organizations-exposure-to-leaked-secrets/choosing-github-secret-protection">GitHub Docs: Choosing GitHub Secret Protection</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>git_vaccinate()</code>, <code>use_git_ignore()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Closed the pre-commit gap identified during initial probe testing in our npm-based repo using <strong>secretlint</strong> (<code>secretlint --maskSecrets</code> via <code>lint-staged</code> with <code>@secretlint/secretlint-rule-preset-recommend</code>). A re-probe with a fake <code>ghp_</code> token was blocked immediately before commit creation (<code>[GITHUB_TOKEN] found GitHub Token</code>, masked), while R repos continue using the gitleaks pre-commit hook.</li>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist. Marked project-dependent usethis block as .norun.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Linked every template file and showed it on the page.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 6 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/ci-github-actions/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 5</span><span class="site-related-card__title">CI with GitHub Actions</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/secrets-management/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 7</span><span class="site-related-card__title">Secrets management</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/index.html" class="site-link-row" title="Use OpenID Connect and Google Cloud Workload Identity Federation to authenticate CI pipelines without long-lived JSON keys."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Keyless deploys: let CI prove who it is (OIDC)</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/index.html" class="site-link-row" title="Drive Shiny applications end to end with shinytest2 and headless Chrome, testing real browser rendering, user input sequences, and reactive outputs."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">End-to-end Shiny tests with shinytest2</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Security</category>
  <category>R</category>
  <category>CI/CD</category>
  <guid>https://insightsurge-dev.web.app/posts/secret-scanning/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Secrets management</title>
  <link>https://insightsurge-dev.web.app/posts/secrets-management/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-principle" class="level2">
<h2 class="anchored" data-anchor-id="the-principle">The principle</h2>
<p>A <strong>secret</strong> is anything that grants access: a database password, an API token, a PAT, a service-account key. The rule that makes everything else simple:</p>
<blockquote class="blockquote">
<p><strong>The <em>name</em> of a secret lives in git. The <em>value</em> never does.</strong></p>
</blockquote>
<p>Code asks for <code>Sys.getenv("DB_PASSWORD")</code>. <em>Where</em> the value comes from depends on where the code runs, and none of those places is the repo. <a href="https://insightsurge-dev.web.app/posts/secret-scanning/index.html">Secret scanning</a> is the safety net for when this rule slips; this post is about not needing the net.</p>
</section>
<section id="where-values-live" class="level2">
<h2 class="anchored" data-anchor-id="where-values-live">Where values live</h2>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Where the code runs</th>
<th>Store</th>
<th>How code reads it</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Your laptop</td>
<td>Project <code>.Renviron</code> (gitignored), or the OS keychain</td>
<td><code>Sys.getenv()</code>, <code>keyring::key_get()</code></td>
</tr>
<tr class="even">
<td>GitHub Actions</td>
<td>Repository/environment <strong>secrets</strong> (<code>gh secret set</code>)</td>
<td><code>${{ secrets.NAME }}</code>; masked in logs</td>
</tr>
<tr class="odd">
<td>Posit Connect</td>
<td>Content <strong>Vars</strong> (environment variables)</td>
<td><code>Sys.getenv()</code></td>
</tr>
<tr class="even">
<td>shinyapps.io / Connect via rsconnect</td>
<td><code>rsconnect::deployApp(envVars = c("DB_PASSWORD"))</code> sends your local values</td>
<td><code>Sys.getenv()</code></td>
</tr>
<tr class="odd">
<td>Google Cloud</td>
<td><strong>Secret Manager</strong>, referenced by name</td>
<td>Injected as env vars at runtime</td>
</tr>
</tbody>
</table>
</div>
</section>
<section id="the-web-repo-way-what-we-did" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way-what-we-did">The web-repo way (what we did)</h2>
<ul>
<li><p>The production vault is <strong>GCP Secret Manager</strong>. The app config (<code>apphosting.yaml</code>) names the secret, and the platform injects the value at runtime:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb1-1"><span class="fu" style="color: #4758AB;">env</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">variable</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> CONTACT_NOTIFY_TO</span></span>
<span id="cb1-3"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">secret</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> contactNotifyTo</span><span class="co" style="color: #5E5E5E;">      # a name, not a value</span></span></code></pre></div></div></li>
<li><p><strong><code>.env.example</code></strong> is committed, with every variable listed and no values. Real <code>.env*</code> files are gitignored.</p></li>
<li><p><strong><code>NEXT_PUBLIC_*</code> means public.</strong> Anything with that prefix is shipped to browsers, so it’s never a secret. In Shiny terms: anything sent to the UI (including <code>session$sendCustomMessage()</code> payloads) is public.</p></li>
<li><p><strong>No JSON service-account keys, ever.</strong> A key file is a password that never expires.</p></li>
</ul>
<section id="keyless-deploys-the-modern-default" class="level3">
<h3 class="anchored" data-anchor-id="keyless-deploys-the-modern-default">Keyless deploys: the modern default</h3>
<p>Our playbook deploys from GitHub Actions to Firebase Hosting <strong>without any secret at all</strong>. GitHub issues each workflow run a short-lived OIDC token. Google Cloud’s <strong>Workload Identity Federation</strong> trusts tokens from <em>one specific repo</em> (pinned by numeric repo ID) and lets it act as a deploy-only service account for the length of the job:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb2-1"><span class="fu" style="color: #4758AB;">permissions</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">id-token</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> write</span></span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;">steps</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-4"><span class="at" style="color: #657422;">  </span><span class="kw" style="color: #003B4F;
font-weight: bold;">-</span><span class="at" style="color: #657422;"> </span><span class="fu" style="color: #4758AB;">uses</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> google-github-actions/auth@v3</span></span>
<span id="cb2-5"><span class="at" style="color: #657422;">    </span><span class="fu" style="color: #4758AB;">with</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb2-6"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">workload_identity_provider</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }}</span></span>
<span id="cb2-7"><span class="at" style="color: #657422;">      </span><span class="fu" style="color: #4758AB;">service_account</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> ${{ vars.GCP_SERVICE_ACCOUNT }}</span></span></code></pre></div></div>
<p>The provider and service-account names are <em>identifiers</em>, so they’re stored as plain repository <strong>variables</strong>, not secrets. Firebase’s own deploy action asks for a JSON key, which is why we used this route with the Firebase CLI instead. AWS and Azure support the same OIDC pattern, so ask your platform team whether your cloud or Connect setup does too.</p>
</section>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<section id="local-.renviron-with-a-committed-example" class="level3">
<h3 class="anchored" data-anchor-id="local-.renviron-with-a-committed-example">Local: <code>.Renviron</code> with a committed example</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">edit_r_environ</span>(<span class="at" style="color: #657422;">scope =</span> <span class="st" style="color: #20794D;">"project"</span>)   <span class="co" style="color: #5E5E5E;"># creates/opens ./.Renviron</span></span>
<span id="cb3-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_git_ignore</span>(<span class="st" style="color: #20794D;">".Renviron"</span>)         <span class="co" style="color: #5E5E5E;"># git_vaccinate() does NOT cover it (see secret scanning)</span></span></code></pre></div></div>
<p>Commit a <strong><code>.Renviron.example</code></strong> with the names and no values. It’s the R twin of <code>.env.example</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># .Renviron.example: copy to .Renviron and fill in</span></span>
<span id="cb4-2"><span class="va" style="color: #111111;">DB_HOST</span><span class="op" style="color: #5E5E5E;">=</span></span>
<span id="cb4-3"><span class="va" style="color: #111111;">DB_USER</span><span class="op" style="color: #5E5E5E;">=</span></span>
<span id="cb4-4"><span class="va" style="color: #111111;">DB_PASSWORD</span><span class="op" style="color: #5E5E5E;">=</span></span>
<span id="cb4-5"><span class="va" style="color: #111111;">R_CONFIG_ACTIVE</span><span class="op" style="color: #5E5E5E;">=</span>default</span></code></pre></div></div>
<p>Remember from <a href="https://insightsurge-dev.web.app/posts/identity-isolation/index.html">identity and environment isolation</a>: a project <code>.Renviron</code> <strong>replaces</strong> <code>~/.Renviron</code>. It doesn’t add to it.</p>
</section>
<section id="keychain-keyring" class="level3">
<h3 class="anchored" data-anchor-id="keychain-keyring">Keychain: <code>keyring</code></h3>
<p>For secrets you’d rather not keep in a plain file:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1">keyring<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">key_set</span>(<span class="st" style="color: #20794D;">"warehouse-db"</span>, <span class="at" style="color: #657422;">username =</span> <span class="st" style="color: #20794D;">"analyst"</span>)   <span class="co" style="color: #5E5E5E;"># prompts; stored in macOS Keychain / Windows Credential Store / Secret Service</span></span>
<span id="cb5-2">keyring<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">key_get</span>(<span class="st" style="color: #20794D;">"warehouse-db"</span>, <span class="at" style="color: #657422;">username =</span> <span class="st" style="color: #20794D;">"analyst"</span>)</span></code></pre></div></div>
</section>
<section id="environments-config" class="level3">
<h3 class="anchored" data-anchor-id="environments-config">Environments: <code>config</code></h3>
<p><code>config</code> picks a block from <code>config.yml</code> using <code>R_CONFIG_ACTIVE</code>, and <code>!expr</code> pulls values from the environment, so the YAML file itself holds no secrets:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb6-1"><span class="fu" style="color: #4758AB;">default</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb6-2"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">db_host</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> localhost</span></span>
<span id="cb6-3"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">db_password</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> !expr Sys.getenv("DB_PASSWORD")</span></span>
<span id="cb6-4"><span class="fu" style="color: #4758AB;">rsconnect</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span></span>
<span id="cb6-5"><span class="at" style="color: #657422;">  </span><span class="fu" style="color: #4758AB;">db_host</span><span class="kw" style="color: #003B4F;
font-weight: bold;">:</span><span class="at" style="color: #657422;"> warehouse.internal</span></span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1">cfg <span class="ot" style="color: #003B4F;">&lt;-</span> config<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">get</span>()</span>
<span id="cb7-2">DBI<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">dbConnect</span>(odbc<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">odbc</span>(), <span class="at" style="color: #657422;">server =</span> cfg<span class="sc" style="color: #5E5E5E;">$</span>db_host, <span class="at" style="color: #657422;">pwd =</span> cfg<span class="sc" style="color: #5E5E5E;">$</span>db_password)</span></code></pre></div></div>
<p>Posit Connect sets <code>R_CONFIG_ACTIVE=rsconnect</code>, according to <code>config</code>’s own documentation, so the same code picks the right block on deploy without any <code>if</code>.</p>
</section>
<section id="deploying" class="level3">
<h3 class="anchored" data-anchor-id="deploying">Deploying</h3>
<ul>
<li><strong>Posit Connect:</strong> set values in the content’s <em>Vars</em> panel, or pass <code>envVars = c("DB_PASSWORD")</code> to <code>rsconnect::deployApp()</code>, which sends your local values. Leaving a name out of <code>envVars</code> leaves the value on the server unchanged.</li>
<li><strong>GitHub Actions:</strong> <code>gh secret set DB_PASSWORD</code>, then <code>env: DB_PASSWORD: ${{ secrets.DB_PASSWORD }}</code>. Secrets aren’t passed to workflows triggered by PRs from forks.</li>
</ul>
</section>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Printing a secret while debugging.</strong> <code>print(Sys.getenv())</code> ends up in logs and rendered reports.</li>
<li><strong>Secrets as function defaults.</strong> <code>connect &lt;- function(pwd = "hunter2")</code> is a secret in git.</li>
<li><strong>One shared “team” token.</strong> Use per-person or per-service credentials, so you can revoke one without breaking all.</li>
<li><strong>Rotation nobody owns.</strong> Write down who rotates what, and how often. Keyless auth removes most of this.</li>
</ul>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Vaults and platforms</strong></p>
<ul>
<li><strong>GCP Secret Manager</strong>: <a href="https://cloud.google.com/secret-manager/docs">cloud.google.com/secret-manager/docs</a></li>
<li><strong>Workload Identity Federation</strong>: <a href="https://docs.cloud.google.com/iam/docs/workload-identity-federation">Google Cloud IAM docs</a></li>
<li><strong>google-github-actions/auth</strong>: <a href="https://github.com/google-github-actions/auth">github.com/google-github-actions/auth</a></li>
<li><strong>Posit Connect content Vars</strong>: <a href="https://docs.posit.co/connect/user/content-settings/">docs.posit.co/connect</a></li>
<li><strong>GitHub Actions secrets (<code>gh secret set</code>)</strong>: <a href="https://cli.github.com/manual/gh_secret_set">cli.github.com/manual/gh_secret_set</a></li>
<li><strong><code>NEXT_PUBLIC_*</code> environment variables are shipped to the browser</strong>: <a href="https://nextjs.org/docs/app/guides/environment-variables">Next.js Docs: Environment Variables</a></li>
</ul>
<p><strong>R package documentation</strong></p>
<ul>
<li><strong>usethis</strong> (<code>edit_r_environ()</code>, <code>use_git_ignore()</code>): <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
<li><strong>keyring</strong>: <a href="https://keyring.r-lib.org/">keyring.r-lib.org</a></li>
<li><strong>config</strong>: <a href="https://rstudio.github.io/config/">rstudio.github.io/config</a></li>
<li><strong>config with Posit Connect (<code>R_CONFIG_ACTIVE=rsconnect</code>)</strong>: <a href="https://rstudio.github.io/config/articles/rsconnect.html">Using config with Posit Connect</a></li>
<li><strong>rsconnect</strong> (<code>deployApp(envVars = )</code>): <a href="https://rstudio.github.io/rsconnect/">rstudio.github.io/rsconnect</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist. Marked interactive and environment-dependent blocks as .norun.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 7 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/secret-scanning/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 6</span><span class="site-related-card__title">Secret scanning with gitleaks</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/issue-forms-pr-templates/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 8</span><span class="site-related-card__title">Issue forms, PR templates, labels &amp; milestones</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/index.html" class="site-link-row" title="Use OpenID Connect and Google Cloud Workload Identity Federation to authenticate CI pipelines without long-lived JSON keys."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Keyless deploys: let CI prove who it is (OIDC)</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/identity-isolation/index.html" class="site-link-row" title="Isolate git identities, SSH keys, and environment variables across personal, work, and client projects on one machine."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Identity &amp; environment isolation</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/quarto-firebase-previews/index.html" class="site-link-row" title="Deploy temporary Firebase Hosting preview channels on every pull request to review rendered Quarto sites before merging."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Deploy a Quarto site with a preview for every pull request</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Security</category>
  <category>R</category>
  <category>Shiny</category>
  <guid>https://insightsurge-dev.web.app/posts/secrets-management/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Snapshot tests for R output, tables and plots</title>
  <link>https://insightsurge-dev.web.app/posts/snapshot-tests/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>In <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html">the first post in this series</a>, we wrote unit tests with explicit assertions like <code>expect_equal()</code> and <code>expect_identical()</code>. When a function returns a scalar number, a vector, or a small data frame, writing the expected value by hand is straightforward.</p>
<p>That approach breaks down when the expected output is complex, multi-line, or visual:</p>
<ul>
<li><strong>Formatted console output:</strong> Pretty-printed tables, ASCII borders, and indented trees.</li>
<li><strong>Diagnostic messages and errors:</strong> Informational notices, warnings, and multi-line errors built with <a href="https://cli.r-lib.org/">{cli}</a>.</li>
<li><strong>Complex nested objects:</strong> Statistical models or nested lists where hand-writing expected structures requires pages of brittle assertions.</li>
<li><strong>Rendered clinical tables:</strong> Tabular reports produced by <a href="https://cran.r-project.org/package=rtables">{rtables}</a> with hierarchical column splits, statistics rows, and formatting templates.</li>
<li><strong>Graphical plots:</strong> Data visualisations produced with <a href="https://ggplot2.tidyverse.org/">{ggplot2}</a> or base graphics, where layout, margins, legends, and alignment matter.</li>
</ul>
<p>When teams test these with standard equality assertions, they either spend hours writing fragile string checks filled with escaped quotes and newlines, or write shallow assertions that check only the object class, leaving the rendered layout unprotected against regressions.</p>
<p>Snapshot tests (or golden tests) solve this dilemma. Instead of hand-coding expected results in test scripts, you capture reference output in a human-readable file managed by <a href="https://testthat.r-lib.org/">{testthat}</a>. When code changes, testthat compares the new output against the recorded snapshot and highlights differences line by line.</p>
<section id="when-to-use-snapshot-tests-and-when-not-to" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-snapshot-tests-and-when-not-to">When to use snapshot tests (and when not to)</h3>
<p>Snapshot tests are a specialised tool. Use them when:</p>
<ol type="1">
<li>The output is <strong>awkward to write by hand</strong>, such as printed console representations, multi-line error diagnostics, or graphical figures.</li>
<li>The primary value lies in <strong>human inspection</strong>, verifying that a table layout is legible or an error message is helpful.</li>
<li>You need <strong>regression protection</strong> across large objects where asserting individual elements would require excessive boilerplate.</li>
</ol>
<p>Do not use snapshot tests for:</p>
<ul>
<li><strong>Simple values:</strong> If you expect <code>2</code> or <code>"placebo"</code>, use <code>expect_equal()</code>. A snapshot adds file management overhead and obscures test intent.</li>
<li><strong>Noisy or volatile output:</strong> Text containing unseeded random values, timestamps, memory addresses, or temporary file paths will change on every run. Unless you scrub volatile tokens, snapshots generate false failures.</li>
<li><strong>Internal implementation details:</strong> Snapshot public interfaces and user-facing outputs, not internal data structures that change during routine refactoring.</li>
</ul>
</section>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In JavaScript and TypeScript repositories, frameworks such as Vitest and Jest make snapshot testing and visual regression a core part of development:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb1-1"><span class="co" style="color: #5E5E5E;">// src/components/summary-card.test.ts</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;">import</span> { describe<span class="op" style="color: #5E5E5E;">,</span> it<span class="op" style="color: #5E5E5E;">,</span> expect } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"vitest"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-3"><span class="im" style="color: #00769E;">import</span> { renderSummaryCard } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"./summary-card"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;">describe</span>(<span class="st" style="color: #20794D;">"renderSummaryCard"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-6">  <span class="fu" style="color: #4758AB;">it</span>(<span class="st" style="color: #20794D;">"renders clinical summary card correctly"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-7">    <span class="kw" style="color: #003B4F;
font-weight: bold;">const</span> card <span class="op" style="color: #5E5E5E;">=</span> <span class="fu" style="color: #4758AB;">renderSummaryCard</span>({ studyId<span class="op" style="color: #5E5E5E;">:</span> <span class="st" style="color: #20794D;">"STUDY-01"</span><span class="op" style="color: #5E5E5E;">,</span> enrolled<span class="op" style="color: #5E5E5E;">:</span> <span class="dv" style="color: #AD0000;">120</span> })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-8">    <span class="co" style="color: #5E5E5E;">// Serializes the DOM node to __snapshots__/summary-card.test.ts.snap</span></span>
<span id="cb1-9">    <span class="fu" style="color: #4758AB;">expect</span>(card)<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toMatchSnapshot</span>()<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-10">  })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-11">})<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<p>Web repositories rely on three fundamental patterns:</p>
<ol type="1">
<li><strong>Dedicated snapshot files:</strong> Vitest stores serialized representations in separate <code>.snap</code> files alongside tests (or inline via <code>toMatchInlineSnapshot()</code>).</li>
<li><strong>Reviewable diffs in pull requests:</strong> When a component’s markup changes, git records the diff in the snapshot file. Reviewers evaluate visual changes directly in the pull request.</li>
<li><strong>Visual regression testing:</strong> Tools like Playwright and Storybook capture pixel-by-pixel or vector snapshots of rendered web pages to catch CSS and layout regressions.</li>
</ol>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In R packages, <a href="https://testthat.r-lib.org/">{testthat}</a> (3rd edition) and <a href="https://vdiffr.r-lib.org/">{vdiffr}</a> provide the equivalent toolset for console output, structured data, whole files, and plots.</p>
<section id="console-output-messages-and-errors-expect_snapshot" class="level3">
<h3 class="anchored" data-anchor-id="console-output-messages-and-errors-expect_snapshot">1 · Console output, messages, and errors: <code>expect_snapshot()</code></h3>
<p><code>expect_snapshot()</code> evaluates an expression as if it were typed in the console. It captures standard output, printed representations, messages, warnings, and errors:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;"># tests/testthat/test-format_summary.R</span></span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"format_patient_summary() prints formatted console block"</span>, {</span>
<span id="cb2-4">  <span class="fu" style="color: #4758AB;">expect_snapshot</span>(</span>
<span id="cb2-5">    <span class="fu" style="color: #4758AB;">format_patient_summary</span>(<span class="at" style="color: #657422;">id =</span> <span class="st" style="color: #20794D;">"SUBJ-001"</span>, <span class="at" style="color: #657422;">age =</span> <span class="dv" style="color: #AD0000;">64</span>, <span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Placebo"</span>)</span>
<span id="cb2-6">  )</span>
<span id="cb2-7">})</span></code></pre></div></div>
<p>By default, an unexpected error inside <code>expect_snapshot()</code> causes the test to fail. To deliberately test and capture an error message, set <code>error = TRUE</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"validate_subject() rejects invalid identifiers"</span>, {</span>
<span id="cb3-2">  <span class="fu" style="color: #4758AB;">expect_snapshot</span>(</span>
<span id="cb3-3">    <span class="fu" style="color: #4758AB;">validate_subject</span>(<span class="st" style="color: #20794D;">"INVALID_ID"</span>),</span>
<span id="cb3-4">    <span class="at" style="color: #657422;">error =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb3-5">  )</span>
<span id="cb3-6">})</span></code></pre></div></div>
<p>With <code>error = TRUE</code>, testthat expects at least one expression to signal an error and records the message in the snapshot. If the expression executes without error, the expectation fails.</p>
</section>
<section id="serializing-structured-objects-expect_snapshot_value" class="level3">
<h3 class="anchored" data-anchor-id="serializing-structured-objects-expect_snapshot_value">2 · Serializing structured objects: <code>expect_snapshot_value()</code></h3>
<p>If you care about the return value of an object rather than its printed console representation, use <code>expect_snapshot_value()</code>. It serializes the object using one of four styles set by <code>style</code>:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>Style</th>
<th>Underlying mechanism</th>
<th>Strengths</th>
<th>Trade-offs</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>"json"</code></td>
<td><code>jsonlite::toJSON()</code></td>
<td>Clean, human-readable JSON</td>
<td>Best for lists, vectors, and simple objects</td>
</tr>
<tr class="even">
<td><code>"json2"</code></td>
<td><code>jsonlite::serializeJSON()</code></td>
<td>Preserves more R types and attributes</td>
<td>More verbose JSON syntax</td>
</tr>
<tr class="odd">
<td><code>"deparse"</code></td>
<td><code>base::deparse()</code></td>
<td>Depicts objects as valid R code</td>
<td>Can become unwieldy on nested objects</td>
</tr>
<tr class="even">
<td><code>"serialize"</code></td>
<td><code>base::serialize()</code> (base64)</td>
<td>Works for any R object</td>
<td>Opaque binary; unreadable in git diffs</td>
</tr>
</tbody>
</table>
</div>
<p>For nested parameter lists and summary structures, <code>"json"</code> produces the clearest diff in git:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"compute_demographics() returns expected parameter structure"</span>, {</span>
<span id="cb4-2">  res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">compute_demographics</span>(<span class="at" style="color: #657422;">study =</span> <span class="st" style="color: #20794D;">"STUDY-01"</span>)</span>
<span id="cb4-3">  <span class="fu" style="color: #4758AB;">expect_snapshot_value</span>(res, <span class="at" style="color: #657422;">style =</span> <span class="st" style="color: #20794D;">"json"</span>)</span>
<span id="cb4-4">})</span></code></pre></div></div>
<p><code>expect_snapshot_value()</code> also accepts a <code>tolerance</code> argument (default <code>testthat_tolerance()</code>, the same as <code>expect_equal()</code>), so tiny floating-point differences don’t trigger false alarms.</p>
</section>
<section id="whole-file-snapshots-expect_snapshot_file" class="level3">
<h3 class="anchored" data-anchor-id="whole-file-snapshots-expect_snapshot_file">3 · Whole-file snapshots: <code>expect_snapshot_file()</code></h3>
<p>When code generates output files on disk—such as CSV exports, generated reports, or standalone text documents—use <code>expect_snapshot_file()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"export_study_manifest() writes expected CSV output"</span>, {</span>
<span id="cb5-2">  manifest_path <span class="ot" style="color: #003B4F;">&lt;-</span> withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_tempfile</span>(<span class="at" style="color: #657422;">fileext =</span> <span class="st" style="color: #20794D;">".csv"</span>)</span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;">export_study_manifest</span>(manifest_path)</span>
<span id="cb5-4"></span>
<span id="cb5-5">  <span class="fu" style="color: #4758AB;">expect_snapshot_file</span>(</span>
<span id="cb5-6">    manifest_path,</span>
<span id="cb5-7">    <span class="at" style="color: #657422;">name =</span> <span class="st" style="color: #20794D;">"study_manifest.csv"</span>,</span>
<span id="cb5-8">    <span class="at" style="color: #657422;">compare =</span> compare_file_text</span>
<span id="cb5-9">  )</span>
<span id="cb5-10">})</span></code></pre></div></div>
<p><code>expect_snapshot_file()</code> stores reference files under <code>tests/testthat/_snaps/&lt;test&gt;/&lt;name&gt;</code>. By default it compares files line by line with <code>compare_file_text()</code> (ignoring Windows versus Unix line endings) only when <code>name</code> ends in <code>.r</code>, <code>.R</code>, <code>.Rmd</code>, <code>.md</code> or <code>.txt</code>; everything else, including <code>.csv</code> and <code>.json</code>, is compared byte by byte with <code>compare_file_binary()</code>. That’s why the example passes <code>compare = compare_file_text</code> for a CSV.</p>
</section>
<section id="where-snapshots-live-and-how-to-review-them" class="level3">
<h3 class="anchored" data-anchor-id="where-snapshots-live-and-how-to-review-them">4 · Where snapshots live and how to review them</h3>
<p>Snapshots live inside your package under <code>tests/testthat/_snaps/</code>:</p>
<ul>
<li>Standard snapshots for <code>test-demographics.R</code> live in <code>tests/testthat/_snaps/demographics.md</code>.</li>
<li>File snapshots created by <code>expect_snapshot_file()</code> live in <code>tests/testthat/_snaps/demographics/&lt;name&gt;</code>.</li>
<li>Environmental variants live in subdirectories such as <code>tests/testthat/_snaps/&lt;variant&gt;/demographics.md</code>.</li>
</ul>
<p>Snapshots are stored in human-readable Markdown:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb6-1"><span class="fu" style="color: #4758AB;"># format_patient_summary() prints formatted console block</span></span>
<span id="cb6-2"></span>
<span id="cb6-3"><span class="in" style="color: #5E5E5E;">    Code</span></span>
<span id="cb6-4"><span class="in" style="color: #5E5E5E;">      format_patient_summary(id = "SUBJ-001", age = 64, arm = "Placebo")</span></span>
<span id="cb6-5"><span class="in" style="color: #5E5E5E;">    Output</span></span>
<span id="cb6-6"><span class="in" style="color: #5E5E5E;">      Subject: SUBJ-001</span></span>
<span id="cb6-7"><span class="in" style="color: #5E5E5E;">      Age:     64</span></span>
<span id="cb6-8"><span class="in" style="color: #5E5E5E;">      Arm:     Placebo</span></span></code></pre></div></div>
<p>Each test starts with a level 1 heading (<code>#</code>), followed by the code and its recorded output indented by four spaces; several snapshots in one test are separated by <code>---</code>.</p>
<section id="committing-snapshots-to-version-control" class="level4">
<h4 class="anchored" data-anchor-id="committing-snapshots-to-version-control">Committing snapshots to version control</h4>
<p>Snapshot files <strong>must be committed to git</strong>. They are not ephemeral caches; they represent the recorded specification of your software’s expected output. Committing them ensures that every pull request displays an exact diff whenever output changes.</p>
</section>
<section id="reviewing-changes-locally" class="level4">
<h4 class="anchored" data-anchor-id="reviewing-changes-locally">Reviewing changes locally</h4>
<p>When a snapshot fails because output has intentionally changed, testthat provides two tools:</p>
<ul>
<li><code>testthat::snapshot_review()</code>: opens a small Shiny app that shows each changed snapshot (text diffs, or old and new images) so you can accept or skip it.</li>
<li><code>testthat::snapshot_accept("demographics")</code>: Programmatically accepts changes for a test file, updating <code>_snaps/demographics.md</code> and removing temporary <code>.new.md</code> files.</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="co" style="color: #5E5E5E;"># Review differences interactively in a Shiny app</span></span>
<span id="cb7-2">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">snapshot_review</span>()</span>
<span id="cb7-3"></span>
<span id="cb7-4"><span class="co" style="color: #5E5E5E;"># Or accept changes for a specific test file</span></span>
<span id="cb7-5">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">snapshot_accept</span>(<span class="st" style="color: #20794D;">"demographics"</span>)</span></code></pre></div></div>
</section>
</section>
<section id="snapshot-lifecycle-first-run-changes-ci-and-cran" class="level3">
<h3 class="anchored" data-anchor-id="snapshot-lifecycle-first-run-changes-ci-and-cran">5 · Snapshot lifecycle: first run, changes, CI, and CRAN</h3>
<p>Understanding snapshot behaviour across environments prevents unexpected failures:</p>
<pre><code>[Local First Run]    ──&gt; Saves to _snaps/{test}.md    ──&gt; Emits warning ──&gt; Test PASSES
[Local Match]        ──&gt; Compares via waldo::compare()──&gt; No diff       ──&gt; Test PASSES
[Local Mismatch]     ──&gt; Writes _snaps/{test}.new.md  ──&gt; Shows diff    ──&gt; Test FAILS
[CI, new snapshot]   ──&gt; Not recorded                 ──&gt; Error         ──&gt; Test FAILS
[CRAN (cran = FALSE)]──&gt; Not compared                 ──&gt; Returns       ──&gt; Neither pass nor fail</code></pre>
<ol type="1">
<li><strong>First run locally:</strong> When testthat encounters a new snapshot expectation, it writes <code>tests/testthat/_snaps/{test}.md</code>, emits a warning (<code>Adding new snapshot:</code>), and passes the test.</li>
<li><strong>Changed snapshot locally:</strong> If code changes and output diverges, testthat displays a <code>waldo</code> diff in the console, writes the new output to <code>_snaps/{test}.new.md</code>, and fails the test.</li>
<li><strong>Continuous Integration (CI):</strong> when the <code>CI</code> environment variable is <code>"true"</code> (GitHub Actions sets it), creating a <em>new</em> snapshot fails instead of passing. If a developer writes a snapshot test but forgets to commit its <code>_snaps/</code> file, the test fails on CI instead of quietly passing.</li>
<li><strong>CRAN checks:</strong> Snapshot expectations default to <code>cran = FALSE</code>. When running on CRAN (that is, when <code>NOT_CRAN</code> isn’t <code>"true"</code>), a snapshot expectation just returns: it neither succeeds nor fails, and the rest of the test still runs. This prevents minor upstream formatting shifts or platform font differences from breaking CRAN checks. If you explicitly set <code>cran = TRUE</code>, snapshots are verified on CRAN. With <code>error = TRUE</code>, the expectation fails even on CRAN if the expected error isn’t thrown (or an unexpected one is).</li>
</ol>
</section>
<section id="managing-volatile-output-transform-and-variant" class="level3">
<h3 class="anchored" data-anchor-id="managing-volatile-output-transform-and-variant">6 · Managing volatile output: <code>transform</code> and <code>variant</code></h3>
<p>Snapshots require deterministic output. When text contains fluctuating elements, two arguments provide control:</p>
<section id="scrubbing-text-with-transform" class="level4">
<h4 class="anchored" data-anchor-id="scrubbing-text-with-transform">Scrubbing text with <code>transform</code></h4>
<p>The <code>transform</code> argument takes a function that accepts a character vector of output lines and returns a scrubbed character vector:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb9-1">scrub_volatile <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(lines) {</span>
<span id="cb9-2">  <span class="co" style="color: #5E5E5E;"># Replace fluctuating timestamps and temporary directories</span></span>
<span id="cb9-3">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">gsub</span>(<span class="st" style="color: #20794D;">"[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}"</span>, <span class="st" style="color: #20794D;">"&lt;TIMESTAMP&gt;"</span>, lines)</span>
<span id="cb9-4">  lines <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">gsub</span>(<span class="st" style="color: #20794D;">"/tmp/Rtmp[A-Za-z0-9]+"</span>, <span class="st" style="color: #20794D;">"&lt;TEMPDIR&gt;"</span>, lines)</span>
<span id="cb9-5">  lines</span>
<span id="cb9-6">}</span>
<span id="cb9-7"></span>
<span id="cb9-8"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"export_pipeline() logs deterministic progress"</span>, {</span>
<span id="cb9-9">  <span class="fu" style="color: #4758AB;">expect_snapshot</span>(</span>
<span id="cb9-10">    <span class="fu" style="color: #4758AB;">run_export_pipeline</span>(),</span>
<span id="cb9-11">    <span class="at" style="color: #657422;">transform =</span> scrub_volatile</span>
<span id="cb9-12">  )</span>
<span id="cb9-13">})</span></code></pre></div></div>
<p>By scrubbing dynamic paths and timestamps into fixed tokens (<code>&lt;TIMESTAMP&gt;</code>, <code>&lt;TEMPDIR&gt;</code>), the snapshot remains stable across runs and machines.</p>
</section>
<section id="platform-differences-with-variant" class="level4">
<h4 class="anchored" data-anchor-id="platform-differences-with-variant">Platform differences with <code>variant</code></h4>
<p>When output legitimately differs across operating systems or R versions, use <code>variant</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"numerical summary matches platform representation"</span>, {</span>
<span id="cb10-2">  os_variant <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (.Platform<span class="sc" style="color: #5E5E5E;">$</span>OS.type <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"windows"</span>) <span class="st" style="color: #20794D;">"windows"</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> <span class="st" style="color: #20794D;">"unix"</span></span>
<span id="cb10-3">  <span class="fu" style="color: #4758AB;">expect_snapshot</span>(</span>
<span id="cb10-4">    <span class="fu" style="color: #4758AB;">print_complex_summary</span>(),</span>
<span id="cb10-5">    <span class="at" style="color: #657422;">variant =</span> os_variant</span>
<span id="cb10-6">  )</span>
<span id="cb10-7">})</span></code></pre></div></div>
<p>Snapshots are stored in <code>tests/testthat/_snaps/&lt;variant&gt;/&lt;test&gt;.md</code>. Use variants sparingly, and delete a variant’s folder when you stop supporting that environment.</p>
</section>
</section>
<section id="visual-regression-for-plots-with-vdiffr" class="level3">
<h3 class="anchored" data-anchor-id="visual-regression-for-plots-with-vdiffr">7 · Visual regression for plots with <code>vdiffr</code></h3>
<p>You cannot reliably verify graphical plots by comparing deparsed code. The <a href="https://vdiffr.r-lib.org/">{vdiffr}</a> package provides visual regression testing by converting plots into deterministic SVG files:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="co" style="color: #5E5E5E;"># tests/testthat/test-plots.R</span></span>
<span id="cb11-2"></span>
<span id="cb11-3"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"age by arm plot renders consistently"</span>, {</span>
<span id="cb11-4">  adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb11-5">  p <span class="ot" style="color: #003B4F;">&lt;-</span> ggplot2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ggplot</span>(adsl_saf, ggplot2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">aes</span>(<span class="at" style="color: #657422;">x =</span> TRT01A, <span class="at" style="color: #657422;">y =</span> AGE)) <span class="sc" style="color: #5E5E5E;">+</span></span>
<span id="cb11-6">    ggplot2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">geom_boxplot</span>() <span class="sc" style="color: #5E5E5E;">+</span></span>
<span id="cb11-7">    ggplot2<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">labs</span>(<span class="at" style="color: #657422;">title =</span> <span class="st" style="color: #20794D;">"Age by actual treatment"</span>, <span class="at" style="color: #657422;">x =</span> <span class="cn" style="color: #8f5902;">NULL</span>, <span class="at" style="color: #657422;">y =</span> <span class="st" style="color: #20794D;">"Age (years)"</span>)</span>
<span id="cb11-8"></span>
<span id="cb11-9">  vdiffr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_doppelganger</span>(<span class="st" style="color: #20794D;">"age-by-arm"</span>, p)</span>
<span id="cb11-10">})</span></code></pre></div></div>
<p><code>vdiffr::expect_doppelganger()</code> takes a title (sanitized to create the SVG file name) and a plot object (a ggplot, a recorded plot, or a function that draws a base plot). It writes the reference SVG to <code>tests/testthat/_snaps/plots/age-by-arm.svg</code>.</p>
<p>If a change alters margins, point sizes, or fonts:</p>
<ul>
<li>The test fails.</li>
<li>Under <code>R CMD check</code>, vdiffr logs the failures to <code>tests/vdiffr.Rout.fail</code>.</li>
<li>Running <code>testthat::snapshot_review()</code> opens an interactive visual diff viewer to compare the reference SVG against the new rendering.</li>
</ul>
</section>
<section id="the-pharma-angle-clinical-tables-as-regression-benchmarks" class="level3">
<h3 class="anchored" data-anchor-id="the-pharma-angle-clinical-tables-as-regression-benchmarks">8 · The pharma angle: clinical tables as regression benchmarks</h3>
<p>In clinical reporting, Tables, Figures, and Listings (TFLs) are primary deliverables. Statistical analysis plans define rigorous layout specifications: column headers with treatment counts (N=xx), indented summary labels, and strict decimal formatting templates (such as <code>xx.x (xx.x)</code>).</p>
<p>Building tables with <a href="https://cran.r-project.org/package=rtables">{rtables}</a> and data from <a href="https://pharmaverse.github.io/pharmaverseadam/">{pharmaverseadam}</a> produces complex hierarchical layouts:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;">library</span>(rtables)</span>
<span id="cb12-2"></span>
<span id="cb12-3">adsl_saf <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">subset</span>(pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl, SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>)</span>
<span id="cb12-4"></span>
<span id="cb12-5">lyt <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">basic_table</span>() <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb12-6">  <span class="fu" style="color: #4758AB;">split_cols_by</span>(<span class="st" style="color: #20794D;">"TRT01A"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb12-7">  <span class="fu" style="color: #4758AB;">add_colcounts</span>() <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb12-8">  <span class="fu" style="color: #4758AB;">analyze</span>(<span class="st" style="color: #20794D;">"AGE"</span>, <span class="at" style="color: #657422;">afun =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(x) {</span>
<span id="cb12-9">    <span class="fu" style="color: #4758AB;">in_rows</span>(</span>
<span id="cb12-10">      <span class="st" style="color: #20794D;">"Mean (SD)"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">rcell</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="fu" style="color: #4758AB;">mean</span>(x), <span class="fu" style="color: #4758AB;">sd</span>(x)), <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"xx.x (xx.x)"</span>),</span>
<span id="cb12-11">      <span class="st" style="color: #20794D;">"Median"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">rcell</span>(<span class="fu" style="color: #4758AB;">median</span>(x), <span class="at" style="color: #657422;">format =</span> <span class="st" style="color: #20794D;">"xx.x"</span>)</span>
<span id="cb12-12">    )</span>
<span id="cb12-13">  })</span>
<span id="cb12-14"></span>
<span id="cb12-15">tbl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">build_table</span>(lyt, adsl_saf)</span></code></pre></div></div>
<p>Asserting this table by manually indexing cells or concatenating strings is tedious and fragile. Snapshot testing the rendered table captures the entire formatted layout:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"adsl baseline demographic summary table layout matches snapshot"</span>, {</span>
<span id="cb13-2">  <span class="fu" style="color: #4758AB;">expect_snapshot</span>(tbl)</span>
<span id="cb13-3">})</span></code></pre></div></div>
<p>When evaluated, <code>expect_snapshot(tbl)</code> records the exact ASCII table in <code>_snaps/demographics.md</code>:</p>
<pre><code>             Placebo     Xanomeline High Dose   Xanomeline Low Dose
              (N=86)            (N=72)                (N=96)       
———————————————————————————————————————————————————————————————————
Mean (SD)   75.2 (8.6)        73.8 (7.9)            76.0 (8.1)     
Median         76.0              75.5                  78.0        </code></pre>
<p>In regulated environments, reviewing snapshot diffs in pull requests links testing directly to change control:</p>
<ul>
<li><strong>Auditable change tracking:</strong> If an upstream package update changes table padding or an algorithm adjusts rounding, git diffs highlight the exact text rows affected.</li>
<li><strong>Verification evidence:</strong> Snapshot files provide concrete, human-readable records that output formatting matches study specifications.</li>
<li><strong>Risk-based validation:</strong> Reviewers inspect the visual impact of code refactors before merging, preventing formatting drift across clinical deliverables.</li>
</ul>
<p>The next post in this series covers testing Shiny server logic with <code>testServer()</code>.</p>
</section>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Forgetting to commit <code>_snaps/</code>:</strong> New snapshots pass locally on the first run. If you forget to commit the generated markdown or SVG files, CI detects missing reference files and fails the build.</li>
<li><strong>Blindly running <code>snapshot_accept()</code>:</strong> Snapshot testing works only if humans review the changes. Accepting snapshot changes without inspecting the diff defeats the entire purpose of the test.</li>
<li><strong>Snapshotting unseeded or dynamic output:</strong> Output containing <code>Sys.time()</code>, random numbers, or process IDs will fail continuously. Always isolate random seeds with <code>withr::local_seed()</code> or scrub strings with <code>transform =</code>.</li>
<li><strong>Using snapshots for simple scalar assertions:</strong> Snapshotting <code>expect_snapshot(nrow(df))</code> adds file management overhead without benefit. Use <code>expect_equal()</code> for scalar values.</li>
<li><strong>Over-relying on variants:</strong> Variants duplicate snapshot files. Keep variants minimal and delete obsolete variant directories when older environments are retired.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/snapshot-tests/scripts/snapshot-demo.R">View <code>snapshot-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/snapshot-tests/scripts/snapshot-demo.R" download="snapshot-demo.R">Download</a></p>
<p>Builds a throwaway package whose tests snapshot a printed table with <code>expect_snapshot()</code> and a plot with <code>vdiffr::expect_doppelganger()</code>, runs them twice (record, then compare), then changes the output so you can see a snapshot fail. Requires <code>{testthat}</code>, <code>{usethis}</code>, <code>{withr}</code>, <code>{ggplot2}</code>, and <code>{vdiffr}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>snapshot-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><span class="co" style="color: #5E5E5E;"># Snapshot tests, end to end: builds a throwaway package whose tests snapshot a</span></span>
<span id="cb15-2"><span class="co" style="color: #5E5E5E;"># printed summary with expect_snapshot() and a plot with</span></span>
<span id="cb15-3"><span class="co" style="color: #5E5E5E;"># vdiffr::expect_doppelganger(). Runs the tests twice (record, then compare),</span></span>
<span id="cb15-4"><span class="co" style="color: #5E5E5E;"># then changes the output so a snapshot fails.</span></span>
<span id="cb15-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb15-6"><span class="co" style="color: #5E5E5E;">#   Rscript snapshot-demo.R</span></span>
<span id="cb15-7"></span>
<span id="cb15-8">demo_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb15-9">  <span class="st" style="color: #20794D;">"R/age-summary.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb15-10">    <span class="st" style="color: #20794D;">"#' Print a small age summary"</span>,</span>
<span id="cb15-11">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb15-12">    <span class="st" style="color: #20794D;">"print_age_summary &lt;- function(age) {"</span>,</span>
<span id="cb15-13">    <span class="st" style="color: #20794D;">"  if (!is.numeric(age)) stop(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">`age` must be numeric.</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, call. = FALSE)"</span>,</span>
<span id="cb15-14">    <span class="st" style="color: #20794D;">"  cat(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">n:        </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, length(age), </span><span class="sc" style="color: #5E5E5E;">\"\\</span><span class="st" style="color: #20794D;">n</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, sep = </span><span class="sc" style="color: #5E5E5E;">\"\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb15-15">    <span class="st" style="color: #20794D;">"  cat(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Mean (SD):</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, sprintf(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">%.1f (%.1f)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, mean(age), stats::sd(age)), </span><span class="sc" style="color: #5E5E5E;">\"\\</span><span class="st" style="color: #20794D;">n</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb15-16">    <span class="st" style="color: #20794D;">"  invisible(age)"</span>,</span>
<span id="cb15-17">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb15-18">  ),</span>
<span id="cb15-19">  <span class="st" style="color: #20794D;">"R/age-plot.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb15-20">    <span class="st" style="color: #20794D;">"#' Box plot of age by arm"</span>,</span>
<span id="cb15-21">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb15-22">    <span class="st" style="color: #20794D;">"age_plot &lt;- function(data) {"</span>,</span>
<span id="cb15-23">    <span class="st" style="color: #20794D;">"  ggplot2::ggplot(data, ggplot2::aes(x = arm, y = age)) +"</span>,</span>
<span id="cb15-24">    <span class="st" style="color: #20794D;">"    ggplot2::geom_boxplot() +"</span>,</span>
<span id="cb15-25">    <span class="st" style="color: #20794D;">"    ggplot2::labs(x = NULL, y = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">Age (years)</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb15-26">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb15-27">  ),</span>
<span id="cb15-28">  <span class="st" style="color: #20794D;">"tests/testthat/test-age-summary.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb15-29">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">print_age_summary() output is stable</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb15-30">    <span class="st" style="color: #20794D;">"  expect_snapshot(print_age_summary(c(64, 71, 80)))"</span>,</span>
<span id="cb15-31">    <span class="st" style="color: #20794D;">"})"</span>,</span>
<span id="cb15-32">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb15-33">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">print_age_summary() explains a wrong input</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb15-34">    <span class="st" style="color: #20794D;">"  expect_snapshot(print_age_summary(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">64</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">), error = TRUE)"</span>,</span>
<span id="cb15-35">    <span class="st" style="color: #20794D;">"})"</span></span>
<span id="cb15-36">  ),</span>
<span id="cb15-37">  <span class="st" style="color: #20794D;">"tests/testthat/test-age-plot.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb15-38">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">age_plot() looks the same</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb15-39">    <span class="st" style="color: #20794D;">"  data &lt;- data.frame(arm = rep(c(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">A</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">B</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">), each = 3), age = c(60, 65, 70, 62, 68, 74))"</span>,</span>
<span id="cb15-40">    <span class="st" style="color: #20794D;">"  vdiffr::expect_doppelganger(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">age-plot</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, age_plot(data))"</span>,</span>
<span id="cb15-41">    <span class="st" style="color: #20794D;">"})"</span></span>
<span id="cb15-42">  )</span>
<span id="cb15-43">)</span>
<span id="cb15-44"></span>
<span id="cb15-45"><span class="co" style="color: #5E5E5E;"># Creates the package and returns its path.</span></span>
<span id="cb15-46">make_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">path =</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"snapdemo"</span>)) {</span>
<span id="cb15-47">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(path, <span class="at" style="color: #657422;">rstudio =</span> <span class="cn" style="color: #8f5902;">FALSE</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb15-48">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">with_project</span>(path, {</span>
<span id="cb15-49">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_testthat</span>(<span class="dv" style="color: #AD0000;">3</span>)</span>
<span id="cb15-50">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"ggplot2"</span>)</span>
<span id="cb15-51">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"vdiffr"</span>, <span class="at" style="color: #657422;">type =</span> <span class="st" style="color: #20794D;">"Suggests"</span>)</span>
<span id="cb15-52">  })</span>
<span id="cb15-53">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (file <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">names</span>(demo_files)) {</span>
<span id="cb15-54">    <span class="fu" style="color: #4758AB;">writeLines</span>(demo_files[[file]], <span class="fu" style="color: #4758AB;">file.path</span>(path, file))</span>
<span id="cb15-55">  }</span>
<span id="cb15-56">  path</span>
<span id="cb15-57">}</span>
<span id="cb15-58"></span>
<span id="cb15-59"><span class="co" style="color: #5E5E5E;"># Runs the package's tests. `ci = FALSE` because this demo records new</span></span>
<span id="cb15-60"><span class="co" style="color: #5E5E5E;"># snapshots on purpose: with CI=true, testthat fails a test that would create</span></span>
<span id="cb15-61"><span class="co" style="color: #5E5E5E;"># a new snapshot (you forgot to commit it).</span></span>
<span id="cb15-62">run_demo_tests <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb15-63">  path,</span>
<span id="cb15-64">  <span class="at" style="color: #657422;">reporter =</span> testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">default_reporter</span>(),</span>
<span id="cb15-65">  <span class="at" style="color: #657422;">ci =</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb15-66">) {</span>
<span id="cb15-67">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_envvar</span>(<span class="at" style="color: #657422;">CI =</span> <span class="fu" style="color: #4758AB;">tolower</span>(<span class="fu" style="color: #4758AB;">as.character</span>(ci)))</span>
<span id="cb15-68">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_local</span>(path, <span class="at" style="color: #657422;">reporter =</span> reporter, <span class="at" style="color: #657422;">stop_on_failure =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb15-69">}</span>
<span id="cb15-70"></span>
<span id="cb15-71"><span class="co" style="color: #5E5E5E;"># Changes the printed output: one decimal place becomes two.</span></span>
<span id="cb15-72">change_output <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb15-73">  file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"age-summary.R"</span>)</span>
<span id="cb15-74">  code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">readLines</span>(file)</span>
<span id="cb15-75">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="fu" style="color: #4758AB;">sub</span>(<span class="st" style="color: #20794D;">"%.1f (%.1f)"</span>, <span class="st" style="color: #20794D;">"%.2f (%.2f)"</span>, code, <span class="at" style="color: #657422;">fixed =</span> <span class="cn" style="color: #8f5902;">TRUE</span>), file)</span>
<span id="cb15-76">}</span>
<span id="cb15-77"></span>
<span id="cb15-78">snapshot_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb15-79">  <span class="fu" style="color: #4758AB;">list.files</span>(<span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"tests"</span>, <span class="st" style="color: #20794D;">"testthat"</span>, <span class="st" style="color: #20794D;">"_snaps"</span>), <span class="at" style="color: #657422;">recursive =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb15-80">}</span>
<span id="cb15-81"></span>
<span id="cb15-82"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb15-83"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb15-84">  path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">make_demo_package</span>()</span>
<span id="cb15-85">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Run 1: records the snapshots"</span>)</span>
<span id="cb15-86">  <span class="fu" style="color: #4758AB;">run_demo_tests</span>(path)</span>
<span id="cb15-87">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">snapshot_files</span>(path))</span>
<span id="cb15-88">  <span class="fu" style="color: #4758AB;">cat</span>(</span>
<span id="cb15-89">    <span class="fu" style="color: #4758AB;">readLines</span>(<span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"tests/testthat/_snaps/age-summary.md"</span>)),</span>
<span id="cb15-90">    <span class="at" style="color: #657422;">sep =</span> <span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span></span>
<span id="cb15-91">  )</span>
<span id="cb15-92">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Run 2: compares against them"</span>)</span>
<span id="cb15-93">  <span class="fu" style="color: #4758AB;">run_demo_tests</span>(path)</span>
<span id="cb15-94">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Run 3: after changing the output"</span>)</span>
<span id="cb15-95">  <span class="fu" style="color: #4758AB;">change_output</span>(path)</span>
<span id="cb15-96">  <span class="fu" style="color: #4758AB;">run_demo_tests</span>(path)</span>
<span id="cb15-97">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">snapshot_files</span>(path)) <span class="co" style="color: #5E5E5E;"># the .new.md file holds the changed output</span></span>
<span id="cb15-98">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>vdiffr</strong>: <a href="https://vdiffr.r-lib.org/">vdiffr.r-lib.org</a></li>
<li><strong>rtables</strong>: <a href="https://cran.r-project.org/package=rtables">CRAN</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
<li><strong>cli</strong>: <a href="https://cli.r-lib.org/">cli.r-lib.org</a></li>
<li><strong>ggplot2</strong>: <a href="https://ggplot2.tidyverse.org/">ggplot2.tidyverse.org</a></li>
</ul>
<p><strong>Web-repo comparison</strong></p>
<ul>
<li><strong>Vitest</strong>: <a href="https://vitest.dev/">vitest.dev</a></li>
<li><strong>Playwright</strong>: <a href="https://playwright.dev/">playwright.dev</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-series-nav__series">Testing series · part 3 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 2</span><span class="site-related-card__title">Test design: fixtures, temporary state and mocking</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/shiny-testserver/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 4</span><span class="site-related-card__title">Testing Shiny server logic with testServer()</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html" class="site-link-row" title="How to engineer clinical TFLs in R across direct layout engines and ARD-first architectures, with RTF export, listings, and team conventions."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Generating tables, figures and listings in R</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html" class="site-link-row" title="How to build, manipulate, and quality-control Analysis Results Data (ARD) in R with cards and cardx, decoupling computations from presentation."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Analysis Results Data in R with {cards} and {cardx}</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/qc-double-programming-diffdf/index.html" class="site-link-row" title="Why independent programming exists in clinical reporting, how risk-based QC structures verification tiers, and how to reconcile datasets and results in R with diffdf."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">QC and double programming with {diffdf}</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/snapshot-tests/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Test design: fixtures, temporary state and mocking</title>
  <link>https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>In <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html">the first post in this series</a>, we set up automated tests to replace manual console checks. But as a test suite grows, a subtler set of failures emerges: <strong>tests that pass when run on their own, but fail when run together</strong>.</p>
<p>You hit <code>devtools::test()</code> or run tests in CI, and suddenly assertions break:</p>
<ul>
<li><strong>State leaks across tests:</strong> A test sets <code>options(OutDec = ",")</code> or changes an environment variable, and downstream tests fail because the global session was silently mutated.</li>
<li><strong>Leftover files and directories:</strong> A test writes scratch outputs to the project folder, leaving artefacts behind or failing on subsequent runs because the file already exists.</li>
<li><strong>Shifting working directories:</strong> A test calls <code>setwd()</code>, hits an unexpected error before resetting it, and leaves the remaining suite pointing at the wrong path.</li>
<li><strong>Non-deterministic dependencies:</strong> Code that calls <code>Sys.Date()</code>, <code>Sys.time()</code>, or an external API behaves differently on Monday than it did on Friday, or fails entirely when run offline.</li>
<li><strong>Bloated, brittle test data:</strong> Developers copy whole production tables or hand-craft fragile 1,000-row data frames with inconsistent column types, making tests slow to run and painful to maintain.</li>
</ul>
<p>Unit tests must be hermetic: each test should run in a clean sandbox, execute independently in any order, and leave the environment exactly as it found it.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In JavaScript and TypeScript repositories, frameworks such as Vitest and Jest solve isolation and determinism with explicit lifecycle hooks, fixture loaders, and first-class mocking APIs:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb1-1"><span class="co" style="color: #5E5E5E;">// src/trial-tracker.test.ts</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;">import</span> { describe<span class="op" style="color: #5E5E5E;">,</span> it<span class="op" style="color: #5E5E5E;">,</span> expect<span class="op" style="color: #5E5E5E;">,</span> beforeEach<span class="op" style="color: #5E5E5E;">,</span> afterEach<span class="op" style="color: #5E5E5E;">,</span> vi } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"vitest"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-3"><span class="im" style="color: #00769E;">import</span> { daysSinceEnrollment } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"./trial-tracker"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;">describe</span>(<span class="st" style="color: #20794D;">"daysSinceEnrollment"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-6">  <span class="fu" style="color: #4758AB;">beforeEach</span>(() <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-7">    <span class="co" style="color: #5E5E5E;">// Freeze the clock to a deterministic date</span></span>
<span id="cb1-8">    vi<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">useFakeTimers</span>()<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-9">    vi<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">setSystemTime</span>(<span class="kw" style="color: #003B4F;
font-weight: bold;">new</span> <span class="bu" style="color: null;">Date</span>(<span class="st" style="color: #20794D;">"2026-09-26"</span>))<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-10">  })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-11"></span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;">afterEach</span>(() <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-13">    <span class="co" style="color: #5E5E5E;">// Restore global state completely</span></span>
<span id="cb1-14">    vi<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">useRealTimers</span>()<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-15">    vi<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">restoreAllMocks</span>()<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-16">  })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-17"></span>
<span id="cb1-18">  <span class="fu" style="color: #4758AB;">it</span>(<span class="st" style="color: #20794D;">"calculates elapsed days from enrollment"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-19">    <span class="fu" style="color: #4758AB;">expect</span>(<span class="fu" style="color: #4758AB;">daysSinceEnrollment</span>(<span class="st" style="color: #20794D;">"2026-09-20"</span>))<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toBe</span>(<span class="dv" style="color: #AD0000;">6</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-20">  })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-21">})<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<p>Web repositories rely on three fundamental test-design principles:</p>
<ol type="1">
<li><strong>Deterministic boundaries:</strong> Timers, network requests, and external clocks are frozen or replaced during the test.</li>
<li><strong>Teardown always runs:</strong> Setup logic in <code>beforeEach</code> is paired with cleanup in <code>afterEach</code>, ensuring that even when a test throws an unhandled error, the global environment is reset.</li>
<li><strong>Dedicated fixtures:</strong> Persistent sample inputs live in a dedicated <code>fixtures/</code> folder, decoupled from application code.</li>
</ol>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In R, the combination of <a href="https://testthat.r-lib.org/"><code>testthat</code></a> (3rd edition) and <a href="https://withr.r-lib.org/"><code>withr</code></a> provides a tidier model. Rather than pairing setup and teardown callbacks, you call scoped <code>local_*()</code> functions that undo their change automatically when the calling function (or <code>test_that()</code> block) finishes.</p>
<section id="structuring-test-fixtures-in-testthat-3e" class="level3">
<h3 class="anchored" data-anchor-id="structuring-test-fixtures-in-testthat-3e">1 · Structuring test fixtures in testthat 3e</h3>
<p><code>testthat</code> reserves specific file prefixes and folder conventions inside <code>tests/testthat/</code>:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Path / File pattern</th>
<th>Loading behaviour</th>
<th>Best used for</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>tests/testthat/helper-*.R</code></td>
<td>Sourced by <code>devtools::load_all()</code> and <code>devtools::test()</code></td>
<td>Shared fixture generators, domain data factories, custom expectations</td>
</tr>
<tr class="even">
<td><code>tests/testthat/setup*.R</code> (e.g.&nbsp;<code>setup.R</code>)</td>
<td>Run once before the tests; <em>not</em> sourced by <code>load_all()</code></td>
<td>Session-wide options, global test database connections</td>
</tr>
<tr class="odd">
<td><code>tests/testthat/fixtures/</code></td>
<td>Ignored by test runners; paths resolved with <code>test_path()</code></td>
<td>Static reference files (CSVs, JSON, clinical domain subsets)</td>
</tr>
</tbody>
</table>
</div>
<section id="static-fixtures-with-test_path" class="level4">
<h4 class="anchored" data-anchor-id="static-fixtures-with-test_path">Static fixtures with <code>test_path()</code></h4>
<p>When tests run, your working directory changes depending on context: running interactively, running via <code>devtools::test()</code>, or running under <code>R CMD check</code> (where the directory is set to a temporary check folder).</p>
<p>Never use relative file paths like <code>"../../fixtures/input.csv"</code>. Instead, use <code>testthat::test_path()</code>, which always constructs paths relative to <code>tests/testthat/</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"read_lab_data() ingests raw vendor files"</span>, {</span>
<span id="cb2-2">  raw_file <span class="ot" style="color: #003B4F;">&lt;-</span> testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_path</span>(<span class="st" style="color: #20794D;">"fixtures"</span>, <span class="st" style="color: #20794D;">"sample_labs.csv"</span>)</span>
<span id="cb2-3">  res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">read_lab_data</span>(raw_file)</span>
<span id="cb2-4"></span>
<span id="cb2-5">  <span class="fu" style="color: #4758AB;">expect_s3_class</span>(res, <span class="st" style="color: #20794D;">"data.frame"</span>)</span>
<span id="cb2-6">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">nrow</span>(res), <span class="dv" style="color: #AD0000;">5</span>)</span>
<span id="cb2-7">})</span></code></pre></div></div>
</section>
<section id="shared-helpers-in-helper-.r" class="level4">
<h4 class="anchored" data-anchor-id="shared-helpers-in-helper-.r">Shared helpers in <code>helper-*.R</code></h4>
<p>Files named <code>tests/testthat/helper-*.R</code> run before test execution. Because <code>devtools::load_all()</code> sources them too, your fixture generators are immediately available while you develop interactively in the console.</p>
</section>
</section>
<section id="managing-temporary-state-with-withr" class="level3">
<h3 class="anchored" data-anchor-id="managing-temporary-state-with-withr">2 · Managing temporary state with <code>withr</code></h3>
<p>The <code>withr</code> package provides <code>local_*()</code> functions that alter state for the lifetime of the current environment (such as a <code>test_that()</code> block) and restore the prior state when that environment closes.</p>
<p>If a test fails halfway through, <code>withr</code> still restores the original settings.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"formatting respects decimal and directory settings"</span>, {</span>
<span id="cb3-2">  <span class="co" style="color: #5E5E5E;"># 1. Temporary directory: automatically removed when this test block exits</span></span>
<span id="cb3-3">  temp_dir <span class="ot" style="color: #003B4F;">&lt;-</span> withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_tempdir</span>(<span class="at" style="color: #657422;">pattern =</span> <span class="st" style="color: #20794D;">"study-export"</span>)</span>
<span id="cb3-4"></span>
<span id="cb3-5">  <span class="co" style="color: #5E5E5E;"># 2. Temporary option: OutDec restored to "." when test block exits</span></span>
<span id="cb3-6">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_options</span>(<span class="at" style="color: #657422;">OutDec =</span> <span class="st" style="color: #20794D;">","</span>)</span>
<span id="cb3-7"></span>
<span id="cb3-8">  <span class="co" style="color: #5E5E5E;"># 3. Temporary environment variable: un-set when test block exits</span></span>
<span id="cb3-9">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_envvar</span>(<span class="at" style="color: #657422;">ANALYSIS_ENV =</span> <span class="st" style="color: #20794D;">"test"</span>)</span>
<span id="cb3-10"></span>
<span id="cb3-11">  <span class="co" style="color: #5E5E5E;"># 4. Temporary working directory: reverted when test block exits</span></span>
<span id="cb3-12">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_dir</span>(temp_dir)</span>
<span id="cb3-13"></span>
<span id="cb3-14">  <span class="co" style="color: #5E5E5E;"># 5. Temporary seed: previous RNG state restored when test block exits</span></span>
<span id="cb3-15">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_seed</span>(<span class="dv" style="color: #AD0000;">2026</span>)</span>
<span id="cb3-16"></span>
<span id="cb3-17">  <span class="co" style="color: #5E5E5E;"># The code under test sees the temporary settings</span></span>
<span id="cb3-18">  <span class="fu" style="color: #4758AB;">writeLines</span>(<span class="st" style="color: #20794D;">"PARAM,VAL"</span>, <span class="st" style="color: #20794D;">"results.csv"</span>) <span class="co" style="color: #5E5E5E;"># written inside temp_dir</span></span>
<span id="cb3-19">  <span class="fu" style="color: #4758AB;">expect_true</span>(<span class="fu" style="color: #4758AB;">file.exists</span>(<span class="st" style="color: #20794D;">"results.csv"</span>))</span>
<span id="cb3-20">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">format</span>(<span class="fl" style="color: #AD0000;">1.5</span>), <span class="st" style="color: #20794D;">"1,5"</span>)</span>
<span id="cb3-21">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">Sys.getenv</span>(<span class="st" style="color: #20794D;">"ANALYSIS_ENV"</span>), <span class="st" style="color: #20794D;">"test"</span>)</span>
<span id="cb3-22">})</span></code></pre></div></div>
<section id="writing-your-own-local_-helpers" class="level4">
<h4 class="anchored" data-anchor-id="writing-your-own-local_-helpers">Writing your own <code>local_*()</code> helpers</h4>
<p>You can write domain-specific fixture helpers using <code>withr::defer()</code> and the <code>.local_envir</code> argument:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># Inside tests/testthat/helper-fixtures.R</span></span>
<span id="cb4-2"></span>
<span id="cb4-3">local_scratch_file <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(lines, <span class="at" style="color: #657422;">filename =</span> <span class="st" style="color: #20794D;">"input.txt"</span>, <span class="at" style="color: #657422;">.local_envir =</span> <span class="fu" style="color: #4758AB;">parent.frame</span>()) {</span>
<span id="cb4-4">  temp_dir <span class="ot" style="color: #003B4F;">&lt;-</span> withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">local_tempdir</span>(<span class="at" style="color: #657422;">.local_envir =</span> .local_envir)</span>
<span id="cb4-5">  file_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(temp_dir, filename)</span>
<span id="cb4-6">  <span class="fu" style="color: #4758AB;">writeLines</span>(lines, file_path)</span>
<span id="cb4-7"></span>
<span id="cb4-8">  <span class="co" style="color: #5E5E5E;"># Any extra clean-up goes in defer(); it runs when the calling test ends</span></span>
<span id="cb4-9">  withr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">defer</span>(<span class="fu" style="color: #4758AB;">unlink</span>(file_path), <span class="at" style="color: #657422;">envir =</span> .local_envir)</span>
<span id="cb4-10"></span>
<span id="cb4-11">  file_path</span>
<span id="cb4-12">}</span></code></pre></div></div>
<p>When called inside a <code>test_that()</code> block, <code>.local_envir = parent.frame()</code> binds the lifetime of the scratch directory and its deferred cleanup to that specific test. When the test completes, the folder is pruned automatically.</p>
</section>
</section>
<section id="mocking-with-testthatlocal_mocked_bindings" class="level3">
<h3 class="anchored" data-anchor-id="mocking-with-testthatlocal_mocked_bindings">3 · Mocking with <code>testthat::local_mocked_bindings()</code></h3>
<p>Tests that rely on <code>Sys.Date()</code>, <code>Sys.time()</code>, or external HTTP services are prone to transient failures. <code>local_mocked_bindings()</code> (testthat 3.1.7 and later) is the tool for this now. The older <code>with_mock()</code> and <code>local_mock()</code> were deprecated in testthat 3.0.0 and are defunct since 3.3.0: the technique they relied on isn’t allowed from R 4.5.0.</p>
<p><code>local_mocked_bindings()</code> temporarily overrides a function binding within your package’s namespace for the duration of the calling scope:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"days_since_baseline() computes correct duration"</span>, {</span>
<span id="cb5-2">  <span class="co" style="color: #5E5E5E;"># Temporarily mock the package-internal clock helper</span></span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;">local_mocked_bindings</span>(</span>
<span id="cb5-4">    <span class="at" style="color: #657422;">current_date =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() <span class="fu" style="color: #4758AB;">as.Date</span>(<span class="st" style="color: #20794D;">"2026-09-26"</span>)</span>
<span id="cb5-5">  )</span>
<span id="cb5-6"></span>
<span id="cb5-7">  <span class="co" style="color: #5E5E5E;"># days_since_baseline() calls current_date() internally</span></span>
<span id="cb5-8">  duration <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">days_since_baseline</span>(<span class="fu" style="color: #4758AB;">as.Date</span>(<span class="st" style="color: #20794D;">"2026-09-20"</span>))</span>
<span id="cb5-9">  <span class="fu" style="color: #4758AB;">expect_equal</span>(duration, <span class="dv" style="color: #AD0000;">6</span>L)</span>
<span id="cb5-10">})</span></code></pre></div></div>
<section id="the-rule-you-can-only-mock-what-your-package-can-see" class="level4">
<h4 class="anchored" data-anchor-id="the-rule-you-can-only-mock-what-your-package-can-see">The rule: you can only mock what your package can see</h4>
<p><code>local_mocked_bindings()</code> works by temporarily changing bindings in your package’s own namespace. Under <code>R CMD check</code> that namespace is locked, so it can replace a binding that exists but can’t create a new one. A base function such as <code>Sys.Date()</code> has no binding in your package, so there’s nothing to replace. The testthat docs give two ways round this:</p>
<ul>
<li>add a <code>NULL</code> binding to your package (for example <code>Sys.Date &lt;- NULL</code> in <code>R/zzz.R</code>), then mock <code>Sys.Date</code>; or</li>
<li>use the <strong>“wrap it” pattern</strong>, which also makes the code’s intent clearer:</li>
</ul>
<ol type="1">
<li><p>In your package code (<code>R/utils.R</code>), define a thin wrapper:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">today <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() <span class="fu" style="color: #4758AB;">Sys.Date</span>()</span></code></pre></div></div></li>
<li><p>In your package logic, call <code>today()</code> instead of <code>Sys.Date()</code>.</p></li>
<li><p>In your tests, mock <code>today</code> with <code>local_mocked_bindings(today = function() ...)</code>:</p></li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="co" style="color: #5E5E5E;"># R/trial_status.R</span></span>
<span id="cb7-2">study_day <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(baseline_date) {</span>
<span id="cb7-3">  <span class="fu" style="color: #4758AB;">as.integer</span>(<span class="fu" style="color: #4758AB;">today</span>() <span class="sc" style="color: #5E5E5E;">-</span> <span class="fu" style="color: #4758AB;">as.Date</span>(baseline_date)) <span class="sc" style="color: #5E5E5E;">+</span> <span class="dv" style="color: #AD0000;">1</span>L</span>
<span id="cb7-4">}</span>
<span id="cb7-5"></span>
<span id="cb7-6"><span class="co" style="color: #5E5E5E;"># tests/testthat/test-trial_status.R</span></span>
<span id="cb7-7"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"study_day calculates Day 1 correctly"</span>, {</span>
<span id="cb7-8">  <span class="fu" style="color: #4758AB;">local_mocked_bindings</span>(<span class="at" style="color: #657422;">today =</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() <span class="fu" style="color: #4758AB;">as.Date</span>(<span class="st" style="color: #20794D;">"2026-01-15"</span>))</span>
<span id="cb7-9">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">study_day</span>(<span class="st" style="color: #20794D;">"2026-01-15"</span>), <span class="dv" style="color: #AD0000;">1</span>L)</span>
<span id="cb7-10">})</span></code></pre></div></div>
<p>(A real study-day derivation also handles dates before day 1, where there is no day 0; in ADaM code, <code>admiral::derive_vars_dy()</code> does this for you.)</p>
<p>This pattern isolates external boundaries (dates, random numbers, APIs) into explicit, testable ports.</p>
</section>
</section>
<section id="test-data-design-minimal-realistic-clean" class="level3">
<h3 class="anchored" data-anchor-id="test-data-design-minimal-realistic-clean">4 · Test data design: minimal, realistic, clean</h3>
<p>Unit tests do not need massive data frames. A common failure mode in data-heavy teams is a suite slowed down by massive tables that test nothing extra.</p>
<p>Follow three principles when designing test data:</p>
<ol type="1">
<li><strong>Minimal rows:</strong> Two to five rows are typically enough to test grouping, summarisation, and edge cases (e.g.&nbsp;one treated patient, one placebo patient, and one subject with missing baseline data).</li>
<li><strong>Subset existing open schemas:</strong> In clinical reporting, do not invent fictional column structures that diverge from CDISC standards. Subset standard open datasets from <a href="https://pharmaverse.github.io/pharmaverseadam/">{pharmaverseadam}</a> (such as <code>adsl</code> or <code>advs</code>) or <a href="https://pharmaverse.github.io/pharmaversesdtm/">{pharmaversesdtm}</a> (such as <code>dm</code> or <code>ex</code>):</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="co" style="color: #5E5E5E;"># tests/testthat/helper-clinical-fixtures.R</span></span>
<span id="cb8-2"></span>
<span id="cb8-3">make_test_adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>() {</span>
<span id="cb8-4">  <span class="co" style="color: #5E5E5E;"># Take the minimum columns and rows from a known open CDISC standard</span></span>
<span id="cb8-5">  pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl[<span class="dv" style="color: #AD0000;">1</span><span class="sc" style="color: #5E5E5E;">:</span><span class="dv" style="color: #AD0000;">3</span>, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"USUBJID"</span>, <span class="st" style="color: #20794D;">"ARM"</span>, <span class="st" style="color: #20794D;">"AGE"</span>, <span class="st" style="color: #20794D;">"SEX"</span>, <span class="st" style="color: #20794D;">"SAFFL"</span>)]</span>
<span id="cb8-6">}</span></code></pre></div></div>
<ol start="3" type="1">
<li><strong>Never commit real patient data:</strong> Never store real, pseudonymised, or production patient data in a repository. Aside from severe regulatory and data protection violations (HIPAA, GDPR, ICH GCP), real clinical data is unnecessarily large and subject to drift. Synthetic, minimal data belongs in code.</li>
</ol>
</section>
<section id="the-gxp-angle-determinism-as-evidence" class="level3">
<h3 class="anchored" data-anchor-id="the-gxp-angle-determinism-as-evidence">5 · The GxP angle: determinism as evidence</h3>
<p>In regulated environments, test results are part of the evidence that software does what it should. If a test suite passes on the build server on Tuesday but fails on Wednesday because of an un-mocked date or an un-reset environment variable, the audit trail loses credibility.</p>
<p>Isolated, deterministic tests mean that:</p>
<ul>
<li>Verification evidence is <strong>reproducible</strong> across developer laptops and CI runners.</li>
<li>Results are <strong>independent of execution sequence</strong>: running <code>test-alpha.R</code> before <code>test-beta.R</code> yields the exact same outcome as running them in reverse.</li>
<li>Test runs leave no side effects behind on the machine.</li>
</ul>
<p>The next post in this series covers snapshot tests, verifying complex data structures, printed tables, and graphical outputs without fragile manual assertions.</p>
</section>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Mocking internal business logic:</strong> Mock external dependencies (dates, file systems, web APIs), not your own calculations. If you mock every internal helper, you end up verifying your mock definitions rather than your package code.</li>
<li><strong>Fixtures that drift from production schemas:</strong> When APIs or CDISC schemas evolve, outdated static fixtures will pass tests while your package breaks on real datasets. Keep fixtures minimal and align them with open reference standards.</li>
<li><strong>Calling <code>set.seed()</code> or <code>setwd()</code> directly:</strong> Calling <code>set.seed(123)</code> or <code>setwd(dir)</code> without resetting leaves the R process altered for all subsequent tests. Always use <code>withr::local_seed()</code> and <code>withr::local_dir()</code>.</li>
<li><strong>Relying on alphabetical test file ordering:</strong> <code>testthat</code> executes test files alphabetically (<code>test-a.R</code> before <code>test-b.R</code>). Never rely on state established in an earlier file. Each file must be completely self-contained.</li>
<li><strong>Putting heavy computation in <code>setup.R</code>:</strong> Code in <code>setup.R</code> runs unconditionally before the suite. Reserve it for lightweight session guards, and place specific data generation inside <code>helper-*.R</code> functions invoked only where required.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/scripts/test-design-demo.R">View <code>test-design-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/scripts/test-design-demo.R" download="test-design-demo.R">Download</a></p>
<p>Builds a throwaway package whose tests use a helper fixture, <code>withr::local_tempdir()</code>, <code>withr::local_options()</code>, and <code>testthat::local_mocked_bindings()</code> to freeze dates, then runs the test suite. Requires <code>{testthat}</code>, <code>{usethis}</code>, and <code>{withr}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>test-design-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="co" style="color: #5E5E5E;"># Test design in practice: builds a throwaway package whose tests use a helper</span></span>
<span id="cb9-2"><span class="co" style="color: #5E5E5E;"># fixture, withr::local_tempdir() and local_options(), and</span></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;"># testthat::local_mocked_bindings() to freeze "today", then runs the tests.</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb9-5"><span class="co" style="color: #5E5E5E;">#   Rscript test-design-demo.R</span></span>
<span id="cb9-6"></span>
<span id="cb9-7">demo_files <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb9-8">  <span class="co" style="color: #5E5E5E;"># A thin wrapper around the clock, so tests can replace it.</span></span>
<span id="cb9-9">  <span class="st" style="color: #20794D;">"R/today.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-10">    <span class="st" style="color: #20794D;">"today &lt;- function() Sys.Date()"</span></span>
<span id="cb9-11">  ),</span>
<span id="cb9-12">  <span class="st" style="color: #20794D;">"R/days-since.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-13">    <span class="st" style="color: #20794D;">"#' Whole days from a date until today"</span>,</span>
<span id="cb9-14">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb9-15">    <span class="st" style="color: #20794D;">"days_since &lt;- function(date) {"</span>,</span>
<span id="cb9-16">    <span class="st" style="color: #20794D;">"  as.integer(today() - as.Date(date))"</span>,</span>
<span id="cb9-17">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb9-18">  ),</span>
<span id="cb9-19">  <span class="st" style="color: #20794D;">"R/report.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-20">    <span class="st" style="color: #20794D;">"#' Write a data frame to summary.csv in `dir`, returning the path"</span>,</span>
<span id="cb9-21">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb9-22">    <span class="st" style="color: #20794D;">"write_summary &lt;- function(data, dir) {"</span>,</span>
<span id="cb9-23">    <span class="st" style="color: #20794D;">"  path &lt;- file.path(dir, </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">summary.csv</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-24">    <span class="st" style="color: #20794D;">"  utils::write.csv(data, path, row.names = FALSE)"</span>,</span>
<span id="cb9-25">    <span class="st" style="color: #20794D;">"  path"</span>,</span>
<span id="cb9-26">    <span class="st" style="color: #20794D;">"}"</span>,</span>
<span id="cb9-27">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-28">    <span class="st" style="color: #20794D;">"#' Mean to one decimal place, using the session's decimal separator"</span>,</span>
<span id="cb9-29">    <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb9-30">    <span class="st" style="color: #20794D;">"format_mean &lt;- function(x) {"</span>,</span>
<span id="cb9-31">    <span class="st" style="color: #20794D;">"  format(round(mean(x), 1), nsmall = 1)"</span>,</span>
<span id="cb9-32">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb9-33">  ),</span>
<span id="cb9-34">  <span class="co" style="color: #5E5E5E;"># Helpers are sourced before the tests: fixtures live here.</span></span>
<span id="cb9-35">  <span class="st" style="color: #20794D;">"tests/testthat/helper-fixtures.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-36">    <span class="st" style="color: #20794D;">"# The smallest data set the tests need."</span>,</span>
<span id="cb9-37">    <span class="st" style="color: #20794D;">"make_subjects &lt;- function(n = 3) {"</span>,</span>
<span id="cb9-38">    <span class="st" style="color: #20794D;">"  data.frame("</span>,</span>
<span id="cb9-39">    <span class="st" style="color: #20794D;">"    USUBJID = sprintf(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">01-701-%04d</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, seq_len(n)),"</span>,</span>
<span id="cb9-40">    <span class="st" style="color: #20794D;">"    AGE = seq(60, by = 10, length.out = n)"</span>,</span>
<span id="cb9-41">    <span class="st" style="color: #20794D;">"  )"</span>,</span>
<span id="cb9-42">    <span class="st" style="color: #20794D;">"}"</span>,</span>
<span id="cb9-43">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-44">    <span class="st" style="color: #20794D;">"# A local_*() helper: a folder that is deleted when the calling test ends."</span>,</span>
<span id="cb9-45">    <span class="st" style="color: #20794D;">"local_output_dir &lt;- function(env = parent.frame()) {"</span>,</span>
<span id="cb9-46">    <span class="st" style="color: #20794D;">"  withr::local_tempdir(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">output-</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, .local_envir = env)"</span>,</span>
<span id="cb9-47">    <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb9-48">  ),</span>
<span id="cb9-49">  <span class="st" style="color: #20794D;">"tests/testthat/test-days-since.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-50">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">days_since() counts whole days up to today</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-51">    <span class="st" style="color: #20794D;">"  local_mocked_bindings(today = function() as.Date(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">2026-01-31</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">))"</span>,</span>
<span id="cb9-52">    <span class="st" style="color: #20794D;">"  expect_equal(days_since(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">2026-01-01</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">), 30L)"</span>,</span>
<span id="cb9-53">    <span class="st" style="color: #20794D;">"})"</span></span>
<span id="cb9-54">  ),</span>
<span id="cb9-55">  <span class="st" style="color: #20794D;">"tests/testthat/test-report.R"</span> <span class="ot" style="color: #003B4F;">=</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-56">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">write_summary() writes one row per subject</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-57">    <span class="st" style="color: #20794D;">"  dir &lt;- local_output_dir()"</span>,</span>
<span id="cb9-58">    <span class="st" style="color: #20794D;">"  path &lt;- write_summary(make_subjects(), dir)"</span>,</span>
<span id="cb9-59">    <span class="st" style="color: #20794D;">"  expect_true(file.exists(path))"</span>,</span>
<span id="cb9-60">    <span class="st" style="color: #20794D;">"  expect_equal(nrow(utils::read.csv(path)), 3)"</span>,</span>
<span id="cb9-61">    <span class="st" style="color: #20794D;">"})"</span>,</span>
<span id="cb9-62">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-63">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">format_mean() follows the decimal separator option</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-64">    <span class="st" style="color: #20794D;">"  withr::local_options(OutDec = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">,</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-65">    <span class="st" style="color: #20794D;">"  expect_equal(format_mean(c(1, 2)), </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">1,5</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-66">    <span class="st" style="color: #20794D;">"})"</span>,</span>
<span id="cb9-67">    <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-68">    <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">local_options() restores the option afterwards</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-69">    <span class="st" style="color: #20794D;">"  with_comma &lt;- function() {"</span>,</span>
<span id="cb9-70">    <span class="st" style="color: #20794D;">"    withr::local_options(OutDec = </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">,</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-71">    <span class="st" style="color: #20794D;">"    format_mean(c(1, 2))"</span>,</span>
<span id="cb9-72">    <span class="st" style="color: #20794D;">"  }"</span>,</span>
<span id="cb9-73">    <span class="st" style="color: #20794D;">"  expect_equal(with_comma(), </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">1,5</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-74">    <span class="st" style="color: #20794D;">"  expect_equal(format_mean(c(1, 2)), </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">1.5</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-75">    <span class="st" style="color: #20794D;">"})"</span></span>
<span id="cb9-76">  )</span>
<span id="cb9-77">)</span>
<span id="cb9-78"></span>
<span id="cb9-79"><span class="co" style="color: #5E5E5E;"># Creates the package and returns its path.</span></span>
<span id="cb9-80">make_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">path =</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"trialclock"</span>)) {</span>
<span id="cb9-81">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(path, <span class="at" style="color: #657422;">rstudio =</span> <span class="cn" style="color: #8f5902;">FALSE</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-82">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">with_project</span>(path, {</span>
<span id="cb9-83">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_testthat</span>(<span class="dv" style="color: #AD0000;">3</span>)</span>
<span id="cb9-84">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_package</span>(<span class="st" style="color: #20794D;">"withr"</span>, <span class="at" style="color: #657422;">type =</span> <span class="st" style="color: #20794D;">"Suggests"</span>)</span>
<span id="cb9-85">  })</span>
<span id="cb9-86">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (file <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">names</span>(demo_files)) {</span>
<span id="cb9-87">    <span class="fu" style="color: #4758AB;">writeLines</span>(demo_files[[file]], <span class="fu" style="color: #4758AB;">file.path</span>(path, file))</span>
<span id="cb9-88">  }</span>
<span id="cb9-89">  path</span>
<span id="cb9-90">}</span>
<span id="cb9-91"></span>
<span id="cb9-92"><span class="co" style="color: #5E5E5E;"># Loads the package from source and runs its tests (like devtools::test()).</span></span>
<span id="cb9-93">run_demo_tests <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path, <span class="at" style="color: #657422;">reporter =</span> testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">default_reporter</span>()) {</span>
<span id="cb9-94">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_local</span>(path, <span class="at" style="color: #657422;">reporter =</span> reporter, <span class="at" style="color: #657422;">stop_on_failure =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-95">}</span>
<span id="cb9-96"></span>
<span id="cb9-97"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb9-98"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb9-99">  path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">make_demo_package</span>()</span>
<span id="cb9-100">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_demo_tests</span>(path)</span>
<span id="cb9-101">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">as.data.frame</span>(results)[, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"file"</span>, <span class="st" style="color: #20794D;">"test"</span>, <span class="st" style="color: #20794D;">"nb"</span>, <span class="st" style="color: #20794D;">"failed"</span>)])</span>
<span id="cb9-102">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>withr</strong>: <a href="https://withr.r-lib.org/">withr.r-lib.org</a></li>
<li><strong>admiral</strong> (<code>derive_vars_dy()</code>): <a href="https://pharmaverse.github.io/admiral/">pharmaverse.github.io/admiral</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
<li><strong>pharmaversesdtm</strong>: <a href="https://pharmaverse.github.io/pharmaversesdtm/">pharmaverse.github.io/pharmaversesdtm</a></li>
</ul>
<p><strong>Web-repo comparison</strong></p>
<ul>
<li><strong>Vitest</strong> (<code>vi.useFakeTimers()</code>, <code>vi.setSystemTime()</code>): <a href="https://vitest.dev/">vitest.dev</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist. Marked package-dependent testthat blocks as .norun.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-series-nav__series">Testing series · part 2 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 1</span><span class="site-related-card__title">testthat essentials</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 3</span><span class="site-related-card__title">Snapshot tests for R output, tables and plots</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/property-based-testing/index.html" class="site-link-row" title="Define general invariants, generate varied test inputs with quickcheck, and use shrinking to pinpoint edge cases in R functions and clinical derivations."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Property-based testing in R</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/index.html" class="site-link-row" title="Move reusable analysis helpers from sourced scripts into a minimal R package, and replace workspace pollution with the devtools::load_all() loop."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">From scripts to a package</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="site-link-row" title="Use the R package development loop, read R CMD check diagnostics, and fix four recurring problems."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">The package development loop and R CMD check</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Test your guardrails: probe PRs</title>
  <link>https://insightsurge-dev.web.app/posts/test-your-guardrails/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-idea" class="level2">
<h2 class="anchored" data-anchor-id="the-idea">The idea</h2>
<p>After setting up hooks and CI, it’s tempting to open one clean PR, see green ticks and move on. But green only proves the checks <em>can pass</em>. It doesn’t prove they <strong>fail when they should</strong>. A misspelled trigger, a path filter, a <code>continue-on-error</code>, a missing licence key: any of these gives you a check that is always green.</p>
<p>So we <strong>challenge</strong> each guardrail on purpose, with throwaway PRs designed to fail.</p>
</section>
<section id="the-probes-we-ran" class="level2">
<h2 class="anchored" data-anchor-id="the-probes-we-ran">The probes we ran</h2>
<p>Each probe was a branch from <code>main</code> with one deliberate defect, opened as a PR and <strong>closed unmerged</strong> afterwards:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>Probe</th>
<th>Defect</th>
<th>Expected</th>
<th>Observed</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Local</td>
<td>Commit message <code>initial stuff</code></td>
<td>commit-msg hook rejects</td>
<td>Rejected: <em>subject may not be empty, type may not be empty</em></td>
</tr>
<tr class="even">
<td>PR A</td>
<td>Title <code>updated the readme</code></td>
<td>PR-title check fails; others pass</td>
<td><em>No release type found in pull request title</em></td>
</tr>
<tr class="odd">
<td>PR B</td>
<td><code>const x: number = "not a number"</code></td>
<td>CI fails <strong>at the typecheck step</strong></td>
<td>Typecheck: failure; tests and build skipped; lint passed</td>
</tr>
<tr class="even">
<td>PR C</td>
<td>Random <code>ghp_…</code> token in a text file</td>
<td>Secret scan fails</td>
<td>gitleaks rule <code>github-pat</code>, pointing at the file</td>
</tr>
<tr class="odd">
<td>PR D</td>
<td>A harmless doc change</td>
<td>Everything passes</td>
<td>All green</td>
</tr>
</tbody>
</table>
</div>
<p>PR D matters as much as the others. It proves the checks aren’t simply broken and red for everything.</p>
</section>
<section id="read-the-log-not-the-colour" class="level2">
<h2 class="anchored" data-anchor-id="read-the-log-not-the-colour">Read the log, not the colour</h2>
<p>A red cross only proves <em>something</em> failed. For each probe we opened the log and confirmed it failed <strong>for the planted reason</strong>. PR B, for example, had to fail at <em>Typecheck</em>, not at lint or install. A probe that fails for the wrong reason tells you nothing about the guardrail. Track any gaps exposed by failing probes as engineering issues to resolve.</p>
</section>
<section id="what-the-probes-taught-us" class="level2">
<h2 class="anchored" data-anchor-id="what-the-probes-taught-us">What the probes taught us</h2>
<ul>
<li><strong>A gap resolved:</strong> the planted token initially passed the local pre-commit hook (which only formatted code) and was caught only in CI after being pushed. We followed up by integrating <strong>secretlint</strong> into pre-commit (<code>lint-staged</code>) and re-probed successfully: a fake <code>ghp_</code> token was blocked on the laptop before the commit could even be created (see <a href="https://insightsurge-dev.web.app/posts/secret-scanning/index.html">secret scanning</a>).</li>
<li><strong>A surprise:</strong> after deleting the probe branch, its commit was <strong>still served</strong> by the GitHub API through the closed PR. Deleting a branch doesn’t delete what was pushed. Only use <em>fake</em> secrets for probes.</li>
</ul>
</section>
<section id="the-r-version" class="level2">
<h2 class="anchored" data-anchor-id="the-r-version">The R version</h2>
<p>The same probes work for an R package or Shiny repo:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Guardrail</th>
<th>Probe</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>R CMD check</code> workflow</td>
<td>A PR that adds <code>stop("probe")</code> inside a tested function, or an undeclared <code>pkg::fn()</code></td>
</tr>
<tr class="even">
<td><code>lintr</code> / Air check</td>
<td>A PR with <code>x = 1</code> and a 200-character line</td>
</tr>
<tr class="odd">
<td><code>shinytest2</code> snapshots</td>
<td>A PR that changes a UI label without updating the snapshot</td>
</tr>
<tr class="even">
<td>PR-title check</td>
<td><code>updated stuff</code></td>
</tr>
<tr class="odd">
<td>gitleaks</td>
<td>A fake <code>ghp_</code> + 36 random characters (never a real token)</td>
</tr>
<tr class="even">
<td>Coverage threshold</td>
<td>A PR that adds an untested function</td>
</tr>
</tbody>
</table>
</div>
<p>Generate a fake token that matches the pattern but has never existed:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="bu" style="color: null;">echo</span> <span class="st" style="color: #20794D;">"token=ghp_</span><span class="va" style="color: #111111;">$(LC_ALL</span><span class="op" style="color: #5E5E5E;">=</span>C <span class="fu" style="color: #4758AB;">tr</span> <span class="at" style="color: #657422;">-dc</span> <span class="st" style="color: #20794D;">'A-Za-z0-9'</span> <span class="op" style="color: #5E5E5E;">&lt;</span>/dev/urandom <span class="kw" style="color: #003B4F;
font-weight: bold;">|</span> <span class="fu" style="color: #4758AB;">head</span> <span class="at" style="color: #657422;">-c</span> 36<span class="va" style="color: #111111;">)</span><span class="st" style="color: #20794D;">"</span> <span class="op" style="color: #5E5E5E;">&gt;</span> leak-probe.txt</span></code></pre></div></div>
</section>
<section id="the-gxp-link-this-is-oq-for-your-own-quality-system" class="level2">
<h2 class="anchored" data-anchor-id="the-gxp-link-this-is-oq-for-your-own-quality-system">The GxP link: this is OQ for your own quality system</h2>
<p>Validation people will recognise this as <strong>challenge testing</strong>. In operational qualification you show an alarm trips at its limit, not just that it stays quiet in normal operation. Probe PRs are OQ for your development controls, and the closed PRs, with their logs, are the evidence. Re-run them when you change a workflow, runner or major action version.</p>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Tools used in the probes</strong></p>
<ul>
<li><strong>gitleaks</strong>: <a href="https://github.com/gitleaks/gitleaks">github.com/gitleaks/gitleaks</a></li>
<li><strong>secretlint</strong>: <a href="https://github.com/secretlint/secretlint">github.com/secretlint/secretlint</a></li>
<li><strong>shinytest2</strong>: <a href="https://rstudio.github.io/shinytest2/">rstudio.github.io/shinytest2</a></li>
</ul>
<section id="further-reading" class="level3">
<h3 class="anchored">Further reading</h3>
<ul>
<li><strong>GAMP 5 (2nd Edition)</strong>, the source of the operational-qualification (OQ) idea this post borrows: <a href="https://ispe.org/publications/guidance-documents/gamp-5-guide-2nd-edition">ispe.org</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Closed the pre-commit scanning gap identified during initial probe testing. Added <strong>secretlint</strong> to the staged-files pre-commit pipeline (see <a href="https://insightsurge-dev.web.app/posts/secret-scanning/index.html">secret scanning</a>) and re-probed successfully: staged test tokens are blocked locally before commit creation.</li>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/foundations.html" class="site-series-nav__series">Foundations series · part 11 of 16</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/dependencies-runtime-vetting/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 10</span><span class="site-related-card__title">Dependency updates, runtime pinning &amp; package vetting</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/adrs-and-evidence/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 12</span><span class="site-related-card__title">ADRs &amp; evidence: record decisions, verify docs</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="site-link-row" title="Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Coverage and tests as evidence</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/git-workflow/index.html" class="site-link-row" title="A predictable branch-and-PR workflow for R teams with branch protection, squash merges, and signed commits."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Git workflow: branches, squash-only merges, signed commits</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/keyless-ci-auth-oidc/index.html" class="site-link-row" title="Use OpenID Connect and Google Cloud Workload Identity Federation to authenticate CI pipelines without long-lived JSON keys."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Keyless deploys: let CI prove who it is (OIDC)</span></a></li>
</ul>
</div>
</section>
</div>

</section>
</section>

 ]]></description>
  <category>CI/CD</category>
  <category>GxP</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/test-your-guardrails/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>Testing Shiny server logic with testServer()</title>
  <link>https://insightsurge-dev.web.app/posts/shiny-testserver/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Interactive Shiny applications rely on a reactive dependency graph: user inputs invalidate reactive expressions, observers execute, and outputs re-render.</p>
<p>Most teams test this interactively: start the app, wait for the browser, click dropdowns, and eyeball the result.</p>
<p>Interactive manual testing breaks down as applications grow:</p>
<ul>
<li><strong>Slow and unrepeatable:</strong> Navigating multi-tab workflows takes minutes, cannot run in CI, and leaves no record.</li>
<li><strong>Unclear failure boundaries:</strong> When an exploratory click yields a wrong number, you cannot tell whether the fault lies in input serialization, data transformation, reactive invalidation, or HTML rendering.</li>
<li><strong>Untested edge cases:</strong> Checking missing baselines or empty clinical subgroups requires tedious clicking that teams skip under deadline pressure.</li>
</ul>
<p>Manual browser checking couples business calculations to browser rendering. We need headless, automated tests that isolate server logic from the web browser.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>Web engineering teams hit the same problem. Running browser suites with Playwright or Cypress for every calculation is slow and brittle.</p>
<p>Web engineering separates testing into three tiers:</p>
<ol type="1">
<li><strong>Pure domain logic:</strong> Data transformations and business rules live in pure TypeScript functions with no browser dependencies, tested with Vitest or Jest.</li>
<li><strong>Headless state and hook testing:</strong> Custom state hooks and state machines are tested in memory without opening a browser using <code>@testing-library/react</code> and <code>renderHook</code>:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb1-1"><span class="co" style="color: #5E5E5E;">// src/use-safety-filter.test.ts</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;">import</span> { renderHook<span class="op" style="color: #5E5E5E;">,</span> act } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"@testing-library/react"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-3"><span class="im" style="color: #00769E;">import</span> { useSafetyFilter } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"./use-safety-filter"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-4"><span class="im" style="color: #00769E;">import</span> { mockParticipants } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"./fixtures"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-5"></span>
<span id="cb1-6"><span class="fu" style="color: #4758AB;">describe</span>(<span class="st" style="color: #20794D;">"useSafetyFilter"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-7">  <span class="fu" style="color: #4758AB;">it</span>(<span class="st" style="color: #20794D;">"filters participants and updates summary counts on arm change"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-8">    <span class="kw" style="color: #003B4F;
font-weight: bold;">const</span> { result } <span class="op" style="color: #5E5E5E;">=</span> <span class="fu" style="color: #4758AB;">renderHook</span>(() <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> <span class="fu" style="color: #4758AB;">useSafetyFilter</span>(mockParticipants))<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-9"></span>
<span id="cb1-10">    <span class="fu" style="color: #4758AB;">expect</span>(result<span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">current</span><span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">selectedCount</span>)<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toBe</span>(<span class="dv" style="color: #AD0000;">254</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-11"></span>
<span id="cb1-12">    <span class="fu" style="color: #4758AB;">act</span>(() <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-13">      result<span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">current</span><span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">setArm</span>(<span class="st" style="color: #20794D;">"Placebo"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-14">    })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-15"></span>
<span id="cb1-16">    <span class="fu" style="color: #4758AB;">expect</span>(result<span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">current</span><span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">selectedCount</span>)<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toBe</span>(<span class="dv" style="color: #AD0000;">86</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-17">    <span class="fu" style="color: #4758AB;">expect</span>(result<span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">current</span><span class="op" style="color: #5E5E5E;">.</span><span class="at" style="color: #657422;">statusText</span>)<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toBe</span>(</span>
<span id="cb1-18">      <span class="st" style="color: #20794D;">"Placebo: 86 of 254 subjects (safety population)"</span></span>
<span id="cb1-19">    )<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-20">  })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-21">})<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<ol start="3" type="1">
<li><strong>End-to-end browser tests:</strong> Real browsers verify page rendering, CSS layout, and user flows.</li>
</ol>
<p>The middle tier—headless state testing—is fast, deterministic, and tests reactive transitions without browser overhead.</p>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In R, <a href="https://cran.r-project.org/package=shiny">{shiny}</a> mirrors this three-tier architecture:</p>
<ol type="1">
<li>Extract business logic into <strong>pure R functions</strong> tested with <a href="https://testthat.r-lib.org/">{testthat}</a> (see <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html">testthat essentials</a>).</li>
<li>Test reactive wiring, inputs, observers, rendered outputs, and module return values headless in memory with <code>shiny::testServer()</code>.</li>
<li>Reserve end-to-end browser tests for visual rendering and user workflows.</li>
</ol>
<section id="separating-pure-domain-logic-from-reactive-wiring" class="level3">
<h3 class="anchored" data-anchor-id="separating-pure-domain-logic-from-reactive-wiring">1 · Separating pure domain logic from reactive wiring</h3>
<p>The most useful rule for testable Shiny code: <strong>keep reactives thin</strong>.</p>
<p>When filtering and clinical derivations sit inside <code>shiny::reactive()</code> or <code>shiny::renderText()</code>, they cannot be tested without a reactive context.</p>
<p>Consider a clinical trial module that filters <code>pharmaverseadam::adsl</code> to the safety population (<code>SAFFL == "Y"</code>) and calculates subject counts for a selected treatment arm (<code>TRT01A</code>). Extracting the domain logic into a pure R function leaves the calculation independent of Shiny:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;">#' Filter safety population and summarize treatment arm counts</span></span>
<span id="cb2-2">summarize_safety_arm <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data, <span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"All"</span>) {</span>
<span id="cb2-3">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.data.frame</span>(data)) {</span>
<span id="cb2-4">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`data` must be a data frame."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb2-5">  }</span>
<span id="cb2-6">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">all</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"SAFFL"</span>, <span class="st" style="color: #20794D;">"TRT01A"</span>) <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">names</span>(data))) {</span>
<span id="cb2-7">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`data` must contain `SAFFL` and `TRT01A` columns."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb2-8">  }</span>
<span id="cb2-9"></span>
<span id="cb2-10">  saffl_data <span class="ot" style="color: #003B4F;">&lt;-</span> data[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(data<span class="sc" style="color: #5E5E5E;">$</span>SAFFL) <span class="sc" style="color: #5E5E5E;">&amp;</span> data<span class="sc" style="color: #5E5E5E;">$</span>SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>, , drop <span class="ot" style="color: #003B4F;">=</span> <span class="cn" style="color: #8f5902;">FALSE</span>]</span>
<span id="cb2-11">  n_total <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">nrow</span>(saffl_data)</span>
<span id="cb2-12"></span>
<span id="cb2-13">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">identical</span>(arm, <span class="st" style="color: #20794D;">"All"</span>)) {</span>
<span id="cb2-14">    filtered <span class="ot" style="color: #003B4F;">&lt;-</span> saffl_data</span>
<span id="cb2-15">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb2-16">    filtered <span class="ot" style="color: #003B4F;">&lt;-</span> saffl_data[</span>
<span id="cb2-17">      <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(saffl_data<span class="sc" style="color: #5E5E5E;">$</span>TRT01A) <span class="sc" style="color: #5E5E5E;">&amp;</span> saffl_data<span class="sc" style="color: #5E5E5E;">$</span>TRT01A <span class="sc" style="color: #5E5E5E;">==</span> arm,</span>
<span id="cb2-18">      ,</span>
<span id="cb2-19">      drop <span class="ot" style="color: #003B4F;">=</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb2-20">    ]</span>
<span id="cb2-21">  }</span>
<span id="cb2-22"></span>
<span id="cb2-23">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb2-24">    <span class="at" style="color: #657422;">data =</span> filtered,</span>
<span id="cb2-25">    <span class="at" style="color: #657422;">n_arm =</span> <span class="fu" style="color: #4758AB;">nrow</span>(filtered),</span>
<span id="cb2-26">    <span class="at" style="color: #657422;">n_total =</span> n_total,</span>
<span id="cb2-27">    <span class="at" style="color: #657422;">arm =</span> arm</span>
<span id="cb2-28">  )</span>
<span id="cb2-29">}</span></code></pre></div></div>
<p>This function, and the module functions shown later, are copied from the companion script (<a href="https://insightsurge-dev.web.app/posts/shiny-testserver/scripts/module-demo.R">scripts/module-demo.R</a>); a test fails if the copies ever differ. Because <code>summarize_safety_arm()</code> is a plain R function, you can write unit tests with standard testthat assertions without any Shiny session:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">adsl <span class="ot" style="color: #003B4F;">&lt;-</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl</span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;"># Verify safety population filtering against baseline data</span></span>
<span id="cb3-4">all_res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">summarize_safety_arm</span>(adsl, <span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"All"</span>)</span>
<span id="cb3-5">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(all_res<span class="sc" style="color: #5E5E5E;">$</span>n_total, <span class="dv" style="color: #AD0000;">254</span>L)</span>
<span id="cb3-6">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(all_res<span class="sc" style="color: #5E5E5E;">$</span>n_arm, <span class="dv" style="color: #AD0000;">254</span>L)</span>
<span id="cb3-7"></span>
<span id="cb3-8"><span class="co" style="color: #5E5E5E;"># Verify treatment arm subsetting</span></span>
<span id="cb3-9">pbo_res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">summarize_safety_arm</span>(adsl, <span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Placebo"</span>)</span>
<span id="cb3-10">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(pbo_res<span class="sc" style="color: #5E5E5E;">$</span>n_arm, <span class="dv" style="color: #AD0000;">86</span>L)</span>
<span id="cb3-11">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(pbo_res<span class="sc" style="color: #5E5E5E;">$</span>n_total, <span class="dv" style="color: #AD0000;">254</span>L)</span>
<span id="cb3-12"></span>
<span id="cb3-13"><span class="co" style="color: #5E5E5E;"># Verify input validation guardrails</span></span>
<span id="cb3-14">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_error</span>(</span>
<span id="cb3-15">  <span class="fu" style="color: #4758AB;">summarize_safety_arm</span>(<span class="fu" style="color: #4758AB;">list</span>()),</span>
<span id="cb3-16">  <span class="st" style="color: #20794D;">"`data` must be a data frame."</span></span>
<span id="cb3-17">)</span></code></pre></div></div>
<p>With domain calculations tested directly, the module server only handles reactive orchestration:</p>
</section>
<section id="headless-module-testing-with-testserver" class="level3">
<h3 class="anchored" data-anchor-id="headless-module-testing-with-testserver">2 · Headless module testing with testServer()</h3>
<p>Shiny modules pair UI with server logic wrapped in <code>shiny::moduleServer()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">arm_filter_ui <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb4-2">    id,</span>
<span id="cb4-3">    <span class="at" style="color: #657422;">arms =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"All"</span>, <span class="st" style="color: #20794D;">"Placebo"</span>, <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>, <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)) {</span>
<span id="cb4-4">  ns <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">NS</span>(id)</span>
<span id="cb4-5">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">tagList</span>(</span>
<span id="cb4-6">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">selectInput</span>(</span>
<span id="cb4-7">      <span class="at" style="color: #657422;">inputId =</span> <span class="fu" style="color: #4758AB;">ns</span>(<span class="st" style="color: #20794D;">"arm"</span>),</span>
<span id="cb4-8">      <span class="at" style="color: #657422;">label =</span> <span class="st" style="color: #20794D;">"Treatment Arm:"</span>,</span>
<span id="cb4-9">      <span class="at" style="color: #657422;">choices =</span> arms,</span>
<span id="cb4-10">      <span class="at" style="color: #657422;">selected =</span> <span class="st" style="color: #20794D;">"All"</span></span>
<span id="cb4-11">    ),</span>
<span id="cb4-12">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">textOutput</span>(<span class="at" style="color: #657422;">outputId =</span> <span class="fu" style="color: #4758AB;">ns</span>(<span class="st" style="color: #20794D;">"summary_text"</span>))</span>
<span id="cb4-13">  )</span>
<span id="cb4-14">}</span>
<span id="cb4-15"></span>
<span id="cb4-16">arm_filter_server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(id, <span class="at" style="color: #657422;">data =</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl) {</span>
<span id="cb4-17">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">moduleServer</span>(id, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb4-18">    resolved_data <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>({</span>
<span id="cb4-19">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">is.reactive</span>(data)) {</span>
<span id="cb4-20">        <span class="fu" style="color: #4758AB;">data</span>()</span>
<span id="cb4-21">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb4-22">        data</span>
<span id="cb4-23">      }</span>
<span id="cb4-24">    })</span>
<span id="cb4-25"></span>
<span id="cb4-26">    summary_res <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>({</span>
<span id="cb4-27">      selected_arm <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(input<span class="sc" style="color: #5E5E5E;">$</span>arm)) <span class="st" style="color: #20794D;">"All"</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> input<span class="sc" style="color: #5E5E5E;">$</span>arm</span>
<span id="cb4-28">      <span class="fu" style="color: #4758AB;">summarize_safety_arm</span>(<span class="fu" style="color: #4758AB;">resolved_data</span>(), <span class="at" style="color: #657422;">arm =</span> selected_arm)</span>
<span id="cb4-29">    })</span>
<span id="cb4-30"></span>
<span id="cb4-31">    output<span class="sc" style="color: #5E5E5E;">$</span>summary_text <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">renderText</span>({</span>
<span id="cb4-32">      res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">summary_res</span>()</span>
<span id="cb4-33">      <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb4-34">        <span class="st" style="color: #20794D;">"%s: %d of %d subjects (safety population)"</span>,</span>
<span id="cb4-35">        res<span class="sc" style="color: #5E5E5E;">$</span>arm,</span>
<span id="cb4-36">        res<span class="sc" style="color: #5E5E5E;">$</span>n_arm,</span>
<span id="cb4-37">        res<span class="sc" style="color: #5E5E5E;">$</span>n_total</span>
<span id="cb4-38">      )</span>
<span id="cb4-39">    })</span>
<span id="cb4-40"></span>
<span id="cb4-41">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>(<span class="fu" style="color: #4758AB;">summary_res</span>())</span>
<span id="cb4-42">  })</span>
<span id="cb4-43">}</span></code></pre></div></div>
<p>To test <code>arm_filter_server</code> without launching a browser, call <code>shiny::testServer()</code>. Its signature is:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;">testServer</span>(<span class="at" style="color: #657422;">app =</span> <span class="cn" style="color: #8f5902;">NULL</span>, expr, <span class="at" style="color: #657422;">args =</span> <span class="fu" style="color: #4758AB;">list</span>(), <span class="at" style="color: #657422;">session =</span> MockShinySession<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">new</span>())</span></code></pre></div></div>
<p>Inside <code>expr</code>, <code>testServer()</code> evaluates expressions using <code>rlang::eval_tidy()</code> with a data mask over the server environment. This gives direct access to:</p>
<ul>
<li><code>session$setInputs(...)</code> to simulate user inputs and trigger reactive flushes.</li>
<li>Server reactives and variables by name (e.g.&nbsp;<code>summary_res()</code>).</li>
<li>Rendered outputs via <code>output$&lt;name&gt;</code> (e.g.&nbsp;<code>output$summary_text</code>).</li>
<li>Module return values via <code>session$returned</code> and <code>session$getReturned()</code>.</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">testServer</span>(arm_filter_server, <span class="at" style="color: #657422;">args =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">data =</span> adsl), {</span>
<span id="cb6-2">  <span class="co" style="color: #5E5E5E;"># Default input state: "All"</span></span>
<span id="cb6-3">  session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"All"</span>)</span>
<span id="cb6-4">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, <span class="dv" style="color: #AD0000;">254</span>L)</span>
<span id="cb6-5">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_total, <span class="dv" style="color: #AD0000;">254</span>L)</span>
<span id="cb6-6">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(</span>
<span id="cb6-7">    output<span class="sc" style="color: #5E5E5E;">$</span>summary_text,</span>
<span id="cb6-8">    <span class="st" style="color: #20794D;">"All: 254 of 254 subjects (safety population)"</span></span>
<span id="cb6-9">  )</span>
<span id="cb6-10"></span>
<span id="cb6-11">  <span class="co" style="color: #5E5E5E;"># Change input to Placebo</span></span>
<span id="cb6-12">  session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Placebo"</span>)</span>
<span id="cb6-13">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, <span class="dv" style="color: #AD0000;">86</span>L)</span>
<span id="cb6-14">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(</span>
<span id="cb6-15">    output<span class="sc" style="color: #5E5E5E;">$</span>summary_text,</span>
<span id="cb6-16">    <span class="st" style="color: #20794D;">"Placebo: 86 of 254 subjects (safety population)"</span></span>
<span id="cb6-17">  )</span>
<span id="cb6-18"></span>
<span id="cb6-19">  <span class="co" style="color: #5E5E5E;"># Change input to Xanomeline High Dose</span></span>
<span id="cb6-20">  session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)</span>
<span id="cb6-21">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, <span class="dv" style="color: #AD0000;">72</span>L)</span>
<span id="cb6-22">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(</span>
<span id="cb6-23">    output<span class="sc" style="color: #5E5E5E;">$</span>summary_text,</span>
<span id="cb6-24">    <span class="st" style="color: #20794D;">"Xanomeline High Dose: 72 of 254 subjects (safety population)"</span></span>
<span id="cb6-25">  )</span>
<span id="cb6-26">})</span></code></pre></div></div>
<p><code>session$setInputs()</code> updates the mock session’s inputs and automatically triggers an internal reactive flush, allowing synchronous assertions right after each input change.</p>
</section>
<section id="module-return-values-session-return-bindings-and-getreturned" class="level3">
<h3 class="anchored" data-anchor-id="module-return-values-session-return-bindings-and-getreturned">3 · Module return values: session return bindings and getReturned()</h3>
<p>Modules often return reactives to parent callers. In <code>shiny::MockShinySession</code>, two mechanisms expose the return value:</p>
<ol type="1">
<li><code>session$returned</code>: A public field on the mock session.</li>
<li><code>session$getReturned()</code>: An accessor method returning <code>self$returned</code>.</li>
</ol>
<p>Both point to the same object (<code>identical(session$returned, session$getReturned())</code> is <code>TRUE</code>).</p>
<p>What <code>session$returned</code> holds matches what the module returns:</p>
<ul>
<li>If the module returns a <strong>reactive expression</strong> (like <code>shiny::reactive(summary_res())</code>), <code>session$returned</code> holds that reactive function. Call it with parentheses: <code>session$returned()</code> or <code>session$getReturned()()</code>.</li>
<li>If the module returns a <strong>static value</strong>, <code>session$returned</code> holds it directly.</li>
<li>If the module returns a <strong>list of reactives</strong>, access each as <code>session$returned$counts()</code> or <code>session$getReturned()$counts()</code>.</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">testServer</span>(arm_filter_server, <span class="at" style="color: #657422;">args =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">data =</span> adsl), {</span>
<span id="cb7-2">  session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Placebo"</span>)</span>
<span id="cb7-3"></span>
<span id="cb7-4">  <span class="co" style="color: #5E5E5E;"># session$returned holds the reactive expression returned by moduleServer</span></span>
<span id="cb7-5">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_true</span>(shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">is.reactive</span>(session<span class="sc" style="color: #5E5E5E;">$</span>returned))</span>
<span id="cb7-6"></span>
<span id="cb7-7">  <span class="co" style="color: #5E5E5E;"># Evaluate the returned reactive function</span></span>
<span id="cb7-8">  res <span class="ot" style="color: #003B4F;">&lt;-</span> session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">returned</span>()</span>
<span id="cb7-9">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(res<span class="sc" style="color: #5E5E5E;">$</span>n_arm, <span class="dv" style="color: #AD0000;">86</span>L)</span>
<span id="cb7-10">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(res<span class="sc" style="color: #5E5E5E;">$</span>n_total, <span class="dv" style="color: #AD0000;">254</span>L)</span>
<span id="cb7-11"></span>
<span id="cb7-12">  <span class="co" style="color: #5E5E5E;"># session$getReturned() returns the exact same object</span></span>
<span id="cb7-13">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_identical</span>(session<span class="sc" style="color: #5E5E5E;">$</span>returned, session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">getReturned</span>())</span>
<span id="cb7-14">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">getReturned</span>()()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, <span class="dv" style="color: #AD0000;">86</span>L)</span>
<span id="cb7-15">})</span></code></pre></div></div>
</section>
<section id="whole-app-servers-and-reactive-flushes" class="level3">
<h3 class="anchored" data-anchor-id="whole-app-servers-and-reactive-flushes">4 · Whole-app servers and reactive flushes</h3>
<p><code>testServer()</code> also tests whole-application server functions (<code>server &lt;- function(input, output, session)</code>). When testing an app server that embeds modules, inputs within modules use hyphenated namespace IDs:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">app_server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb8-2">  arm_data <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">arm_filter_server</span>(<span class="st" style="color: #20794D;">"filter_sub"</span>, <span class="at" style="color: #657422;">data =</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl)</span>
<span id="cb8-3"></span>
<span id="cb8-4">  total_selected <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>({</span>
<span id="cb8-5">    <span class="fu" style="color: #4758AB;">arm_data</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm</span>
<span id="cb8-6">  })</span>
<span id="cb8-7"></span>
<span id="cb8-8">  output<span class="sc" style="color: #5E5E5E;">$</span>status <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">renderText</span>({</span>
<span id="cb8-9">    <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Selected %d participants"</span>, <span class="fu" style="color: #4758AB;">total_selected</span>())</span>
<span id="cb8-10">  })</span>
<span id="cb8-11">}</span>
<span id="cb8-12"></span>
<span id="cb8-13">shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">testServer</span>(app_server, {</span>
<span id="cb8-14">  session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="st" style="color: #20794D;">`</span><span class="at" style="color: #657422;">filter_sub-arm</span><span class="st" style="color: #20794D;">`</span> <span class="ot" style="color: #003B4F;">=</span> <span class="st" style="color: #20794D;">"Placebo"</span>)</span>
<span id="cb8-15">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">total_selected</span>(), <span class="dv" style="color: #AD0000;">86</span>L)</span>
<span id="cb8-16">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(output<span class="sc" style="color: #5E5E5E;">$</span>status, <span class="st" style="color: #20794D;">"Selected 86 participants"</span>)</span>
<span id="cb8-17"></span>
<span id="cb8-18">  session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="st" style="color: #20794D;">`</span><span class="at" style="color: #657422;">filter_sub-arm</span><span class="st" style="color: #20794D;">`</span> <span class="ot" style="color: #003B4F;">=</span> <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>)</span>
<span id="cb8-19">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">total_selected</span>(), <span class="dv" style="color: #AD0000;">96</span>L)</span>
<span id="cb8-20">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(output<span class="sc" style="color: #5E5E5E;">$</span>status, <span class="st" style="color: #20794D;">"Selected 96 participants"</span>)</span>
<span id="cb8-21">})</span></code></pre></div></div>
<p>While <code>session$setInputs()</code> flushes dependencies automatically, reactive state can also change outside <code>setInputs()</code>—for example, when a module receives a shared <code>shiny::reactiveVal()</code> or an external data feed. In those cases, calling <code>session$flushReact()</code> triggers the flush cycle on demand:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">shared_flag <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactiveVal</span>(<span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-2"></span>
<span id="cb9-3">monitor_server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(id, <span class="at" style="color: #657422;">flag =</span> shared_flag) {</span>
<span id="cb9-4">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">moduleServer</span>(id, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb9-5">    status <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactiveVal</span>(<span class="st" style="color: #20794D;">"idle"</span>)</span>
<span id="cb9-6">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">observe</span>({</span>
<span id="cb9-7">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">flag</span>()) {</span>
<span id="cb9-8">        <span class="fu" style="color: #4758AB;">status</span>(<span class="st" style="color: #20794D;">"active"</span>)</span>
<span id="cb9-9">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb9-10">        <span class="fu" style="color: #4758AB;">status</span>(<span class="st" style="color: #20794D;">"idle"</span>)</span>
<span id="cb9-11">      }</span>
<span id="cb9-12">    })</span>
<span id="cb9-13">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>(<span class="fu" style="color: #4758AB;">status</span>())</span>
<span id="cb9-14">  })</span>
<span id="cb9-15">}</span>
<span id="cb9-16"></span>
<span id="cb9-17">shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">testServer</span>(monitor_server, <span class="at" style="color: #657422;">args =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">flag =</span> shared_flag), {</span>
<span id="cb9-18">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">returned</span>(), <span class="st" style="color: #20794D;">"idle"</span>)</span>
<span id="cb9-19"></span>
<span id="cb9-20">  <span class="co" style="color: #5E5E5E;"># Mutate external reactive value directly</span></span>
<span id="cb9-21">  <span class="fu" style="color: #4758AB;">shared_flag</span>(<span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb9-22"></span>
<span id="cb9-23">  <span class="co" style="color: #5E5E5E;"># Before flush: observer has not executed yet</span></span>
<span id="cb9-24">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">returned</span>(), <span class="st" style="color: #20794D;">"idle"</span>)</span>
<span id="cb9-25"></span>
<span id="cb9-26">  <span class="co" style="color: #5E5E5E;"># Explicitly flush the reactive domain</span></span>
<span id="cb9-27">  session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">flushReact</span>()</span>
<span id="cb9-28">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">expect_equal</span>(session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">returned</span>(), <span class="st" style="color: #20794D;">"active"</span>)</span>
<span id="cb9-29">})</span></code></pre></div></div>
</section>
<section id="what-testserver-cannot-test" class="level3">
<h3 class="anchored" data-anchor-id="what-testserver-cannot-test">5 · What testServer() cannot test</h3>
<p><code>testServer()</code> executes inside a simulated headless session with <code>shiny::MockShinySession</code>. Its boundaries are clear:</p>
<ul>
<li><strong>No browser DOM:</strong> HTML is not parsed, laid out, or rendered. <code>testServer()</code> cannot test CSS layout, responsive breakpoints, font rendering, or whether an element is visually hidden.</li>
<li><strong>No JavaScript execution:</strong> Custom JavaScript bindings (<code>Shiny.addCustomMessageHandler</code>, <code>Shiny.setInputValue</code> from client scripts, jQuery handlers, and HTML widgets) do not run.</li>
<li><strong>No client-server network interaction:</strong> Websocket reconnections, file uploads through browser dialogs, and latency effects cannot be tested with <code>testServer()</code>.</li>
</ul>
<p>For full browser rendering, client-side JavaScript, and visual regression checks, we use end-to-end browser testing with <code>{shinytest2}</code>, which is covered in a subsequent post.</p>
</section>
<section id="tests-as-evidence-the-gxp-pharma-angle" class="level3">
<h3 class="anchored" data-anchor-id="tests-as-evidence-the-gxp-pharma-angle">6 · Tests as evidence: the GxP pharma angle</h3>
<p>In clinical trial reporting, interactive Shiny dashboards are increasingly deployed for safety monitoring, cohort filtering, and protocol deviation tracking.</p>
<p>Under GxP validation expectations, manual ad-hoc clicking does not constitute verifiable evidence. Automated tests provide:</p>
<ul>
<li><strong>Automated execution:</strong> Running on every pull request via continuous integration.</li>
<li><strong>Traceable requirements:</strong> A test’s description can name the requirement it checks (for example “safety population = subjects with <code>SAFFL == "Y"</code>”), and the test computes the expected value from that rule, not from a copied number.</li>
<li><strong>Regression protection:</strong> Refactoring UI styles or layout cannot inadvertently alter underlying clinical counts without tripping test failures.</li>
</ul>
<p>Continuous integration keeps the test results with the commit, which a later post in the series turns into evidence.</p>
</section>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Burying business logic in reactives:</strong> Writing complex data wrangling inside <code>shiny::reactive()</code> makes testing cumbersome. Move domain calculations into pure helper functions and test them with <code>testthat::expect_equal()</code> before testing the module.</li>
<li><strong>Confusing module return invocation:</strong> If your module returns <code>shiny::reactive(...)</code>, calling <code>session$returned</code> returns the reactive function, not its evaluated value. Call <code>session$returned()</code> or <code>session$getReturned()()</code>.</li>
<li><strong>Expecting JavaScript to run in testServer():</strong> If your module depends on a custom JavaScript input handler, <code>testServer()</code> will not invoke it. Pass simulated input values explicitly using <code>session$setInputs()</code>.</li>
<li><strong>Forgetting flushReact() with external reactive updates:</strong> If your test updates an external <code>reactiveVal</code> or reactive source outside <code>session$setInputs()</code>, call <code>session$flushReact()</code> to trigger pending observers.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/shiny-testserver/scripts/module-demo.R">View <code>module-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/shiny-testserver/scripts/module-demo.R" download="module-demo.R">Download</a></p>
<p>Defines a pure clinical filtering helper, a Shiny module (UI and server), and a verification runner exercising server logic against <code>pharmaverseadam::adsl</code> using <code>shiny::testServer()</code>. Requires <code>{shiny}</code> and <code>{pharmaverseadam}</code>. The script’s functions have tests that check the counts against the data and catch a planted bug.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>module-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="co" style="color: #5E5E5E;"># Testing Shiny server logic with testServer(): defines a pure helper function</span></span>
<span id="cb10-2"><span class="co" style="color: #5E5E5E;"># for safety population filtering and arm counts on ADSL, a Shiny module</span></span>
<span id="cb10-3"><span class="co" style="color: #5E5E5E;"># (UI + server) for interactive filtering, and an automated verification runner</span></span>
<span id="cb10-4"><span class="co" style="color: #5E5E5E;"># using shiny::testServer().</span></span>
<span id="cb10-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb10-6"><span class="co" style="color: #5E5E5E;">#   Rscript module-demo.R</span></span>
<span id="cb10-7"></span>
<span id="cb10-8"><span class="co" style="color: #5E5E5E;">#' Filter safety population and summarize treatment arm counts</span></span>
<span id="cb10-9"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-10"><span class="co" style="color: #5E5E5E;">#' Filters an ADSL data frame to the safety population (SAFFL == "Y") and</span></span>
<span id="cb10-11"><span class="co" style="color: #5E5E5E;">#' optionally to a specific treatment arm (TRT01A), computing participant counts.</span></span>
<span id="cb10-12"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-13"><span class="co" style="color: #5E5E5E;">#' @param data An ADSL data frame containing `SAFFL` and `TRT01A`.</span></span>
<span id="cb10-14"><span class="co" style="color: #5E5E5E;">#' @param arm Treatment arm name to filter by, or "All" for all arms.</span></span>
<span id="cb10-15"><span class="co" style="color: #5E5E5E;">#' @return A list with `data` (filtered data frame), `n_arm` (subject count in</span></span>
<span id="cb10-16"><span class="co" style="color: #5E5E5E;">#'   selected arm), `n_total` (total subjects in safety population), and</span></span>
<span id="cb10-17"><span class="co" style="color: #5E5E5E;">#'   `arm` (the selected arm).</span></span>
<span id="cb10-18"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-19">summarize_safety_arm <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(data, <span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"All"</span>) {</span>
<span id="cb10-20">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.data.frame</span>(data)) {</span>
<span id="cb10-21">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`data` must be a data frame."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb10-22">  }</span>
<span id="cb10-23">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">all</span>(<span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"SAFFL"</span>, <span class="st" style="color: #20794D;">"TRT01A"</span>) <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">names</span>(data))) {</span>
<span id="cb10-24">    <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"`data` must contain `SAFFL` and `TRT01A` columns."</span>, <span class="at" style="color: #657422;">call. =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb10-25">  }</span>
<span id="cb10-26"></span>
<span id="cb10-27">  saffl_data <span class="ot" style="color: #003B4F;">&lt;-</span> data[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(data<span class="sc" style="color: #5E5E5E;">$</span>SAFFL) <span class="sc" style="color: #5E5E5E;">&amp;</span> data<span class="sc" style="color: #5E5E5E;">$</span>SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>, , drop <span class="ot" style="color: #003B4F;">=</span> <span class="cn" style="color: #8f5902;">FALSE</span>]</span>
<span id="cb10-28">  n_total <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">nrow</span>(saffl_data)</span>
<span id="cb10-29"></span>
<span id="cb10-30">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">identical</span>(arm, <span class="st" style="color: #20794D;">"All"</span>)) {</span>
<span id="cb10-31">    filtered <span class="ot" style="color: #003B4F;">&lt;-</span> saffl_data</span>
<span id="cb10-32">  } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb10-33">    filtered <span class="ot" style="color: #003B4F;">&lt;-</span> saffl_data[</span>
<span id="cb10-34">      <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(saffl_data<span class="sc" style="color: #5E5E5E;">$</span>TRT01A) <span class="sc" style="color: #5E5E5E;">&amp;</span> saffl_data<span class="sc" style="color: #5E5E5E;">$</span>TRT01A <span class="sc" style="color: #5E5E5E;">==</span> arm,</span>
<span id="cb10-35">      ,</span>
<span id="cb10-36">      drop <span class="ot" style="color: #003B4F;">=</span> <span class="cn" style="color: #8f5902;">FALSE</span></span>
<span id="cb10-37">    ]</span>
<span id="cb10-38">  }</span>
<span id="cb10-39"></span>
<span id="cb10-40">  <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb10-41">    <span class="at" style="color: #657422;">data =</span> filtered,</span>
<span id="cb10-42">    <span class="at" style="color: #657422;">n_arm =</span> <span class="fu" style="color: #4758AB;">nrow</span>(filtered),</span>
<span id="cb10-43">    <span class="at" style="color: #657422;">n_total =</span> n_total,</span>
<span id="cb10-44">    <span class="at" style="color: #657422;">arm =</span> arm</span>
<span id="cb10-45">  )</span>
<span id="cb10-46">}</span>
<span id="cb10-47"></span>
<span id="cb10-48"><span class="co" style="color: #5E5E5E;">#' UI for treatment arm filter module</span></span>
<span id="cb10-49"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-50"><span class="co" style="color: #5E5E5E;">#' @param id Module namespace id.</span></span>
<span id="cb10-51"><span class="co" style="color: #5E5E5E;">#' @param arms Character vector of available treatment arms.</span></span>
<span id="cb10-52"><span class="co" style="color: #5E5E5E;">#' @return A shiny tagList containing input controls and text output.</span></span>
<span id="cb10-53"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-54">arm_filter_ui <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb10-55">  id,</span>
<span id="cb10-56">  <span class="at" style="color: #657422;">arms =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"All"</span>, <span class="st" style="color: #20794D;">"Placebo"</span>, <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>, <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)</span>
<span id="cb10-57">) {</span>
<span id="cb10-58">  ns <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">NS</span>(id)</span>
<span id="cb10-59">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">tagList</span>(</span>
<span id="cb10-60">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">selectInput</span>(</span>
<span id="cb10-61">      <span class="at" style="color: #657422;">inputId =</span> <span class="fu" style="color: #4758AB;">ns</span>(<span class="st" style="color: #20794D;">"arm"</span>),</span>
<span id="cb10-62">      <span class="at" style="color: #657422;">label =</span> <span class="st" style="color: #20794D;">"Treatment Arm:"</span>,</span>
<span id="cb10-63">      <span class="at" style="color: #657422;">choices =</span> arms,</span>
<span id="cb10-64">      <span class="at" style="color: #657422;">selected =</span> <span class="st" style="color: #20794D;">"All"</span></span>
<span id="cb10-65">    ),</span>
<span id="cb10-66">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">textOutput</span>(<span class="at" style="color: #657422;">outputId =</span> <span class="fu" style="color: #4758AB;">ns</span>(<span class="st" style="color: #20794D;">"summary_text"</span>))</span>
<span id="cb10-67">  )</span>
<span id="cb10-68">}</span>
<span id="cb10-69"></span>
<span id="cb10-70"><span class="co" style="color: #5E5E5E;">#' Server logic for treatment arm filter module</span></span>
<span id="cb10-71"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-72"><span class="co" style="color: #5E5E5E;">#' @param id Module namespace id.</span></span>
<span id="cb10-73"><span class="co" style="color: #5E5E5E;">#' @param data ADSL data frame or a reactive expression returning one.</span></span>
<span id="cb10-74"><span class="co" style="color: #5E5E5E;">#' @return A reactive expression returning the summary list from</span></span>
<span id="cb10-75"><span class="co" style="color: #5E5E5E;">#'   `summarize_safety_arm()`.</span></span>
<span id="cb10-76"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-77">arm_filter_server <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(id, <span class="at" style="color: #657422;">data =</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl) {</span>
<span id="cb10-78">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">moduleServer</span>(id, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(input, output, session) {</span>
<span id="cb10-79">    resolved_data <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>({</span>
<span id="cb10-80">      <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">is.reactive</span>(data)) {</span>
<span id="cb10-81">        <span class="fu" style="color: #4758AB;">data</span>()</span>
<span id="cb10-82">      } <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> {</span>
<span id="cb10-83">        data</span>
<span id="cb10-84">      }</span>
<span id="cb10-85">    })</span>
<span id="cb10-86"></span>
<span id="cb10-87">    summary_res <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>({</span>
<span id="cb10-88">      selected_arm <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(input<span class="sc" style="color: #5E5E5E;">$</span>arm)) <span class="st" style="color: #20794D;">"All"</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">else</span> input<span class="sc" style="color: #5E5E5E;">$</span>arm</span>
<span id="cb10-89">      <span class="fu" style="color: #4758AB;">summarize_safety_arm</span>(<span class="fu" style="color: #4758AB;">resolved_data</span>(), <span class="at" style="color: #657422;">arm =</span> selected_arm)</span>
<span id="cb10-90">    })</span>
<span id="cb10-91"></span>
<span id="cb10-92">    output<span class="sc" style="color: #5E5E5E;">$</span>summary_text <span class="ot" style="color: #003B4F;">&lt;-</span> shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">renderText</span>({</span>
<span id="cb10-93">      res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">summary_res</span>()</span>
<span id="cb10-94">      <span class="fu" style="color: #4758AB;">sprintf</span>(</span>
<span id="cb10-95">        <span class="st" style="color: #20794D;">"%s: %d of %d subjects (safety population)"</span>,</span>
<span id="cb10-96">        res<span class="sc" style="color: #5E5E5E;">$</span>arm,</span>
<span id="cb10-97">        res<span class="sc" style="color: #5E5E5E;">$</span>n_arm,</span>
<span id="cb10-98">        res<span class="sc" style="color: #5E5E5E;">$</span>n_total</span>
<span id="cb10-99">      )</span>
<span id="cb10-100">    })</span>
<span id="cb10-101"></span>
<span id="cb10-102">    shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">reactive</span>(<span class="fu" style="color: #4758AB;">summary_res</span>())</span>
<span id="cb10-103">  })</span>
<span id="cb10-104">}</span>
<span id="cb10-105"></span>
<span id="cb10-106"><span class="co" style="color: #5E5E5E;">#' Run headless reactive checks on arm_filter_server using testServer</span></span>
<span id="cb10-107"><span class="co" style="color: #5E5E5E;">#'</span></span>
<span id="cb10-108"><span class="co" style="color: #5E5E5E;">#' @param data ADSL dataset to test against.</span></span>
<span id="cb10-109"><span class="co" style="color: #5E5E5E;">#' @return A list containing verified summary counts and status.</span></span>
<span id="cb10-110"><span class="co" style="color: #5E5E5E;">#' @export</span></span>
<span id="cb10-111">run_module_checks <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">data =</span> pharmaverseadam<span class="sc" style="color: #5E5E5E;">::</span>adsl) {</span>
<span id="cb10-112">  saffl_sub <span class="ot" style="color: #003B4F;">&lt;-</span> data[<span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(data<span class="sc" style="color: #5E5E5E;">$</span>SAFFL) <span class="sc" style="color: #5E5E5E;">&amp;</span> data<span class="sc" style="color: #5E5E5E;">$</span>SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>, , drop <span class="ot" style="color: #003B4F;">=</span> <span class="cn" style="color: #8f5902;">FALSE</span>]</span>
<span id="cb10-113">  exp_total <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">nrow</span>(saffl_sub)</span>
<span id="cb10-114">  exp_pbo <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sum</span>(saffl_sub<span class="sc" style="color: #5E5E5E;">$</span>TRT01A <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Placebo"</span>, <span class="at" style="color: #657422;">na.rm =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb10-115">  exp_low <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sum</span>(saffl_sub<span class="sc" style="color: #5E5E5E;">$</span>TRT01A <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>, <span class="at" style="color: #657422;">na.rm =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb10-116">  exp_high <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">sum</span>(saffl_sub<span class="sc" style="color: #5E5E5E;">$</span>TRT01A <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>, <span class="at" style="color: #657422;">na.rm =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb10-117"></span>
<span id="cb10-118">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>()</span>
<span id="cb10-119">  shiny<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">testServer</span>(arm_filter_server, <span class="at" style="color: #657422;">args =</span> <span class="fu" style="color: #4758AB;">list</span>(<span class="at" style="color: #657422;">data =</span> data), {</span>
<span id="cb10-120">    session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"All"</span>)</span>
<span id="cb10-121">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, exp_total))</span>
<span id="cb10-122">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_total, exp_total))</span>
<span id="cb10-123">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">returned</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, exp_total))</span>
<span id="cb10-124">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">returned</span>(), session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">getReturned</span>()()))</span>
<span id="cb10-125"></span>
<span id="cb10-126">    session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Placebo"</span>)</span>
<span id="cb10-127">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, exp_pbo))</span>
<span id="cb10-128">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">returned</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, exp_pbo))</span>
<span id="cb10-129">    pbo_text_out <span class="ot" style="color: #003B4F;">&lt;-</span> output<span class="sc" style="color: #5E5E5E;">$</span>summary_text</span>
<span id="cb10-130"></span>
<span id="cb10-131">    session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Xanomeline Low Dose"</span>)</span>
<span id="cb10-132">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, exp_low))</span>
<span id="cb10-133"></span>
<span id="cb10-134">    session<span class="sc" style="color: #5E5E5E;">$</span><span class="fu" style="color: #4758AB;">setInputs</span>(<span class="at" style="color: #657422;">arm =</span> <span class="st" style="color: #20794D;">"Xanomeline High Dose"</span>)</span>
<span id="cb10-135">    <span class="fu" style="color: #4758AB;">stopifnot</span>(<span class="fu" style="color: #4758AB;">identical</span>(<span class="fu" style="color: #4758AB;">summary_res</span>()<span class="sc" style="color: #5E5E5E;">$</span>n_arm, exp_high))</span>
<span id="cb10-136"></span>
<span id="cb10-137">    results <span class="ot" style="color: #003B4F;">&lt;&lt;-</span> <span class="fu" style="color: #4758AB;">list</span>(</span>
<span id="cb10-138">      <span class="at" style="color: #657422;">n_total =</span> exp_total,</span>
<span id="cb10-139">      <span class="at" style="color: #657422;">pbo_count =</span> exp_pbo,</span>
<span id="cb10-140">      <span class="at" style="color: #657422;">low_count =</span> exp_low,</span>
<span id="cb10-141">      <span class="at" style="color: #657422;">high_count =</span> exp_high,</span>
<span id="cb10-142">      <span class="at" style="color: #657422;">pbo_text =</span> pbo_text_out,</span>
<span id="cb10-143">      <span class="at" style="color: #657422;">passed =</span> <span class="cn" style="color: #8f5902;">TRUE</span></span>
<span id="cb10-144">    )</span>
<span id="cb10-145">  })</span>
<span id="cb10-146">  results</span>
<span id="cb10-147">}</span>
<span id="cb10-148"></span>
<span id="cb10-149"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by tests).</span></span>
<span id="cb10-150"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb10-151">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"Running testServer verification on arm_filter_server...</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb10-152">  res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_module_checks</span>()</span>
<span id="cb10-153">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Total safety population: %d</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, res<span class="sc" style="color: #5E5E5E;">$</span>n_total))</span>
<span id="cb10-154">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Placebo count:           %d</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, res<span class="sc" style="color: #5E5E5E;">$</span>pbo_count))</span>
<span id="cb10-155">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Xanomeline Low Dose:     %d</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, res<span class="sc" style="color: #5E5E5E;">$</span>low_count))</span>
<span id="cb10-156">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Xanomeline High Dose:    %d</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, res<span class="sc" style="color: #5E5E5E;">$</span>high_count))</span>
<span id="cb10-157">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"Placebo output text:     %s</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>, res<span class="sc" style="color: #5E5E5E;">$</span>pbo_text))</span>
<span id="cb10-158">  <span class="fu" style="color: #4758AB;">cat</span>(<span class="st" style="color: #20794D;">"All reactive tests passed via testServer().</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">"</span>)</span>
<span id="cb10-159">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>shiny</strong> (<code>testServer()</code>, <code>moduleServer()</code>): <a href="https://cran.r-project.org/package=shiny">CRAN</a></li>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
</ul>
<p><strong>Web-repo comparison</strong></p>
<ul>
<li><strong>Playwright</strong>: <a href="https://playwright.dev/">playwright.dev</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
<li><strong>2026-09-27:</strong> Noted that shared functions match the companion script under automated tests.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-series-nav__series">Testing series · part 4 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 3</span><span class="site-related-card__title">Snapshot tests for R output, tables and plots</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/shinytest2-end-to-end/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 5</span><span class="site-related-card__title">End-to-end Shiny tests with shinytest2</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/index.html" class="site-link-row" title="Isolate test state with withr, manage fixtures cleanly in testthat 3e, and mock boundary functions to build repeatable verification suites."><span class="is-card__eyebrow site-link-row__label">Builds on</span><span class="site-link-row__title">Test design: fixtures, temporary state and mocking</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/from-scripts-to-a-package/index.html" class="site-link-row" title="Move reusable analysis helpers from sourced scripts into a minimal R package, and replace workspace pollution with the devtools::load_all() loop."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">From scripts to a package</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="site-link-row" title="Use the R package development loop, read R CMD check diagnostics, and fix four recurring problems."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">The package development loop and R CMD check</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Shiny</category>
  <category>R</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/shiny-testserver/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>The CDISC Analysis Results Standard and {siera}</title>
  <link>https://insightsurge-dev.web.app/posts/cdisc-ars-siera/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>In traditional clinical trial reporting, the blueprint for study deliverables is fragmented across disconnected documents. A Statistical Analysis Plan (SAP) specifies endpoints and populations in narrative prose. Table shells mock up visual displays in word-processor or spreadsheet documents. Statistical programmers then translate those descriptions into procedural macros or bespoke R scripts.</p>
<p>This manual translation creates three recurring engineering bottlenecks:</p>
<ul>
<li><strong>Analysis definitions are scattered</strong>: To verify why a specific adverse-event table applied a certain treatment-emergent definition or population filter, a programmer must search through narrative paragraphs in the SAP, check footnotes in the table shell, and inspect extensive procedural code.</li>
<li><strong>Results are trapped in presentation documents</strong>: As noted in our posts on <a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/index.html">the clinical reporting pipeline</a> and <a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html">generating TFLs</a>, clinical outputs are traditionally rendered directly to static Rich Text Format (RTF) or PDF files. Because numbers are embedded in display formatting, downstream systems—such as executive summaries, clinical dashboards, or meta-analyses—cannot programmatically ingest or verify results without scraping text.</li>
<li><strong>Cross-table reconciliation is error-prone</strong>: Table 14.1.1 (demographics) and Table 14.3.1 (safety) often independently re-derive denominator counts. Small divergences in filtering rules or rounding logic create discrepancies that require manual investigation.</li>
</ul>
<p><a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html">Analysis Results Data with {cards}</a> addresses the output side of this equation by storing computed statistics in a tidy, one-row-per-statistic tabular structure. But someone still has to write the bespoke R script that invokes each calculation. What clinical engineering requires is an open, machine-readable standard for the analysis plan itself.</p>
</section>
<section id="the-web-analogue-contract-first-code-generation" class="level2">
<h2 class="anchored" data-anchor-id="the-web-analogue-contract-first-code-generation">The web analogue: contract-first code generation</h2>
<p>In distributed systems and web API development, interface definitions once suffered from the same documentation drift. Teams wrote API specifications in wikis or PDF documents, while backend and frontend developers manually implemented route handlers, parameter validation, and client HTTP requests. When an endpoint or parameter changed, implementations silently diverged.</p>
<p>Web engineering resolved this by adopting <strong>contract-first specifications</strong>, epitomised by OpenAPI (formerly Swagger) and Protocol Buffers:</p>
<pre class="text"><code>API Contract (OpenAPI JSON/YAML)
   │
   ├──&gt; Code Generator ──&gt; Typed Client SDKs (TypeScript / Go / Python)
   ├──&gt; Code Generator ──&gt; Server Route Stubs &amp; Input Validators
   └──&gt; Test Harness   ──&gt; Automated Contract &amp; Schema Tests</code></pre>
<p>In a contract-first architecture:</p>
<ol type="1">
<li><strong>The specification is the single source of truth</strong>: Endpoints, data types, query parameters, and response schemas are declared in a structured, machine-readable format.</li>
<li><strong>Boilerplate code is generated, not hand-coded</strong>: Tooling ingests the schema to generate typed client SDKs and server stubs. Programmers do not write repetitive data fetching or schema validation code by hand.</li>
<li><strong>Automated verification guards against divergence</strong>: Contract-testing tools verify that API responses conform to the specification on every build.</li>
</ol>
<p>Applying this pattern to clinical reporting means treating analysis plans as machine-readable contracts. Instead of hand-coding every table script from prose requirements, teams define analyses in a structured standard and generate auditable execution code.</p>
</section>
<section id="the-r-way-cdisc-ars-and-siera" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-cdisc-ars-and-siera">The R way: CDISC ARS and {siera}</h2>
<p>The Clinical Data Interchange Standards Consortium (CDISC) established the <a href="https://www.cdisc.org/standards/foundational/analysis-results-standard">Analysis Results Standard (ARS)</a>; v1.0 was published on 19 April 2024. The ARS establishes a technology-independent logical data model for describing planned analyses, their input data sources, populations, calculation methods, and results.</p>
<section id="the-cdisc-ars-logical-data-model" class="level3">
<h3 class="anchored" data-anchor-id="the-cdisc-ars-logical-data-model">The CDISC ARS logical data model</h3>
<p>At the top level of the ARS model is the <code>ReportingEvent</code>, which encapsulates all analyses and displays planned for a clinical milestone (such as a Clinical Study Report or interim analysis). Within a reporting event, the <a href="https://cdisc-org.github.io/analysis-results-standard/">model</a> organizes analysis metadata into distinct, linked entities:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Model Entity</th>
<th>Purpose in the ARS Model</th>
<th>Clinical Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>Output</code></td>
<td>Defines a display item (table, listing, or figure)</td>
<td>Table 14-1.1: Demographics and Baseline Characteristics</td>
</tr>
<tr class="even">
<td><code>Analysis</code></td>
<td>The core unit linking data, population, and method</td>
<td>Summary of Age in the Safety Population by Treatment Arm</td>
</tr>
<tr class="odd">
<td><code>AnalysisSet</code></td>
<td>Defines population inclusion criteria via logical conditions</td>
<td>Safety Population (<code>SAFFL == "Y"</code>)</td>
</tr>
<tr class="even">
<td><code>DataSubset</code></td>
<td>Defines analysis-specific record filtering rules</td>
<td>Treatment-emergent events (<code>TRTEMFL == "Y"</code>)</td>
</tr>
<tr class="odd">
<td><code>GroupingFactor</code></td>
<td>Defines stratification factors (data-driven or categorized)</td>
<td>Actual Treatment Arm (<code>TRT01A</code>), Age Groups (<code>AGEGR1</code>)</td>
</tr>
<tr class="even">
<td><code>AnalysisMethod</code></td>
<td>Describes the statistical algorithm and required operations</td>
<td>Summary statistics for continuous variables (<code>n</code>, <code>mean</code>, <code>sd</code>)</td>
</tr>
</tbody>
</table>
</div>
<p>An <code>AnalysisMethod</code> in the ARS model can define an <code>Operation</code> (one of the method’s computational steps; the generated ARD’s <code>operationid</code> points back to it) and an operational code template: <code>AnalysisProgrammingCodeTemplate</code> with its <code>TemplateCodeParameter</code>s. These templates supply parameterized expressions that an execution engine populates with metadata variables (such as substituting <code>TRT01A</code> for grouping and <code>AGE</code> for the analysis variable).</p>
</section>
<section id="how-ars-relates-to-ard-and-cards" class="level3">
<h3 class="anchored" data-anchor-id="how-ars-relates-to-ard-and-cards">How ARS relates to ARD and {cards}</h3>
<p>The relationship between the CDISC Analysis Results Standard and Analysis Results Data (ARD) is a separation of metadata from tabular results:</p>
<ul>
<li><strong>ARS is the specification contract</strong>: It defines <em>what</em> analyses exist, <em>which</em> populations and subsets apply, and <em>how</em> calculations are performed. It is vendor-neutral and technology-independent: the <a href="https://cdisc-org.github.io/analysis-results-standard/">model</a> itself names no storage format; tools exchange it as JSON (the format {siera} reads), and {siera} also reads the ARS Excel template.</li>
<li><strong>ARD is the tabular result</strong>: It represents the calculated numerical outputs: one row per statistic, containing values, parameter names, and condition flags.</li>
<li><strong><code>{cards}</code> is the R engine</strong>: It provides an R-native S3 data structure (<code>"card"</code>) for calculating and storing ARD, with composable functions like <code>cards::ard_continuous()</code>, <code>cards::ard_categorical()</code>, and <code>cards::ard_stack()</code>.</li>
</ul>
<p>The ARS specification defines the analysis plan. An execution engine consumes that plan, executes <code>{cards}</code> calls against ADaM data, and produces an ARD.</p>
</section>
</section>
<section id="ingesting-ars-and-generating-code-with-siera" class="level2">
<h2 class="anchored" data-anchor-id="ingesting-ars-and-generating-code-with-siera">Ingesting ARS and generating code with {siera}</h2>
<p>The <a href="https://cran.r-project.org/package=siera"><code>{siera}</code></a> package (available on CRAN) bridges the CDISC ARS standard and R execution. It ingests ARS metadata—formatted in JSON or Excel—and generates executable R scripts that produce <code>{cards}</code>-compatible ARD datasets.</p>
<p>The core function in <code>{siera}</code> is <code>siera::readARS()</code>. The demo uses the package’s bundled example data: <code>ARS_example("exampleARS_1.json")</code> against the bundled <code>ADSL.csv</code> (84/84/86 subjects across the three <code>TRT01AN</code> arms in <code>An_01</code>), not <code>pharmaverseadam::adsl</code> used in earlier posts.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">library</span>(siera)</span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="co" style="color: #5E5E5E;"># Ingest bundled CDISC ARS JSON metadata</span></span>
<span id="cb2-4">ars_file <span class="ot" style="color: #003B4F;">&lt;-</span> siera<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ARS_example</span>(<span class="st" style="color: #20794D;">"exampleARS_1.json"</span>)</span>
<span id="cb2-5">out_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tempfile</span>(<span class="st" style="color: #20794D;">"siera_demo_"</span>)</span>
<span id="cb2-6"><span class="fu" style="color: #4758AB;">dir.create</span>(out_dir)</span>
<span id="cb2-7"></span>
<span id="cb2-8"><span class="co" style="color: #5E5E5E;"># Copy example ADaM dataset to the input folder</span></span>
<span id="cb2-9"><span class="fu" style="color: #4758AB;">file.copy</span>(siera<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ARS_example</span>(<span class="st" style="color: #20794D;">"ADSL.csv"</span>), <span class="fu" style="color: #4758AB;">file.path</span>(out_dir, <span class="st" style="color: #20794D;">"ADSL.csv"</span>))</span>
<span id="cb2-10"></span>
<span id="cb2-11"><span class="co" style="color: #5E5E5E;"># Generate R scripts from the ARS specification.</span></span>
<span id="cb2-12"><span class="co" style="color: #5E5E5E;"># readARS() writes the scripts to output_path and returns NULL, so its</span></span>
<span id="cb2-13"><span class="co" style="color: #5E5E5E;"># return value is not what you inspect - list the generated files instead.</span></span>
<span id="cb2-14">siera<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">readARS</span>(</span>
<span id="cb2-15">  <span class="at" style="color: #657422;">ARS_path =</span> ars_file,</span>
<span id="cb2-16">  <span class="at" style="color: #657422;">output_path =</span> out_dir,</span>
<span id="cb2-17">  <span class="at" style="color: #657422;">adam_path =</span> out_dir</span>
<span id="cb2-18">)</span>
<span id="cb2-19"></span>
<span id="cb2-20"><span class="fu" style="color: #4758AB;">basename</span>(<span class="fu" style="color: #4758AB;">list.files</span>(out_dir, <span class="at" style="color: #657422;">pattern =</span> <span class="st" style="color: #20794D;">"[.]R$"</span>))</span></code></pre></div></div>
<p><code>siera::readARS()</code> accepts:</p>
<ul>
<li><code>ARS_path</code>: Path to an ARS metadata file in JSON or Excel format.</li>
<li><code>output_path</code>: Directory where generated <code>.R</code> script files will be written (defaults to <code>tempdir()</code>).</li>
<li><code>adam_path</code>: Directory where input ADaM datasets reside.</li>
<li><code>spec_output</code>: An optional output ID to generate code for a single display rather than all displays in the file.</li>
</ul>
<p><code>{siera}</code> also provides helper utilities: <code>siera::ARS_example()</code> lists or retrieves bundled ARS metadata files, and <code>siera::ARD_script_example()</code> accesses reference generated scripts.</p>
<section id="verifying-and-running-generated-scripts" class="level3">
<h3 class="anchored" data-anchor-id="verifying-and-running-generated-scripts">Verifying and running generated scripts</h3>
<p>Because <code>{siera}</code> emits standard R scripts, you can inspect and parse them using base R before execution:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="co" style="color: #5E5E5E;"># Verify that generated scripts parse without syntax errors</span></span>
<span id="cb3-2">script_path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">file.path</span>(out_dir, <span class="st" style="color: #20794D;">"ARD_Out_01.R"</span>)</span>
<span id="cb3-3">parsed_code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">parse</span>(<span class="at" style="color: #657422;">file =</span> script_path)</span>
<span id="cb3-4"><span class="fu" style="color: #4758AB;">length</span>(parsed_code)</span></code></pre></div></div>
<p>To run the generated script, execute it in an isolated environment pointing to your verified ADaM datasets. The generated code calls <code>library()</code> on its own dependencies (<code>dplyr</code>, <code>readxl</code>, <code>readr</code>, <code>cards</code>, <code>cardx</code>, <code>broom</code>, <code>parameters</code>, <code>tidyr</code>), so the project must have them installed — this site’s renv does:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># Execute the generated script in an isolated environment</span></span>
<span id="cb4-2">env <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">new.env</span>(<span class="at" style="color: #657422;">parent =</span> <span class="fu" style="color: #4758AB;">globalenv</span>())</span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;">sys.source</span>(script_path, <span class="at" style="color: #657422;">envir =</span> env)</span>
<span id="cb4-4"></span>
<span id="cb4-5">ard <span class="ot" style="color: #003B4F;">&lt;-</span> env<span class="sc" style="color: #5E5E5E;">$</span>ARD</span>
<span id="cb4-6"><span class="fu" style="color: #4758AB;">dim</span>(ard)</span></code></pre></div></div>
<p>The resulting <code>ard</code> object is a complete Analysis Results Dataset:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;"># Inspect the ARD: both cards statistical values and ARS metadata keys</span></span>
<span id="cb5-2">ard_sample <span class="ot" style="color: #003B4F;">&lt;-</span> ard[</span>
<span id="cb5-3">  ard<span class="sc" style="color: #5E5E5E;">$</span>AnalysisId <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"An_01"</span>,</span>
<span id="cb5-4">  <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"variable"</span>, <span class="st" style="color: #20794D;">"stat_name"</span>, <span class="st" style="color: #20794D;">"stat"</span>, <span class="st" style="color: #20794D;">"AnalysisId"</span>, <span class="st" style="color: #20794D;">"MethodId"</span>, <span class="st" style="color: #20794D;">"OutputId"</span>)</span>
<span id="cb5-5">]</span>
<span id="cb5-6">ard_sample</span></code></pre></div></div>
<p>Crucially, <code>{siera}</code> does not merely generate standard <code>{cards}</code> calls; it stamps CDISC ARS metadata columns directly onto each row:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="co" style="color: #5E5E5E;"># The generated ARD links directly to the CDISC ARS metadata IDs</span></span>
<span id="cb6-2"><span class="fu" style="color: #4758AB;">unique</span>(ard<span class="sc" style="color: #5E5E5E;">$</span>AnalysisId)</span></code></pre></div></div>
<p>Each row records its <code>AnalysisId</code>, <code>MethodId</code>, <code>OutputId</code>, and <code>operationid</code>, establishing complete traceability from result to specification.</p>
</section>
</section>
<section id="anatomy-of-a-generated-script" class="level2">
<h2 class="anchored" data-anchor-id="anatomy-of-a-generated-script">Anatomy of a generated script</h2>
<p>Understanding how <code>{siera}</code> structures generated code is essential for code review. <code>ARD_Out_01.R</code> follows a consistent layout, visible in its own comments:</p>
<pre class="text"><code># Programme:    Generate code to produce ARD for Out_01
# Output:       Subject Disposition
# Date created: &lt;timestamp&gt;

# load libraries ----
    library(dplyr)
    ...

# Load ADaM -------
ADSL &lt;- readr::read_csv(...)

# Analysis An_01----
# Apply Analysis Set ---
# Apply Data Subset ---
# Apply Method ---
# Method ID:              Mth_01
# Method name:            Count by group for a categorical variable
# Method description:     Count across groups for a categorical variable, ...
   ... (repeated per analysis in the output: An_01, An_02, ...)

# combine analyses to create ARD ----
ARD &lt;- dplyr::bind_rows(df3_An_01, df3_An_02, ...)</code></pre>
<section id="reviewing-generated-code-in-production" class="level3">
<h3 class="anchored" data-anchor-id="reviewing-generated-code-in-production">Reviewing generated code in production</h3>
<p>When incorporating generated reporting scripts into a clinical repository, teams should adopt specific engineering review practices:</p>
<ol type="1">
<li><strong>The metadata is the source of truth</strong>: Treat generated <code>.R</code> files like compiled build artifacts. If an analysis filter or grouping is incorrect, update the ARS metadata file and re-run <code>siera::readARS()</code>. Never manually patch generated scripts in place; manual edits decouple code from metadata and invalidate traceability.</li>
<li><strong>Automate syntax verification in CI</strong>: In CI pipelines, run <code>parse(file = script)</code> across all generated files. This confirms that all parameterized metadata substitutions yielded valid R expressions before executing long-running calculations.</li>
<li><strong>Double-programming as data comparison</strong>: Rather than having a second programmer independently write duplicate table formatting code, have the validation programmer independently derive the ARD. Compare the primary and validation ARDs as data frames using <code>waldo::compare()</code>, as demonstrated in our <a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html">ARD post</a>.</li>
</ol>
</section>
</section>
<section id="traceability-and-gxp-qualification" class="level2">
<h2 class="anchored" data-anchor-id="traceability-and-gxp-qualification">Traceability and GxP qualification</h2>
<p>In regulated clinical environments, open-source R packages are never qualified off the shelf. Package qualification is a formal, risk-based process conducted by a sponsor or team to demonstrate that software reliably fulfills its intended use in a controlled environment.</p>
<p>What CDISC ARS and <code>{siera}</code> provide is structural <strong>traceability</strong>:</p>
<ul>
<li><strong>From Result to Method</strong>: Every calculated statistic in the ARD contains <code>MethodId</code> and <code>operationid</code>, identifying the mathematical algorithm and operational step that produced it.</li>
<li><strong>From Method to Analysis</strong>: The <code>AnalysisId</code> links the result to the exact planned analysis in the ARS metadata, identifying the target variable, population criteria, and stratification factors.</li>
<li><strong>From Analysis to Output</strong>: The <code>OutputId</code> links the result to the planned display it belongs to. The model can also hold document references (<code>ReferenceDocument</code>, <code>DocumentReference</code>) for linking an output or analysis back to a SAP section or CSR table shell, though the bundled example JSON ships this list empty, so that link depends on what a sponsor’s own ARS file populates.</li>
</ul>
<p>Each result row carries IDs that lead back to its analysis and method in the metadata, so a reviewer can follow a number back to its definition.</p>
<p>The post script <a href="https://insightsurge-dev.web.app/posts/cdisc-ars-siera/scripts/ars-demo.R">scripts/ars-demo.R</a> ingests CDISC ARS JSON metadata, generates R scripts into a temporary directory, parses each file for syntax integrity, and executes a generated script on ADaM data to produce a metadata-stamped ARD.</p>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Manually editing generated scripts</strong>: Modifying generated <code>.R</code> scripts directly to resolve minor formatting issues destroys the link between metadata and execution code. All modifications must originate in the ARS specification.</li>
<li><strong>ADaM naming discrepancies</strong>: ARS metadata expects specific variable names (such as <code>TRT01AN</code> or <code>SAFFL</code>). If input ADaM datasets use non-standard column names or missing flags, generated scripts fail during column selection or filtering.</li>
<li><strong>Incomplete ARS metadata sections</strong>: Removing a required top-level section (<code>analysisSets</code>, in a copy of the bundled example) does not stop at a parsing error or a silent fallback to unfiltered data: <code>readARS()</code> emits a warning (“Input ARS file is missing required metadata sections: analysisSets”) and writes no <code>.R</code> scripts at all. Check for that warning, and check <code>output_path</code> for the expected script count, rather than assuming generation succeeded.</li>
<li><strong>Confusing code generation with statistical review</strong>: Generating code from metadata automates the mechanical construction of R syntax, but does not verify whether the statistical method chosen in the SAP is clinically appropriate. Scientific and statistical review remains essential.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/cdisc-ars-siera/scripts/ars-demo.R">View <code>ars-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/cdisc-ars-siera/scripts/ars-demo.R" download="ars-demo.R">Download</a></p>
<p>Ingests CDISC ARS JSON metadata, generates R analysis scripts into a temporary directory, parses each file for syntax integrity, and executes a generated script on ADaM data to produce a metadata-stamped ARD. Requires <code>{siera}</code>, plus the packages the generated code loads: <code>{dplyr}</code>, <code>{readxl}</code>, <code>{readr}</code>, <code>{cards}</code>, <code>{cardx}</code>, <code>{broom}</code>, <code>{parameters}</code> and <code>{tidyr}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>ars-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="co" style="color: #5E5E5E;"># Ingest CDISC Analysis Results Standard (ARS) metadata with {siera},</span></span>
<span id="cb8-2"><span class="co" style="color: #5E5E5E;"># generate R analysis programs, parse them for syntax correctness, and execute</span></span>
<span id="cb8-3"><span class="co" style="color: #5E5E5E;"># an auto-generated script to produce Analysis Results Data (ARD).</span></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb8-5"><span class="co" style="color: #5E5E5E;">#   Rscript ars-demo.R</span></span>
<span id="cb8-6"></span>
<span id="cb8-7"><span class="co" style="color: #5E5E5E;"># Ingest an ARS metadata file and generate R analysis scripts into output_dir.</span></span>
<span id="cb8-8">generate_ars_scripts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(</span>
<span id="cb8-9">  <span class="at" style="color: #657422;">ars_file =</span> <span class="cn" style="color: #8f5902;">NULL</span>,</span>
<span id="cb8-10">  <span class="at" style="color: #657422;">output_dir =</span> <span class="fu" style="color: #4758AB;">tempdir</span>(),</span>
<span id="cb8-11">  <span class="at" style="color: #657422;">adam_dir =</span> <span class="fu" style="color: #4758AB;">tempdir</span>(),</span>
<span id="cb8-12">  <span class="at" style="color: #657422;">spec_output =</span> <span class="st" style="color: #20794D;">""</span></span>
<span id="cb8-13">) {</span>
<span id="cb8-14">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">is.null</span>(ars_file)) {</span>
<span id="cb8-15">    ars_file <span class="ot" style="color: #003B4F;">&lt;-</span> siera<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ARS_example</span>(<span class="st" style="color: #20794D;">"exampleARS_1.json"</span>)</span>
<span id="cb8-16">  }</span>
<span id="cb8-17">  siera<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">readARS</span>(</span>
<span id="cb8-18">    <span class="at" style="color: #657422;">ARS_path =</span> ars_file,</span>
<span id="cb8-19">    <span class="at" style="color: #657422;">output_path =</span> output_dir,</span>
<span id="cb8-20">    <span class="at" style="color: #657422;">adam_path =</span> adam_dir,</span>
<span id="cb8-21">    <span class="at" style="color: #657422;">spec_output =</span> spec_output</span>
<span id="cb8-22">  )</span>
<span id="cb8-23">  <span class="fu" style="color: #4758AB;">list.files</span>(output_dir, <span class="at" style="color: #657422;">pattern =</span> <span class="st" style="color: #20794D;">"[.]R$"</span>, <span class="at" style="color: #657422;">full.names =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span>
<span id="cb8-24">}</span>
<span id="cb8-25"></span>
<span id="cb8-26"><span class="co" style="color: #5E5E5E;"># Parse a set of R script files to confirm each parses without syntax errors.</span></span>
<span id="cb8-27">parse_ars_scripts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(script_paths) {</span>
<span id="cb8-28">  parsed <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">lapply</span>(script_paths, <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path) {</span>
<span id="cb8-29">    <span class="fu" style="color: #4758AB;">parse</span>(<span class="at" style="color: #657422;">file =</span> path)</span>
<span id="cb8-30">  })</span>
<span id="cb8-31">  <span class="fu" style="color: #4758AB;">names</span>(parsed) <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">basename</span>(script_paths)</span>
<span id="cb8-32">  parsed</span>
<span id="cb8-33">}</span>
<span id="cb8-34"></span>
<span id="cb8-35"><span class="co" style="color: #5E5E5E;"># Execute a generated ARD script in an isolated environment. The generated</span></span>
<span id="cb8-36"><span class="co" style="color: #5E5E5E;"># code calls library() on its own dependencies (dplyr, readxl, readr, cards,</span></span>
<span id="cb8-37"><span class="co" style="color: #5E5E5E;"># cardx, broom, parameters, tidyr), so the project must have them installed.</span></span>
<span id="cb8-38">run_generated_ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(script_path) {</span>
<span id="cb8-39">  env <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">new.env</span>(<span class="at" style="color: #657422;">parent =</span> <span class="fu" style="color: #4758AB;">globalenv</span>())</span>
<span id="cb8-40">  <span class="fu" style="color: #4758AB;">sys.source</span>(script_path, <span class="at" style="color: #657422;">envir =</span> env)</span>
<span id="cb8-41">  env<span class="sc" style="color: #5E5E5E;">$</span>ARD</span>
<span id="cb8-42">}</span>
<span id="cb8-43"></span>
<span id="cb8-44"><span class="co" style="color: #5E5E5E;"># Verify that an ARD object contains core {cards} columns and CDISC ARS columns.</span></span>
<span id="cb8-45">verify_ard_columns <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(ard) {</span>
<span id="cb8-46">  cards_cols <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"variable"</span>, <span class="st" style="color: #20794D;">"context"</span>, <span class="st" style="color: #20794D;">"stat_name"</span>, <span class="st" style="color: #20794D;">"stat"</span>)</span>
<span id="cb8-47">  ars_cols <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"AnalysisId"</span>, <span class="st" style="color: #20794D;">"MethodId"</span>, <span class="st" style="color: #20794D;">"OutputId"</span>, <span class="st" style="color: #20794D;">"operationid"</span>)</span>
<span id="cb8-48">  <span class="fu" style="color: #4758AB;">all</span>(<span class="fu" style="color: #4758AB;">c</span>(cards_cols, ars_cols) <span class="sc" style="color: #5E5E5E;">%in%</span> <span class="fu" style="color: #4758AB;">names</span>(ard))</span>
<span id="cb8-49">}</span>
<span id="cb8-50"></span>
<span id="cb8-51"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by tests).</span></span>
<span id="cb8-52"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb8-53">  work_dir <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">tempfile</span>(<span class="st" style="color: #20794D;">"ars_demo_"</span>)</span>
<span id="cb8-54">  <span class="fu" style="color: #4758AB;">dir.create</span>(work_dir)</span>
<span id="cb8-55"></span>
<span id="cb8-56">  <span class="co" style="color: #5E5E5E;"># Copy bundled example ADaM dataset to the working folder</span></span>
<span id="cb8-57">  <span class="fu" style="color: #4758AB;">file.copy</span>(siera<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ARS_example</span>(<span class="st" style="color: #20794D;">"ADSL.csv"</span>), <span class="fu" style="color: #4758AB;">file.path</span>(work_dir, <span class="st" style="color: #20794D;">"ADSL.csv"</span>))</span>
<span id="cb8-58"></span>
<span id="cb8-59">  ars_path <span class="ot" style="color: #003B4F;">&lt;-</span> siera<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">ARS_example</span>(<span class="st" style="color: #20794D;">"exampleARS_1.json"</span>)</span>
<span id="cb8-60">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Ingesting ARS metadata: "</span>, <span class="fu" style="color: #4758AB;">basename</span>(ars_path))</span>
<span id="cb8-61"></span>
<span id="cb8-62">  scripts <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">generate_ars_scripts</span>(</span>
<span id="cb8-63">    <span class="at" style="color: #657422;">ars_file =</span> ars_path,</span>
<span id="cb8-64">    <span class="at" style="color: #657422;">output_dir =</span> work_dir,</span>
<span id="cb8-65">    <span class="at" style="color: #657422;">adam_dir =</span> work_dir</span>
<span id="cb8-66">  )</span>
<span id="cb8-67">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Generated "</span>, <span class="fu" style="color: #4758AB;">length</span>(scripts), <span class="st" style="color: #20794D;">" scripts:"</span>)</span>
<span id="cb8-68">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (s <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> scripts) {</span>
<span id="cb8-69">    <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"  - "</span>, <span class="fu" style="color: #4758AB;">basename</span>(s))</span>
<span id="cb8-70">  }</span>
<span id="cb8-71"></span>
<span id="cb8-72">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">Parsing generated scripts:"</span>)</span>
<span id="cb8-73">  parsed_exprs <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">parse_ars_scripts</span>(scripts)</span>
<span id="cb8-74">  <span class="cf" style="color: #003B4F;
font-weight: bold;">for</span> (name <span class="cf" style="color: #003B4F;
font-weight: bold;">in</span> <span class="fu" style="color: #4758AB;">names</span>(parsed_exprs)) {</span>
<span id="cb8-75">    <span class="fu" style="color: #4758AB;">message</span>(</span>
<span id="cb8-76">      <span class="st" style="color: #20794D;">"  - "</span>,</span>
<span id="cb8-77">      name,</span>
<span id="cb8-78">      <span class="st" style="color: #20794D;">": "</span>,</span>
<span id="cb8-79">      <span class="fu" style="color: #4758AB;">length</span>(parsed_exprs[[name]]),</span>
<span id="cb8-80">      <span class="st" style="color: #20794D;">" expressions parsed"</span></span>
<span id="cb8-81">    )</span>
<span id="cb8-82">  }</span>
<span id="cb8-83"></span>
<span id="cb8-84">  target_script <span class="ot" style="color: #003B4F;">&lt;-</span> scripts[<span class="dv" style="color: #AD0000;">1</span>]</span>
<span id="cb8-85">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"</span><span class="sc" style="color: #5E5E5E;">\n</span><span class="st" style="color: #20794D;">Executing "</span>, <span class="fu" style="color: #4758AB;">basename</span>(target_script), <span class="st" style="color: #20794D;">"..."</span>)</span>
<span id="cb8-86">  ard <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_generated_ard</span>(target_script)</span>
<span id="cb8-87"></span>
<span id="cb8-88">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"Execution complete. ARD dimensions: "</span>, <span class="fu" style="color: #4758AB;">nrow</span>(ard), <span class="st" style="color: #20794D;">" x "</span>, <span class="fu" style="color: #4758AB;">ncol</span>(ard))</span>
<span id="cb8-89">  <span class="fu" style="color: #4758AB;">message</span>(<span class="st" style="color: #20794D;">"CDISC ARS and {cards} columns present: "</span>, <span class="fu" style="color: #4758AB;">verify_ard_columns</span>(ard))</span>
<span id="cb8-90"></span>
<span id="cb8-91">  cols_to_show <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">intersect</span>(</span>
<span id="cb8-92">    <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb8-93">      <span class="st" style="color: #20794D;">"variable"</span>,</span>
<span id="cb8-94">      <span class="st" style="color: #20794D;">"variable_level"</span>,</span>
<span id="cb8-95">      <span class="st" style="color: #20794D;">"stat_name"</span>,</span>
<span id="cb8-96">      <span class="st" style="color: #20794D;">"stat"</span>,</span>
<span id="cb8-97">      <span class="st" style="color: #20794D;">"AnalysisId"</span>,</span>
<span id="cb8-98">      <span class="st" style="color: #20794D;">"OutputId"</span></span>
<span id="cb8-99">    ),</span>
<span id="cb8-100">    <span class="fu" style="color: #4758AB;">names</span>(ard)</span>
<span id="cb8-101">  )</span>
<span id="cb8-102">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">head</span>(ard[, cols_to_show]))</span>
<span id="cb8-103">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards</strong></p>
<ul>
<li><strong>CDISC Analysis Results Standard</strong> (v1.0, published 19 April 2024): <a href="https://www.cdisc.org/standards/foundational/analysis-results-standard">cdisc.org/standards/foundational/analysis-results-standard</a></li>
<li><strong>ARS model documentation</strong>: <a href="https://cdisc-org.github.io/analysis-results-standard/">cdisc-org.github.io/analysis-results-standard</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>siera</strong>: <a href="https://cran.r-project.org/package=siera">CRAN</a></li>
<li><strong>cards</strong>: <a href="https://pharmaverse.github.io/cards/">pharmaverse.github.io/cards</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
<li><strong>2026-09-27:</strong> Listed every package the companion script needs, including those its generated code loads.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-series-nav__series">Pharma series · part 4 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/analysis-results-data-cards/index.html" class="is-card site-related-card site-series-nav__prev"><span class="is-card__eyebrow">Previous · part 3</span><span class="site-related-card__title">Analysis Results Data in R with {cards} and {cardx}</span></a>
</div>
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/validation-ready-r-packages/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 5</span><span class="site-related-card__title">Validation-ready R packages</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html" class="site-link-row" title="How to engineer clinical TFLs in R across direct layout engines and ARD-first architectures, with RTF export, listings, and team conventions."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Generating tables, figures and listings in R</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/snapshot-tests/index.html" class="site-link-row" title="Capture complex console output, rtables layouts, and plots with testthat snapshots and vdiffr to catch regressions without fragile manual assertions."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Snapshot tests for R output, tables and plots</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dependencies-namespace/index.html" class="site-link-row" title="Declare external packages in DESCRIPTION Imports and Suggests, call functions through pkg::fun() or @importFrom, and guard optional dependencies cleanly."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Dependencies: DESCRIPTION and NAMESPACE</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Pharma</category>
  <category>R</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/cdisc-ars-siera/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>The clinical reporting pipeline in R</title>
  <link>https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Clinical reporting transforms raw participant data from clinical trials into regulatory deliverables for health authorities like the US FDA, EMA, or PMDA. In legacy setups, this work often evolved as monolithic scripts. A single program would ingest raw files, impute dates, derive endpoints, and output tables in one opaque pass. When an audit query or discrepancy arose, locating where a value transformed meant untangling deeply nested procedural code.</p>
<p>Clinical reporting is not an undifferentiated script; it is a pipeline of distinct, standardised stages defined by CDISC (Clinical Data Interchange Standards Consortium). Each transition has an explicit purpose, specific input expectations, and strict regulatory standards.</p>
<p>When engineering an R-based clinical reporting stack, teams need to know exactly which package handles which stage. Without clear boundaries, developers reinvent ad-hoc derivations, mix data manipulation with visual layout, and defer metadata checks until right before submission deadlines.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In data engineering and web platforms, production pipelines rely on strict <strong>schema contracts</strong> between decoupled stages:</p>
<pre class="text"><code>Raw Ingestion ──&gt; [Schema Contract] ──&gt; Transformation Layer ──&gt; [API Contract] ──&gt; Presentation
  (Webhooks)        (JSON Schema / Protobuf)     (dbt Models)        (OpenAPI / GraphQL)   (Client UI)</code></pre>
<p>At every boundary, data does not advance unless it satisfies the contract:</p>
<ul>
<li>Ingestion endpoints reject payloads violating an explicit JSON Schema or Protocol Buffer definition.</li>
<li>Transformation jobs (such as dbt models) operate on typed relations, running automated schema tests on every build.</li>
<li>The presentation layer renders components against typed API responses without guessing whether a field contains an integer, a formatted string, or an unexpected null.</li>
</ul>
<p>Applying this contract-first architecture to clinical programming turns an unpredictable script into an engineered pipeline. Rather than passing loosely structured data frames between ad-hoc scripts, each stage transforms data to satisfy an explicit specification before handing it downstream.</p>
</section>
<section id="the-r-way-stage-by-stage" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way-stage-by-stage">The R way, stage by stage</h2>
<p>The modern R clinical ecosystem, organised primarily under the <a href="https://pharmaverse.org">pharmaverse</a> initiative, provides specialised packages aligned to each CDISC stage.</p>
<section id="understanding-the-cdisc-terminology" class="level3">
<h3 class="anchored" data-anchor-id="understanding-the-cdisc-terminology">Understanding the CDISC terminology</h3>
<p>Before examining the packages, here is how the core CDISC artifacts connect:</p>
<ul>
<li><strong>CRF / Raw data</strong>: Case Report Forms recorded in electronic data capture (EDC) systems. These contain operational tracking fields, site-specific formats, and unstandardised coding.</li>
<li><strong>SDTM (Study Data Tabulation Model)</strong>: Standardises raw data across trials into consistent domains (<code>DM</code> for demographics, <code>AE</code> for adverse events, <code>VS</code> for vital signs) with standardised variable names, types, and controlled terminology.</li>
<li><strong>ADaM (Analysis Data Model)</strong>: Analysis-ready datasets derived from SDTM. ADaM datasets add derived timing windows, baseline flags, treatment allocations, and endpoint calculations (<code>ADSL</code> for subject-level analysis, <code>ADAE</code> for adverse events, <code>ADTTE</code> for time-to-event).</li>
<li><strong>TLFs / TFLs (Tables, Listings, and Figures)</strong>: The statistical summaries, individual patient listings, and graphical displays that populate the Clinical Study Report (CSR).</li>
<li><strong>define.xml</strong>: The machine-readable XML specification that describes the structure, variable definitions, controlled terminologies, derivation algorithms, and origins of all submitted datasets.</li>
<li><strong>XPT and Dataset-JSON</strong>: The data exchange formats used for regulatory submissions. SAS Transport Version 5 (XPT v5) has long been the primary submission format required by regulators. CDISC Dataset-JSON is a modern, lightweight JSON standard designed to exchange clinical datasets without XPT v5 limitations, such as 8-character variable names or 200-character string constraints.</li>
</ul>
</section>
<section id="the-r-package-ecosystem-by-stage" class="level3">
<h3 class="anchored" data-anchor-id="the-r-package-ecosystem-by-stage">The R package ecosystem by stage</h3>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Pipeline Stage</th>
<th>What it produces</th>
<th>R Packages</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Raw → SDTM</strong></td>
<td>Standardised SDTM domains (<code>DM</code>, <code>AE</code>, <code>VS</code>)</td>
<td><code>{sdtm.oak}</code></td>
</tr>
<tr class="even">
<td><strong>Metadata Specification</strong></td>
<td>Machine-readable specification objects</td>
<td><code>{metacore}</code>, <code>{metatools}</code></td>
</tr>
<tr class="odd">
<td><strong>SDTM → ADaM</strong></td>
<td>Analysis-ready datasets (<code>ADSL</code>, <code>ADAE</code>, <code>ADTTE</code>)</td>
<td><code>{admiral}</code> (+ extensions)</td>
</tr>
<tr class="even">
<td><strong>Example &amp; Test Data</strong></td>
<td>Reusable SDTM and ADaM datasets for tests</td>
<td><code>{pharmaversesdtm}</code>, <code>{pharmaverseadam}</code></td>
</tr>
<tr class="odd">
<td><strong>Submission Export</strong></td>
<td>XPT v5 or Dataset-JSON files, checked against the specification</td>
<td><code>{xportr}</code>, <code>{datasetjson}</code></td>
</tr>
<tr class="even">
<td><strong>TFL Generation</strong></td>
<td>Paginated tables, listings, and RTF/HTML outputs</td>
<td><code>{rtables}</code> + <code>{tern}</code>, <code>{gtsummary}</code>, <code>{Tplyr}</code>, <code>{tfrmt}</code>, <code>{rlistings}</code>, <code>{r2rtf}</code></td>
</tr>
<tr class="odd">
<td><strong>Analysis Results Data</strong></td>
<td>Tidy statistical results tables (ARD)</td>
<td><code>{cards}</code>, <code>{cardx}</code></td>
</tr>
</tbody>
</table>
</div>
<section id="raw-sdtm-sdtm.oak" class="level4">
<h4 class="anchored" data-anchor-id="raw-sdtm-sdtm.oak">Raw → SDTM: {sdtm.oak}</h4>
<p>Mapping raw EDC tables to SDTM domains involves recurring transformation patterns: creating ISO-8601 dates, mapping terms to CDISC controlled terminology, and handling condition-based assignments. Rather than bespoke scripts, <a href="https://pharmaverse.github.io/sdtm.oak/"><code>{sdtm.oak}</code></a> provides reusable mapping algorithms, such as <code>assign_datetime()</code>, <code>hardcode_ct()</code> and <code>create_iso8601()</code>, to build reproducible SDTM mapping code.</p>
</section>
<section id="metadata-driven-work-metacore-and-metatools" class="level4">
<h4 class="anchored" data-anchor-id="metadata-driven-work-metacore-and-metatools">Metadata-driven work: {metacore} and {metatools}</h4>
<p>In legacy pipelines, specifications were often buried inside spreadsheets that programmers manually referenced. <a href="https://pharmaverse.github.io/metacore/"><code>{metacore}</code></a> imports trial specifications directly from spreadsheets or <code>define.xml</code> files (<code>spec_to_metacore()</code>, <code>define_to_metacore()</code>), holding dataset definitions, variable types, lengths and controlled terminology codelists in one immutable R object.</p>
<p><a href="https://pharmaverse.github.io/metatools/"><code>{metatools}</code></a> pairs with <code>{metacore}</code> to apply and verify metadata at runtime. Functions like <code>check_variables()</code> verify that a dataset matches its specification, <code>check_ct_col()</code> confirms that values adhere to controlled terminology, and <code>set_variable_labels()</code> assigns attributes directly from the spec.</p>
</section>
<section id="adam-admiral" class="level4">
<h4 class="anchored" data-anchor-id="adam-admiral">ADaM: {admiral}</h4>
<p>Deriving ADaM datasets requires applying specific clinical rules: imputing partial dates, determining baseline values, and calculating study days. Instead of monolithic macros, <a href="https://pharmaverse.github.io/admiral/"><code>{admiral}</code></a> provides composable, modular <code>derive_*</code> functions designed to work directly with tidyverse workflows.</p>
<p>Beyond the core package, verified therapeutic area extensions on pharmaverse.org include: - <code>{admiralonco}</code> for Oncology endpoints - <code>{admiralophtha}</code> for Ophthalmology assessments - <code>{admiralvaccine}</code> for Vaccine trials - <code>{admiralpeds}</code> for Paediatric studies - <code>{admiralmetabolic}</code> for Metabolic trials - <code>{admiralneuro}</code> for Neuroscience assessments</p>
<p>Here is the shape of an <code>{admiral}</code> derivation: the first dose date for each subject, merged from exposure (EX) onto demographics (DM). It’s an excerpt from this post’s script (below), which runs.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;">library</span>(admiral)</span>
<span id="cb2-2"></span>
<span id="cb2-3"><span class="co" style="color: #5E5E5E;"># Exposure records with a start datetime; a dose &gt; 0, or placebo, counts.</span></span>
<span id="cb2-4">ex_ext <span class="ot" style="color: #003B4F;">&lt;-</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>ex <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-5">  <span class="fu" style="color: #4758AB;">derive_vars_dtm</span>(<span class="at" style="color: #657422;">dtc =</span> EXSTDTC, <span class="at" style="color: #657422;">new_vars_prefix =</span> <span class="st" style="color: #20794D;">"EXST"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-6">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">filter</span>(</span>
<span id="cb2-7">    (EXDOSE <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">|</span> (EXDOSE <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"PLACEBO"</span>, EXTRT))) <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(EXSTDTM)</span>
<span id="cb2-8">  )</span>
<span id="cb2-9"></span>
<span id="cb2-10">adsl <span class="ot" style="color: #003B4F;">&lt;-</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>dm <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-11">  dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mutate</span>(<span class="at" style="color: #657422;">TRT01P =</span> ARM, <span class="at" style="color: #657422;">TRT01A =</span> ACTARM) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-12">  <span class="fu" style="color: #4758AB;">derive_vars_merged</span>(</span>
<span id="cb2-13">    <span class="at" style="color: #657422;">dataset_add =</span> ex_ext,</span>
<span id="cb2-14">    <span class="at" style="color: #657422;">by_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(STUDYID, USUBJID),</span>
<span id="cb2-15">    <span class="at" style="color: #657422;">order =</span> <span class="fu" style="color: #4758AB;">exprs</span>(EXSTDTM, EXSEQ),</span>
<span id="cb2-16">    <span class="at" style="color: #657422;">new_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(<span class="at" style="color: #657422;">TRTSDTM =</span> EXSTDTM),</span>
<span id="cb2-17">    <span class="at" style="color: #657422;">mode =</span> <span class="st" style="color: #20794D;">"first"</span></span>
<span id="cb2-18">  ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb2-19">  <span class="fu" style="color: #4758AB;">derive_vars_dtm_to_dt</span>(<span class="at" style="color: #657422;">source_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(TRTSDTM))</span></code></pre></div></div>
<p>Each <code>derive_*()</code> call takes a dataset and returns it with new variables, so a derivation reads top to bottom, and each step can be tested on its own.</p>
</section>
<section id="example-data-pharmaversesdtm-and-pharmaverseadam" class="level4">
<h4 class="anchored" data-anchor-id="example-data-pharmaversesdtm-and-pharmaverseadam">Example data: {pharmaversesdtm} and {pharmaverseadam}</h4>
<p>Reliable unit tests and reproducible examples require standardised test data. <a href="https://pharmaverse.github.io/pharmaversesdtm/"><code>{pharmaversesdtm}</code></a> provides SDTM datasets (<code>dm</code>, <code>ae</code>, <code>lb</code>, <code>vs</code>, …) from the CDISC pilot project. <a href="https://pharmaverse.github.io/pharmaverseadam/"><code>{pharmaverseadam}</code></a> provides ADaM datasets built from them with <code>{admiral}</code> and its extensions (<code>adsl</code>, <code>adae</code>, <code>adlb</code>, <code>adtte_onco</code>, …). These packages allow teams to test derivation logic and develop reporting templates before live trial data arrives.</p>
<p>The post script <a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/scripts/pipeline-demo.R">scripts/pipeline-demo.R</a> takes SDTM DM and EX from <code>{pharmaversesdtm}</code>, derives a small ADSL with <code>{admiral}</code> (treatment dates, a safety population flag, age groups), and prints a demographics table by treatment arm with <code>{rtables}</code>. It has tests, like every script on this site.</p>
</section>
<section id="regulatory-export-xportr-and-datasetjson" class="level4">
<h4 class="anchored" data-anchor-id="regulatory-export-xportr-and-datasetjson">Regulatory export: {xportr} and {datasetjson}</h4>
<p>Creating an ADaM dataset is not the final step; regulatory agencies enforce strict file requirements. <a href="https://atorus-research.github.io/xportr/"><code>{xportr}</code></a> reads your <code>{metacore}</code> specification and systematically applies variable types (<code>xportr_type()</code>), variable lengths (<code>xportr_length()</code>), labels (<code>xportr_label()</code>), formats (<code>xportr_format()</code>), and sorting orders (<code>xportr_order()</code>), before writing the XPT v5 file with <code>xportr_write()</code>.</p>
<p>For modern submissions, <a href="https://atorus-research.github.io/datasetjson/"><code>{datasetjson}</code></a> provides utilities to write (<code>write_dataset_json()</code>), read (<code>read_dataset_json()</code>), and validate (<code>validate_dataset_json()</code>) CDISC Dataset-JSON files.</p>
</section>
<section id="tables-listings-and-figures-tfls" class="level4">
<h4 class="anchored" data-anchor-id="tables-listings-and-figures-tfls">Tables, Listings, and Figures (TFLs)</h4>
<p>When presenting study results, the R ecosystem offers distinct packages tailored to different reporting architectures:</p>
<ul>
<li><strong><code>{rtables}</code> + <code>{tern}</code></strong>: <code>{rtables}</code> provides a hierarchical layout engine for multi-level clinical tables, while <code>{tern}</code> supplies clinical analysis functions built on top of it.</li>
<li><strong><code>{gtsummary}</code></strong>: Summary and regression tables (for example <code>tbl_summary()</code>), widely used outside pharma too.</li>
<li><strong><code>{Tplyr}</code></strong>: Features an explicit grammar of clinical table construction, separating data extraction, summarisation (counts, shifts, descriptive statistics), and formatting.</li>
<li><strong><code>{tfrmt}</code></strong>: Provides a decoupled table formatting language that applies visual styling, alignment, and display rules to pre-aggregated data.</li>
<li><strong><code>{rlistings}</code></strong>: Builds formatted, paginated patient listings with key column grouping designed for Clinical Study Report appendices.</li>
<li><strong><code>{r2rtf}</code></strong>: Writes tables and listings to paginated Rich Text Format (RTF) documents, with control over margins and fonts.</li>
</ul>
</section>
<section id="analysis-results-data-cards-and-cardx" class="level4">
<h4 class="anchored" data-anchor-id="analysis-results-data-cards-and-cardx">Analysis Results Data: {cards} and {cardx}</h4>
<p>Traditional workflows compute summary statistics directly inside table-formatting routines, tightly coupling calculation with presentation. Analysis Results Data (ARD) decouples these responsibilities: <a href="https://pharmaverse.github.io/cards/"><code>{cards}</code></a> and <a href="https://insightsengineering.github.io/cardx/"><code>{cardx}</code></a> calculate statistical summaries and store them in tidy, standardised tabular structures. The same idea underlies the CDISC Analysis Results Standard (ARS): results stored as data can be checked and re-rendered without being recomputed. Later posts cover both.</p>
</section>
</section>
</section>
<section id="package-qualification-in-gxp-environments" class="level2">
<h2 class="anchored" data-anchor-id="package-qualification-in-gxp-environments">Package qualification in GxP environments</h2>
<p>In regulated clinical reporting, an open-source R package cannot simply be declared “validated” off the shelf. Validation is an organisational, risk-based process applied to an intended use within a qualified environment. The <a href="https://www.pharmar.org">R Validation Hub</a> provides a risk-based framework for evaluating package quality, and <a href="https://pharmar.github.io/riskmetric/"><code>{riskmetric}</code></a> collects metrics about a package, such as test coverage, documentation and maintenance activity, to inform that assessment. Later posts in this series will explore qualification pipelines, risk assessments, and double-programming quality control in detail.</p>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Treating example datasets as production inputs</strong>: Packages like <code>{pharmaversesdtm}</code> and <code>{pharmaverseadam}</code> are designed for prototyping, unit testing, and onboarding. Production pipelines must ingest verified study datasets that have completed formal clinical data-management reconciliation.</li>
<li><strong>Mixing specification versions mid-pipeline</strong>: If your ADaM derivation code assumes one version of a variable definition while <code>{metacore}</code> or the target <code>define.xml</code> references another, discrepancies emerge during export. Pin your specification objects and track them under version control.</li>
<li><strong>Deferring metadata checks until final export</strong>: Running <code>{xportr}</code> or <code>{metatools}</code> checks only at filing time turns missing labels, truncated lengths, and invalid codelist values into emergency firefighting. Run specification checks on every build in CI.</li>
<li><strong>Selecting TFL packages per programmer</strong>: Allowing each programmer on a study to select their preferred table package (<code>{rtables}</code> on one domain, <code>{Tplyr}</code> on another, <code>{gtsummary}</code> on a third) fragments code review, duplicates helper code, and complicates quality control. Standardise on a unified reporting framework across the project or team.</li>
</ul>
<div class="callout callout-style-simple callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Coming up in the Pharma series
</div>
</div>
<div class="callout-body-container callout-body">
<p>Later posts in this series explore TFL generation in depth, generating Analysis Results Data with <code>{cards}</code>, working with the CDISC Analysis Results Standard (ARS), and establishing qualification pipelines and quality control for validation-ready R packages.</p>
</div>
</div>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/scripts/pipeline-demo.R">View <code>pipeline-demo.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/scripts/pipeline-demo.R" download="pipeline-demo.R">Download</a></p>
<p>Takes SDTM DM and EX datasets from <code>{pharmaversesdtm}</code>, derives an ADSL data frame with <code>{admiral}</code>, and creates a summary demographics table by treatment arm using <code>{rtables}</code>. Requires <code>{admiral}</code>, <code>{pharmaversesdtm}</code>, <code>{dplyr}</code>, and <code>{rtables}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>pipeline-demo.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="co" style="color: #5E5E5E;"># SDTM -&gt; ADaM -&gt; TFL in one small script. Takes SDTM DM and EX from</span></span>
<span id="cb3-2"><span class="co" style="color: #5E5E5E;"># {pharmaversesdtm} (example data, not real patients), derives a small ADSL</span></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;"># with {admiral}, and prints a demographics table by treatment arm with</span></span>
<span id="cb3-4"><span class="co" style="color: #5E5E5E;"># {rtables}.</span></span>
<span id="cb3-5"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb3-6"><span class="co" style="color: #5E5E5E;">#   Rscript pipeline-demo.R</span></span>
<span id="cb3-7"></span>
<span id="cb3-8"><span class="fu" style="color: #4758AB;">library</span>(admiral)</span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="co" style="color: #5E5E5E;"># ADaM: one row per subject, with treatment variables, the first and last</span></span>
<span id="cb3-11"><span class="co" style="color: #5E5E5E;"># dose dates from EX, a safety population flag and an age group.</span></span>
<span id="cb3-12">derive_adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">dm =</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>dm, <span class="at" style="color: #657422;">ex =</span> pharmaversesdtm<span class="sc" style="color: #5E5E5E;">::</span>ex) {</span>
<span id="cb3-13">  <span class="co" style="color: #5E5E5E;"># Exposure records with a start datetime; a dose &gt; 0, or a placebo record,</span></span>
<span id="cb3-14">  <span class="co" style="color: #5E5E5E;"># counts as treated.</span></span>
<span id="cb3-15">  ex_ext <span class="ot" style="color: #003B4F;">&lt;-</span> ex <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-16">    <span class="fu" style="color: #4758AB;">derive_vars_dtm</span>(<span class="at" style="color: #657422;">dtc =</span> EXSTDTC, <span class="at" style="color: #657422;">new_vars_prefix =</span> <span class="st" style="color: #20794D;">"EXST"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-17">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">filter</span>(</span>
<span id="cb3-18">      (EXDOSE <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">|</span> (EXDOSE <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"PLACEBO"</span>, EXTRT))) <span class="sc" style="color: #5E5E5E;">&amp;</span></span>
<span id="cb3-19">        <span class="sc" style="color: #5E5E5E;">!</span><span class="fu" style="color: #4758AB;">is.na</span>(EXSTDTM)</span>
<span id="cb3-20">    )</span>
<span id="cb3-21"></span>
<span id="cb3-22">  dm <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-23">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mutate</span>(<span class="at" style="color: #657422;">TRT01P =</span> ARM, <span class="at" style="color: #657422;">TRT01A =</span> ACTARM) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-24">    <span class="fu" style="color: #4758AB;">derive_vars_merged</span>(</span>
<span id="cb3-25">      <span class="at" style="color: #657422;">dataset_add =</span> ex_ext,</span>
<span id="cb3-26">      <span class="at" style="color: #657422;">by_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(STUDYID, USUBJID),</span>
<span id="cb3-27">      <span class="at" style="color: #657422;">order =</span> <span class="fu" style="color: #4758AB;">exprs</span>(EXSTDTM, EXSEQ),</span>
<span id="cb3-28">      <span class="at" style="color: #657422;">new_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(<span class="at" style="color: #657422;">TRTSDTM =</span> EXSTDTM),</span>
<span id="cb3-29">      <span class="at" style="color: #657422;">mode =</span> <span class="st" style="color: #20794D;">"first"</span></span>
<span id="cb3-30">    ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-31">    <span class="fu" style="color: #4758AB;">derive_vars_merged</span>(</span>
<span id="cb3-32">      <span class="at" style="color: #657422;">dataset_add =</span> ex_ext,</span>
<span id="cb3-33">      <span class="at" style="color: #657422;">by_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(STUDYID, USUBJID),</span>
<span id="cb3-34">      <span class="at" style="color: #657422;">order =</span> <span class="fu" style="color: #4758AB;">exprs</span>(EXSTDTM, EXSEQ),</span>
<span id="cb3-35">      <span class="at" style="color: #657422;">new_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(<span class="at" style="color: #657422;">TRTEDTM =</span> EXSTDTM),</span>
<span id="cb3-36">      <span class="at" style="color: #657422;">mode =</span> <span class="st" style="color: #20794D;">"last"</span></span>
<span id="cb3-37">    ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-38">    <span class="fu" style="color: #4758AB;">derive_vars_dtm_to_dt</span>(<span class="at" style="color: #657422;">source_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(TRTSDTM, TRTEDTM)) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-39">    <span class="fu" style="color: #4758AB;">derive_var_merged_exist_flag</span>(</span>
<span id="cb3-40">      <span class="at" style="color: #657422;">dataset_add =</span> ex,</span>
<span id="cb3-41">      <span class="at" style="color: #657422;">by_vars =</span> <span class="fu" style="color: #4758AB;">exprs</span>(STUDYID, USUBJID),</span>
<span id="cb3-42">      <span class="at" style="color: #657422;">new_var =</span> SAFFL,</span>
<span id="cb3-43">      <span class="at" style="color: #657422;">condition =</span> (EXDOSE <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">|</span> (EXDOSE <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span> <span class="sc" style="color: #5E5E5E;">&amp;</span> <span class="fu" style="color: #4758AB;">grepl</span>(<span class="st" style="color: #20794D;">"PLACEBO"</span>, EXTRT))),</span>
<span id="cb3-44">      <span class="at" style="color: #657422;">false_value =</span> <span class="st" style="color: #20794D;">"N"</span>,</span>
<span id="cb3-45">      <span class="at" style="color: #657422;">missing_value =</span> <span class="st" style="color: #20794D;">"N"</span> <span class="co" style="color: #5E5E5E;"># no EX records at all (e.g. screen failures)</span></span>
<span id="cb3-46">    ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-47">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mutate</span>(</span>
<span id="cb3-48">      <span class="at" style="color: #657422;">AGEGR1 =</span> <span class="fu" style="color: #4758AB;">factor</span>(</span>
<span id="cb3-49">        dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">case_when</span>(</span>
<span id="cb3-50">          AGE <span class="sc" style="color: #5E5E5E;">&lt;</span> <span class="dv" style="color: #AD0000;">65</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&lt;65"</span>,</span>
<span id="cb3-51">          AGE <span class="sc" style="color: #5E5E5E;">&lt;=</span> <span class="dv" style="color: #AD0000;">80</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"65-80"</span>,</span>
<span id="cb3-52">          AGE <span class="sc" style="color: #5E5E5E;">&gt;</span> <span class="dv" style="color: #AD0000;">80</span> <span class="sc" style="color: #5E5E5E;">~</span> <span class="st" style="color: #20794D;">"&gt;80"</span></span>
<span id="cb3-53">        ),</span>
<span id="cb3-54">        <span class="at" style="color: #657422;">levels =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"&lt;65"</span>, <span class="st" style="color: #20794D;">"65-80"</span>, <span class="st" style="color: #20794D;">"&gt;80"</span>)</span>
<span id="cb3-55">      )</span>
<span id="cb3-56">    )</span>
<span id="cb3-57">}</span>
<span id="cb3-58"></span>
<span id="cb3-59"><span class="co" style="color: #5E5E5E;"># TFL: demographics of the safety population, by actual treatment.</span></span>
<span id="cb3-60">demographics_table <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(adsl) {</span>
<span id="cb3-61">  saf <span class="ot" style="color: #003B4F;">&lt;-</span> adsl <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-62">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">filter</span>(SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-63">    dplyr<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">mutate</span>(<span class="at" style="color: #657422;">TRT01A =</span> <span class="fu" style="color: #4758AB;">factor</span>(TRT01A), <span class="at" style="color: #657422;">SEX =</span> <span class="fu" style="color: #4758AB;">factor</span>(SEX))</span>
<span id="cb3-64"></span>
<span id="cb3-65">  rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">basic_table</span>(</span>
<span id="cb3-66">    <span class="at" style="color: #657422;">title =</span> <span class="st" style="color: #20794D;">"Demographics"</span>,</span>
<span id="cb3-67">    <span class="at" style="color: #657422;">subtitles =</span> <span class="st" style="color: #20794D;">"Safety population (example data)"</span></span>
<span id="cb3-68">  ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-69">    rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">split_cols_by</span>(<span class="st" style="color: #20794D;">"TRT01A"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-70">    rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">add_overall_col</span>(<span class="st" style="color: #20794D;">"All patients"</span>) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-71">    rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">analyze</span>(</span>
<span id="cb3-72">      <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"AGE"</span>, <span class="st" style="color: #20794D;">"AGEGR1"</span>, <span class="st" style="color: #20794D;">"SEX"</span>),</span>
<span id="cb3-73">      <span class="at" style="color: #657422;">var_labels =</span> <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"Age (years)"</span>, <span class="st" style="color: #20794D;">"Age group"</span>, <span class="st" style="color: #20794D;">"Sex"</span>)</span>
<span id="cb3-74">    ) <span class="sc" style="color: #5E5E5E;">|&gt;</span></span>
<span id="cb3-75">    rtables<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">build_table</span>(saf)</span>
<span id="cb3-76">}</span>
<span id="cb3-77"></span>
<span id="cb3-78"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb3-79"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb3-80">  adsl <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">derive_adsl</span>()</span>
<span id="cb3-81">  <span class="fu" style="color: #4758AB;">message</span>(</span>
<span id="cb3-82">    <span class="fu" style="color: #4758AB;">nrow</span>(adsl),</span>
<span id="cb3-83">    <span class="st" style="color: #20794D;">" subjects in ADSL; "</span>,</span>
<span id="cb3-84">    <span class="fu" style="color: #4758AB;">sum</span>(adsl<span class="sc" style="color: #5E5E5E;">$</span>SAFFL <span class="sc" style="color: #5E5E5E;">==</span> <span class="st" style="color: #20794D;">"Y"</span>),</span>
<span id="cb3-85">    <span class="st" style="color: #20794D;">" in the safety population"</span></span>
<span id="cb3-86">  )</span>
<span id="cb3-87">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">demographics_table</span>(adsl))</span>
<span id="cb3-88">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Standards and organisations</strong></p>
<ul>
<li><strong>pharmaverse</strong> initiative: <a href="https://pharmaverse.org">pharmaverse.org</a></li>
<li><strong>R Validation Hub</strong>: <a href="https://pharmar.org/">pharmar.org</a></li>
</ul>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>sdtm.oak</strong>: <a href="https://pharmaverse.github.io/sdtm.oak/">pharmaverse.github.io/sdtm.oak</a></li>
<li><strong>metacore</strong>: <a href="https://atorus-research.github.io/metacore/">atorus-research.github.io/metacore</a></li>
<li><strong>metatools</strong>: <a href="https://pharmaverse.github.io/metatools/">pharmaverse.github.io/metatools</a></li>
<li><strong>admiral</strong>: <a href="https://pharmaverse.github.io/admiral/">pharmaverse.github.io/admiral</a></li>
<li><strong>pharmaversesdtm</strong>: <a href="https://pharmaverse.github.io/pharmaversesdtm/">pharmaverse.github.io/pharmaversesdtm</a></li>
<li><strong>pharmaverseadam</strong>: <a href="https://pharmaverse.github.io/pharmaverseadam/">pharmaverse.github.io/pharmaverseadam</a></li>
<li><strong>xportr</strong>: <a href="https://atorus-research.github.io/xportr/">atorus-research.github.io/xportr</a></li>
<li><strong>datasetjson</strong>: <a href="https://atorus-research.github.io/datasetjson/">atorus-research.github.io/datasetjson</a></li>
<li><strong>rtables</strong>: <a href="https://cran.r-project.org/package=rtables">CRAN</a></li>
<li><strong>tern</strong>: <a href="https://cran.r-project.org/package=tern">CRAN</a></li>
<li><strong>gtsummary</strong>: <a href="https://www.danieldsjoberg.com/gtsummary/">danieldsjoberg.com/gtsummary</a></li>
<li><strong>Tplyr</strong>: <a href="https://atorus-research.github.io/Tplyr/">atorus-research.github.io/Tplyr</a></li>
<li><strong>tfrmt</strong>: <a href="https://cran.r-project.org/package=tfrmt">CRAN</a></li>
<li><strong>rlistings</strong>: <a href="https://cran.r-project.org/package=rlistings">CRAN</a></li>
<li><strong>r2rtf</strong>: <a href="https://cran.r-project.org/package=r2rtf">CRAN</a></li>
<li><strong>cards</strong>: <a href="https://pharmaverse.github.io/cards/">pharmaverse.github.io/cards</a></li>
<li><strong>cardx</strong>: <a href="https://insightsengineering.github.io/cardx/">insightsengineering.github.io/cardx</a></li>
<li><strong>riskmetric</strong>: <a href="https://pharmar.github.io/riskmetric/">pharmar.github.io/riskmetric</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/pharma.html" class="site-series-nav__series">Pharma series · part 1 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/tfl-generation-r/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 2</span><span class="site-related-card__title">Generating tables, figures and listings in R</span></a>
</div>
</div>
</div>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/testthat-essentials/index.html" class="site-link-row" title="Set up testthat 3rd edition, structure unit tests with expectations, run them locally and in CI, and build reproducible verification suites."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">testthat essentials</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="site-link-row" title="Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">Coverage and tests as evidence</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/property-based-testing/index.html" class="site-link-row" title="Define general invariants, generate varied test inputs with quickcheck, and use shrinking to pinpoint edge cases in R functions and clinical derivations."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Property-based testing in R</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>Pharma</category>
  <category>R</category>
  <category>GxP</category>
  <guid>https://insightsurge-dev.web.app/posts/clinical-reporting-pipeline-r/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
<item>
  <title>testthat essentials</title>
  <link>https://insightsurge-dev.web.app/posts/testthat-essentials/</link>
  <description><![CDATA[ 





<!--
  Quarto 1.8.27's title-block.html with three changes: category badges and a
  series link ("Testing series · part 2") sit above the title, as in the brand's
  blog kit; and a post or series page with `trailer: true` shows its trailer beside the title
  (_filters/trailer.lua sets trailer-path; _includes/trailers.html plays it). On a Quarto upgrade, diff this against
  share/formats/html/templates/title-block.html and carry over any changes.
-->



<section id="the-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-problem">The problem</h2>
<p>Most R developers begin testing interactively in the console. You write a function, call it with sample arguments, glance at the resulting vector or data frame, decide it looks right, and move on.</p>
<p>That works until code changes:</p>
<ul>
<li>A colleague tweaks a helper function, altering missing value handling.</li>
<li>An upstream package updates and returns a tibble where base R returned a vector.</li>
<li>You refactor months later and forget which edge cases previously broke your logic.</li>
</ul>
<p>Manual console checks are unrecorded, unrepeatable, and trapped on a single machine. They do not run in continuous integration, cannot prevent pull request regressions, and leave no record anyone could review later.</p>
<p>Automated unit tests replace human memory with executable assertions. They form the base for everything else in this series: test fixtures, mocking, snapshot tests, Shiny tests, and tests as evidence.</p>
</section>
<section id="the-web-repo-way" class="level2">
<h2 class="anchored" data-anchor-id="the-web-repo-way">The web-repo way</h2>
<p>In JavaScript and TypeScript repositories, frameworks like Vitest and Jest make testing an ambient part of development:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb1-1"><span class="co" style="color: #5E5E5E;">// src/format.ts</span></span>
<span id="cb1-2"><span class="im" style="color: #00769E;">export</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">function</span> <span class="fu" style="color: #4758AB;">formatRatio</span>(numerator<span class="op" style="color: #5E5E5E;">:</span> <span class="dt" style="color: #AD0000;">number</span><span class="op" style="color: #5E5E5E;">,</span> denominator<span class="op" style="color: #5E5E5E;">:</span> <span class="dt" style="color: #AD0000;">number</span>)<span class="op" style="color: #5E5E5E;">:</span> <span class="dt" style="color: #AD0000;">string</span> {</span>
<span id="cb1-3">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (denominator <span class="op" style="color: #5E5E5E;">===</span> <span class="dv" style="color: #AD0000;">0</span>) <span class="cf" style="color: #003B4F;
font-weight: bold;">throw</span> <span class="kw" style="color: #003B4F;
font-weight: bold;">new</span> <span class="bu" style="color: null;">Error</span>(<span class="st" style="color: #20794D;">"Denominator cannot be zero"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-4">  <span class="cf" style="color: #003B4F;
font-weight: bold;">return</span> <span class="vs" style="color: #20794D;">`</span><span class="sc" style="color: #5E5E5E;">${</span>((numerator <span class="op" style="color: #5E5E5E;">/</span> denominator) <span class="op" style="color: #5E5E5E;">*</span> <span class="dv" style="color: #AD0000;">100</span>)<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toFixed</span>(<span class="dv" style="color: #AD0000;">1</span>)<span class="sc" style="color: #5E5E5E;">}</span><span class="vs" style="color: #20794D;">%`</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-5">}</span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="co" style="color: #5E5E5E;">// src/format.test.ts</span></span>
<span id="cb1-8"><span class="im" style="color: #00769E;">import</span> { describe<span class="op" style="color: #5E5E5E;">,</span> it<span class="op" style="color: #5E5E5E;">,</span> expect } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"vitest"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-9"><span class="im" style="color: #00769E;">import</span> { formatRatio } <span class="im" style="color: #00769E;">from</span> <span class="st" style="color: #20794D;">"./format"</span><span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-10"></span>
<span id="cb1-11"><span class="fu" style="color: #4758AB;">describe</span>(<span class="st" style="color: #20794D;">"formatRatio"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;">it</span>(<span class="st" style="color: #20794D;">"formats standard percentages correctly"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;">expect</span>(<span class="fu" style="color: #4758AB;">formatRatio</span>(<span class="dv" style="color: #AD0000;">1</span><span class="op" style="color: #5E5E5E;">,</span> <span class="dv" style="color: #AD0000;">4</span>))<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toBe</span>(<span class="st" style="color: #20794D;">"25.0%"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-14">  })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-15"></span>
<span id="cb1-16">  <span class="fu" style="color: #4758AB;">it</span>(<span class="st" style="color: #20794D;">"throws on zero denominator"</span><span class="op" style="color: #5E5E5E;">,</span> () <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> {</span>
<span id="cb1-17">    <span class="fu" style="color: #4758AB;">expect</span>(() <span class="kw" style="color: #003B4F;
font-weight: bold;">=&gt;</span> <span class="fu" style="color: #4758AB;">formatRatio</span>(<span class="dv" style="color: #AD0000;">1</span><span class="op" style="color: #5E5E5E;">,</span> <span class="dv" style="color: #AD0000;">0</span>))<span class="op" style="color: #5E5E5E;">.</span><span class="fu" style="color: #4758AB;">toThrow</span>(<span class="st" style="color: #20794D;">"Denominator cannot be zero"</span>)<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-18">  })<span class="op" style="color: #5E5E5E;">;</span></span>
<span id="cb1-19">})<span class="op" style="color: #5E5E5E;">;</span></span></code></pre></div></div>
<p>Web repositories rely on three core patterns:</p>
<ol type="1">
<li><strong>Co-located pairing:</strong> Tests mirror source code directly (<code>format.ts</code> ↔︎ <code>format.test.ts</code>).</li>
<li><strong>Fast feedback loops:</strong> <code>npm test</code> runs the suite, and watch mode re-runs tests on save.</li>
<li><strong>CI gates:</strong> Tests run automatically on every pull request. Broken tests block merges.</li>
</ol>
</section>
<section id="the-r-way" class="level2">
<h2 class="anchored" data-anchor-id="the-r-way">The R way</h2>
<p>In R, the standard framework is <a href="https://testthat.r-lib.org/"><code>testthat</code></a>. Together with <a href="https://usethis.r-lib.org/"><code>usethis</code></a> and <a href="https://devtools.r-lib.org/"><code>devtools</code></a>, it provides an equivalent development workflow.</p>
<section id="setup-with-usethisuse_testthat3" class="level3">
<h3 class="anchored" data-anchor-id="setup-with-usethisuse_testthat3">1 · Setup with <code>usethis::use_testthat(3)</code></h3>
<p>Set up package testing infrastructure with one command:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb2-1">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_testthat</span>(<span class="dv" style="color: #AD0000;">3</span>)</span></code></pre></div></div>
<p>This performs four key actions:</p>
<ol type="1">
<li><p><strong>Creates <code>tests/testthat/</code>:</strong> The home for all unit test files.</p></li>
<li><p><strong>Creates <code>tests/testthat.R</code>:</strong> The test harness executed during package checks:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;">library</span>(testthat)</span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;">library</span>(yourpackage)</span>
<span id="cb3-3"></span>
<span id="cb3-4"><span class="fu" style="color: #4758AB;">test_check</span>(<span class="st" style="color: #20794D;">"yourpackage"</span>)</span></code></pre></div></div></li>
<li><p><strong>Adds <code>testthat (&gt;= 3.0.0)</code> to <code>Suggests</code></strong> in <code>DESCRIPTION</code>.</p></li>
<li><p><strong>Sets <code>Config/testthat/edition: 3</code> in <code>DESCRIPTION</code>:</strong> Activates testthat’s 3rd edition.</p></li>
</ol>
</section>
<section id="file-pairing-with-usethisuse_test" class="level3">
<h3 class="anchored" data-anchor-id="file-pairing-with-usethisuse_test">2 · File pairing with <code>usethis::use_test()</code></h3>
<p>Package code lives in <code>R/&lt;name&gt;.R</code> and its corresponding tests live in <code>tests/testthat/test-&lt;name&gt;.R</code>.</p>
<p>Create or navigate to the paired test file using <code>usethis::use_test()</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="co" style="color: #5E5E5E;"># With R/format_ratio.R open in RStudio:</span></span>
<span id="cb4-2">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_test</span>()</span>
<span id="cb4-3"></span>
<span id="cb4-4"><span class="co" style="color: #5E5E5E;"># Or specify the name explicitly:</span></span>
<span id="cb4-5">usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_test</span>(<span class="st" style="color: #20794D;">"format_ratio"</span>)</span></code></pre></div></div>
<p><code>use_test()</code> creates <code>tests/testthat/test-format_ratio.R</code> if it’s missing and opens it. <code>usethis::use_r()</code> goes the other way, from a test file to its code file.</p>
</section>
<section id="anatomy-of-a-test-blocks-and-expectations" class="level3">
<h3 class="anchored" data-anchor-id="anatomy-of-a-test-blocks-and-expectations">3 · Anatomy of a test: blocks and expectations</h3>
<p>Say <code>R/format_ratio.R</code> holds:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">format_ratio <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(numerator, denominator) {</span>
<span id="cb5-2">  <span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (denominator <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>) <span class="fu" style="color: #4758AB;">stop</span>(<span class="st" style="color: #20794D;">"Denominator cannot be zero"</span>)</span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;">sprintf</span>(<span class="st" style="color: #20794D;">"%.1f%%"</span>, numerator <span class="sc" style="color: #5E5E5E;">/</span> denominator <span class="sc" style="color: #5E5E5E;">*</span> <span class="dv" style="color: #AD0000;">100</span>)</span>
<span id="cb5-4">}</span></code></pre></div></div>
<p>A test file groups expectations inside <code>test_that()</code> blocks, each describing one behaviour:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"format_ratio() formats percentages to one decimal place"</span>, {</span>
<span id="cb6-2">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">format_ratio</span>(<span class="dv" style="color: #AD0000;">1</span>, <span class="dv" style="color: #AD0000;">4</span>), <span class="st" style="color: #20794D;">"25.0%"</span>)</span>
<span id="cb6-3">  <span class="fu" style="color: #4758AB;">expect_equal</span>(<span class="fu" style="color: #4758AB;">format_ratio</span>(<span class="dv" style="color: #AD0000;">2</span>, <span class="dv" style="color: #AD0000;">3</span>), <span class="st" style="color: #20794D;">"66.7%"</span>)</span>
<span id="cb6-4">})</span>
<span id="cb6-5"></span>
<span id="cb6-6"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"format_ratio() rejects a zero denominator"</span>, {</span>
<span id="cb6-7">  <span class="fu" style="color: #4758AB;">expect_error</span>(<span class="fu" style="color: #4758AB;">format_ratio</span>(<span class="dv" style="color: #AD0000;">1</span>, <span class="dv" style="color: #AD0000;">0</span>), <span class="st" style="color: #20794D;">"Denominator cannot be zero"</span>)</span>
<span id="cb6-8">})</span></code></pre></div></div>
<p>Common expectations cover standard R data structures and conditions:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Expectation</th>
<th>Verifies</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>expect_equal(object, expected)</code></td>
<td>Equality within numerical tolerance</td>
<td><code>expect_equal(sqrt(2)^2, 2)</code></td>
</tr>
<tr class="even">
<td><code>expect_identical(object, expected)</code></td>
<td>Exact equality (no tolerance)</td>
<td><code>expect_identical(1L + 1L, 2L)</code></td>
</tr>
<tr class="odd">
<td><code>expect_error(object, regexp, class)</code></td>
<td>Throws expected error</td>
<td><code>expect_error(log("a"))</code></td>
</tr>
<tr class="even">
<td><code>expect_warning(object, regexp, class)</code></td>
<td>Signals expected warning</td>
<td><code>expect_warning(as.numeric("a"))</code></td>
</tr>
<tr class="odd">
<td><code>expect_message(object, regexp, class)</code></td>
<td>Emits expected message</td>
<td><code>expect_message(message("ready"))</code></td>
</tr>
<tr class="even">
<td><code>expect_true(object)</code> / <code>expect_false(object)</code></td>
<td>Scalar boolean condition</td>
<td><code>expect_true(is.data.frame(df))</code></td>
</tr>
<tr class="odd">
<td><code>expect_length(object, n)</code></td>
<td>Length of vector or list</td>
<td><code>expect_length(names(df), 5)</code></td>
</tr>
<tr class="even">
<td><code>expect_named(object, expected)</code></td>
<td>Vector or list names</td>
<td><code>expect_named(res, c("id", "val"))</code></td>
</tr>
</tbody>
</table>
</div>
</section>
<section id="what-the-3rd-edition-changes" class="level3">
<h3 class="anchored" data-anchor-id="what-the-3rd-edition-changes">What the 3rd edition changes</h3>
<p>The 3rd edition modernises testing behaviour:</p>
<ul>
<li><strong>Clearer differences:</strong> <code>expect_equal()</code> and <code>expect_identical()</code> use <a href="https://waldo.r-lib.org/"><code>waldo::compare()</code></a>, which shows exactly which elements or attributes differ.</li>
<li><strong>Messages aren’t hidden:</strong> the 2nd edition silently dropped messages raised inside a test. The 3rd edition shows them, so an unexpected message gets noticed.</li>
<li><strong>Reproducible output:</strong> each test runs with fixed settings (80-character width, no colour or Unicode, C language and collation), so output doesn’t change between machines.</li>
<li><strong>Deprecated functions:</strong> <code>context()</code> is deprecated (the file name gives the context), and <code>expect_is()</code> gives way to <code>expect_type()</code>, <code>expect_s3_class()</code> and <code>expect_s4_class()</code>.</li>
</ul>
</section>
<section id="running-tests" class="level3">
<h3 class="anchored" data-anchor-id="running-tests">4 · Running tests</h3>
<p>Run tests at the appropriate scope throughout your day:</p>
<div class="table-responsive">
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Scope</th>
<th>Command</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Active file</strong></td>
<td><code>devtools::test_active_file()</code></td>
<td>Quick feedback while editing one file</td>
</tr>
<tr class="even">
<td><strong>Single file</strong></td>
<td><code>testthat::test_file("tests/testthat/test-calc.R")</code></td>
<td>Verify a subsystem from the console</td>
</tr>
<tr class="odd">
<td><strong>Full suite</strong></td>
<td><code>devtools::test()</code></td>
<td>Verify the whole package before committing</td>
</tr>
<tr class="even">
<td><strong>Package check</strong></td>
<td><code>devtools::check()</code> / <code>R CMD check</code></td>
<td>Full pre-merge gate locally and in CI</td>
</tr>
</tbody>
</table>
</div>
<p>In RStudio, <code>Ctrl+Shift+T</code> (<code>Cmd+Shift+T</code> on a Mac) runs <code>devtools::test()</code>. In CI, <code>R CMD check</code> runs <code>tests/testthat.R</code>; a failing test is a check error, so the pull request goes red.</p>
</section>
<section id="skip-helpers" class="level3">
<h3 class="anchored" data-anchor-id="skip-helpers">5 · Skip helpers</h3>
<p>Not every test belongs in every environment. Use skip helpers to bypass checks gracefully:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;">test_that</span>(<span class="st" style="color: #20794D;">"fetches clinical metadata from remote repository"</span>, {</span>
<span id="cb7-2">  <span class="fu" style="color: #4758AB;">skip_on_cran</span>()                    <span class="co" style="color: #5E5E5E;"># Skip on CRAN to respect network and time limits</span></span>
<span id="cb7-3">  <span class="fu" style="color: #4758AB;">skip_if_offline</span>()                 <span class="co" style="color: #5E5E5E;"># Skip if no internet connectivity</span></span>
<span id="cb7-4">  <span class="fu" style="color: #4758AB;">skip_if_not_installed</span>(<span class="st" style="color: #20794D;">"httr2"</span>)    <span class="co" style="color: #5E5E5E;"># Skip if an optional dependency is missing</span></span>
<span id="cb7-5"></span>
<span id="cb7-6">  res <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">fetch_clinical_metadata</span>(<span class="st" style="color: #20794D;">"STUDY-01"</span>)</span>
<span id="cb7-7">  <span class="fu" style="color: #4758AB;">expect_s3_class</span>(res, <span class="st" style="color: #20794D;">"data.frame"</span>)</span>
<span id="cb7-8">})</span></code></pre></div></div>
<p>Skips are reported as skips, not failures, so the results still show what didn’t run.</p>
</section>
<section id="tests-outside-a-package" class="level3">
<h3 class="anchored" data-anchor-id="tests-outside-a-package">6 · Tests outside a package</h3>
<p>You do not need a package structure to write unit tests. Shiny apps, Quarto sites, and data pipelines can adopt testthat directly:</p>
<ol type="1">
<li>Create <code>tests/testthat/</code> at your repository root.</li>
<li>Add standard <code>test-*.R</code> test files.</li>
<li>Run the directory using:</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r norun code-with-copy"><code class="sourceCode r"><span id="cb8-1">testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_dir</span>(<span class="st" style="color: #20794D;">"tests/testthat"</span>, <span class="at" style="color: #657422;">stop_on_failure =</span> <span class="cn" style="color: #8f5902;">TRUE</span>)</span></code></pre></div></div>
<p><code>stop_on_failure = TRUE</code> (the default) makes the call fail when any test fails, which is what a CI step needs. This site does exactly that: its post scripts, such as the one below, have tests that run with <code>test_dir()</code> on every pull request.</p>
</section>
<section id="tests-as-evidence-the-gxp-angle" class="level3">
<h3 class="anchored" data-anchor-id="tests-as-evidence-the-gxp-angle">7 · Tests as evidence: the GxP angle</h3>
<p>In regulated work, “I checked it in the console” isn’t evidence anyone can review. Automated tests are:</p>
<ul>
<li><strong>Repeatable:</strong> anyone can re-run them and get the same result.</li>
<li><strong>Recorded:</strong> a CI run keeps the results together with the commit, the R version and (with renv) the exact package versions.</li>
<li><strong>Traceable:</strong> a test’s description can reference the requirement it checks.</li>
</ul>
<p>That makes test results useful evidence in a risk-based validation approach. A later post in this series covers traceability from requirements to tests.</p>
<p>The next posts in the series cover test design (fixtures, temporary state with <code>withr</code>, and mocking), then snapshot tests.</p>
</section>
</section>
<section id="pitfalls" class="level2">
<h2 class="anchored" data-anchor-id="pitfalls">Pitfalls</h2>
<ul>
<li><strong>Tests depending on global state or working directory:</strong> Never rely on variables left in the global environment or unreset <code>setwd()</code> calls. Each test must run independently in any order.</li>
<li><strong>Testing implementation details over interfaces:</strong> Assert against public function inputs and outputs. If refactoring an internal loop breaks your tests while external behaviour remains unchanged, your tests are too tightly coupled to implementation.</li>
<li><strong>Huge <code>test_that()</code> blocks:</strong> thirty expectations under one description make a failure hard to place, and an <em>error</em> (unlike a failed expectation) stops the rest of the block. Give each behaviour its own block.</li>
<li><strong>Forgetting the edition:</strong> without <code>Config/testthat/edition: 3</code> in <code>DESCRIPTION</code>, a package’s tests run in the 2nd edition, which silences messages and skips the reproducible-output settings.</li>
</ul>
</section>
<section id="companion-code" class="level2">
<h2 class="anchored" data-anchor-id="companion-code">Companion code</h2>
<p><a href="https://insightsurge-dev.web.app/posts/testthat-essentials/scripts/first-tests.R">View <code>first-tests.R</code></a> · <a href="https://insightsurge-dev.web.app/posts/testthat-essentials/scripts/first-tests.R" download="first-tests.R">Download</a></p>
<p>Builds a throwaway package in a temporary directory, configures testthat and helper files with <code>{usethis}</code>, and executes the test suite with <code>{testthat}</code>. Requires <code>{testthat}</code> and <code>{usethis}</code>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Full script: <code>first-tests.R</code>
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="co" style="color: #5E5E5E;"># The testthat loop, end to end: builds a throwaway package in a temporary</span></span>
<span id="cb9-2"><span class="co" style="color: #5E5E5E;"># folder, adds a small function and its tests with usethis, and runs the tests</span></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;"># with testthat.</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;">#</span></span>
<span id="cb9-5"><span class="co" style="color: #5E5E5E;">#   Rscript first-tests.R</span></span>
<span id="cb9-6"></span>
<span id="cb9-7">bmi_code <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-8">  <span class="st" style="color: #20794D;">"#' Body mass index"</span>,</span>
<span id="cb9-9">  <span class="st" style="color: #20794D;">"#'"</span>,</span>
<span id="cb9-10">  <span class="st" style="color: #20794D;">"#' @param weight_kg Weight in kilograms."</span>,</span>
<span id="cb9-11">  <span class="st" style="color: #20794D;">"#' @param height_m Height in metres."</span>,</span>
<span id="cb9-12">  <span class="st" style="color: #20794D;">"#' @return Weight divided by height squared."</span>,</span>
<span id="cb9-13">  <span class="st" style="color: #20794D;">"#' @export"</span>,</span>
<span id="cb9-14">  <span class="st" style="color: #20794D;">"bmi &lt;- function(weight_kg, height_m) {"</span>,</span>
<span id="cb9-15">  <span class="st" style="color: #20794D;">"  if (any(height_m &lt;= 0, na.rm = TRUE)) {"</span>,</span>
<span id="cb9-16">  <span class="st" style="color: #20794D;">"    stop(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">`height_m` must be positive.</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, call. = FALSE)"</span>,</span>
<span id="cb9-17">  <span class="st" style="color: #20794D;">"  }"</span>,</span>
<span id="cb9-18">  <span class="st" style="color: #20794D;">"  weight_kg / height_m^2"</span>,</span>
<span id="cb9-19">  <span class="st" style="color: #20794D;">"}"</span></span>
<span id="cb9-20">)</span>
<span id="cb9-21"></span>
<span id="cb9-22">bmi_tests <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">c</span>(</span>
<span id="cb9-23">  <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">bmi() divides weight by height squared</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-24">  <span class="st" style="color: #20794D;">"  expect_equal(bmi(70, 1.75), 22.857, tolerance = 1e-4)"</span>,</span>
<span id="cb9-25">  <span class="st" style="color: #20794D;">"})"</span>,</span>
<span id="cb9-26">  <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-27">  <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">bmi() is vectorised</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-28">  <span class="st" style="color: #20794D;">"  expect_length(bmi(c(60, 70, 80), c(1.6, 1.7, 1.8)), 3)"</span>,</span>
<span id="cb9-29">  <span class="st" style="color: #20794D;">"})"</span>,</span>
<span id="cb9-30">  <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-31">  <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">bmi() rejects heights that aren't positive</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-32">  <span class="st" style="color: #20794D;">"  expect_error(bmi(70, 0), </span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">must be positive</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">)"</span>,</span>
<span id="cb9-33">  <span class="st" style="color: #20794D;">"})"</span>,</span>
<span id="cb9-34">  <span class="st" style="color: #20794D;">""</span>,</span>
<span id="cb9-35">  <span class="st" style="color: #20794D;">"test_that(</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">bmi() keeps missing values missing</span><span class="sc" style="color: #5E5E5E;">\"</span><span class="st" style="color: #20794D;">, {"</span>,</span>
<span id="cb9-36">  <span class="st" style="color: #20794D;">"  expect_true(is.na(bmi(NA, 1.7)))"</span>,</span>
<span id="cb9-37">  <span class="st" style="color: #20794D;">"})"</span></span>
<span id="cb9-38">)</span>
<span id="cb9-39"></span>
<span id="cb9-40"><span class="co" style="color: #5E5E5E;"># Creates the package and returns its path.</span></span>
<span id="cb9-41">make_demo_package <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(<span class="at" style="color: #657422;">path =</span> <span class="fu" style="color: #4758AB;">file.path</span>(<span class="fu" style="color: #4758AB;">tempdir</span>(), <span class="st" style="color: #20794D;">"bmicalc"</span>)) {</span>
<span id="cb9-42">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">create_package</span>(path, <span class="at" style="color: #657422;">rstudio =</span> <span class="cn" style="color: #8f5902;">FALSE</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-43">  usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">with_project</span>(path, {</span>
<span id="cb9-44">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_testthat</span>(<span class="dv" style="color: #AD0000;">3</span>) <span class="co" style="color: #5E5E5E;"># tests/testthat/, tests/testthat.R, edition 3</span></span>
<span id="cb9-45">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_r</span>(<span class="st" style="color: #20794D;">"bmi"</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>) <span class="co" style="color: #5E5E5E;"># creates the R/bmi.R file</span></span>
<span id="cb9-46">    usethis<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">use_test</span>(<span class="st" style="color: #20794D;">"bmi"</span>, <span class="at" style="color: #657422;">open =</span> <span class="cn" style="color: #8f5902;">FALSE</span>) <span class="co" style="color: #5E5E5E;"># creates its test file</span></span>
<span id="cb9-47">  })</span>
<span id="cb9-48">  <span class="fu" style="color: #4758AB;">writeLines</span>(bmi_code, <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"R"</span>, <span class="st" style="color: #20794D;">"bmi.R"</span>))</span>
<span id="cb9-49">  <span class="fu" style="color: #4758AB;">writeLines</span>(bmi_tests, <span class="fu" style="color: #4758AB;">file.path</span>(path, <span class="st" style="color: #20794D;">"tests"</span>, <span class="st" style="color: #20794D;">"testthat"</span>, <span class="st" style="color: #20794D;">"test-bmi.R"</span>))</span>
<span id="cb9-50">  path</span>
<span id="cb9-51">}</span>
<span id="cb9-52"></span>
<span id="cb9-53"><span class="co" style="color: #5E5E5E;"># Loads the package from source and runs its tests (like devtools::test()).</span></span>
<span id="cb9-54">run_demo_tests <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="cf" style="color: #003B4F;
font-weight: bold;">function</span>(path, <span class="at" style="color: #657422;">reporter =</span> testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">default_reporter</span>()) {</span>
<span id="cb9-55">  testthat<span class="sc" style="color: #5E5E5E;">::</span><span class="fu" style="color: #4758AB;">test_local</span>(path, <span class="at" style="color: #657422;">reporter =</span> reporter, <span class="at" style="color: #657422;">stop_on_failure =</span> <span class="cn" style="color: #8f5902;">FALSE</span>)</span>
<span id="cb9-56">}</span>
<span id="cb9-57"></span>
<span id="cb9-58"><span class="co" style="color: #5E5E5E;"># Run only when called as a script (not when sourced by the tests).</span></span>
<span id="cb9-59"><span class="cf" style="color: #003B4F;
font-weight: bold;">if</span> (<span class="fu" style="color: #4758AB;">sys.nframe</span>() <span class="sc" style="color: #5E5E5E;">==</span> <span class="dv" style="color: #AD0000;">0</span>L) {</span>
<span id="cb9-60">  path <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">make_demo_package</span>()</span>
<span id="cb9-61">  results <span class="ot" style="color: #003B4F;">&lt;-</span> <span class="fu" style="color: #4758AB;">run_demo_tests</span>(path)</span>
<span id="cb9-62">  <span class="fu" style="color: #4758AB;">print</span>(<span class="fu" style="color: #4758AB;">as.data.frame</span>(results)[, <span class="fu" style="color: #4758AB;">c</span>(<span class="st" style="color: #20794D;">"test"</span>, <span class="st" style="color: #20794D;">"nb"</span>, <span class="st" style="color: #20794D;">"failed"</span>, <span class="st" style="color: #20794D;">"error"</span>)])</span>
<span id="cb9-63">}</span></code></pre></div></div>
</div>
</div>
</div>
</section>
<section id="sources" class="level2">
<h2 class="anchored" data-anchor-id="sources">Sources</h2>
<p><strong>Package documentation</strong></p>
<ul>
<li><strong>testthat</strong>: <a href="https://testthat.r-lib.org/">testthat.r-lib.org</a></li>
<li><strong>usethis</strong>: <a href="https://usethis.r-lib.org/">usethis.r-lib.org</a></li>
<li><strong>devtools</strong>: <a href="https://devtools.r-lib.org/">devtools.r-lib.org</a></li>
<li><strong>waldo</strong> (drives 3rd-edition diffs): <a href="https://waldo.r-lib.org/">waldo.r-lib.org</a></li>
</ul>
<p><strong>Web-repo comparison</strong></p>
<ul>
<li><strong>Vitest</strong>: <a href="https://vitest.dev/">vitest.dev</a></li>
<li><strong>Jest</strong>: <a href="https://jestjs.io/">jestjs.io</a></li>
</ul>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Updates
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<ul>
<li><strong>2026-09-26:</strong> Removed the end-of-post checklist. Marked package-dependent and environment-dependent blocks as .norun.</li>
<li><strong>2026-09-27:</strong> Added a Sources section.</li>
<li><strong>2026-09-27:</strong> Added a Companion code section with the full script.</li>
</ul>
</div>
</div>
</div>



<div class="site-related">
<div class="site-series-nav">
<p><a href="https://insightsurge-dev.web.app/series/testing.html" class="site-series-nav__series">Testing series · part 1 of 7</a></p>
<div class="site-card-grid site-series-nav__links">
<div class="site-card-cell">
<a href="https://insightsurge-dev.web.app/posts/test-design-fixtures-mocking/index.html" class="is-card site-related-card site-series-nav__next"><span class="is-card__eyebrow">Next · part 2</span><span class="site-related-card__title">Test design: fixtures, temporary state and mocking</span></a>
</div>
</div>
</div>
<section id="also-in" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="also-in">Also in</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/series/package-dev.html" class="site-link-row" title="Turn scripts into a package, then document, check, share and evolve it. The later parts cover object systems and compiled code."><span class="is-card__eyebrow site-link-row__label">Series · 4 parts</span><span class="site-link-row__title">R package development series</span></a></li>
</ul>
</div>
</section>
<section id="keep-reading" class="level2 unnumbered unlisted no-anchor">
<h2 class="unnumbered unlisted no-anchor" data-anchor-id="keep-reading">Keep reading</h2>
<div class="site-link-list">
<ul>
<li><a href="https://insightsurge-dev.web.app/posts/hooks-formatting-linting/index.html" class="site-link-row" title="Catch syntax errors, stale documentation, and styling differences automatically before code reaches review."><span class="is-card__eyebrow site-link-row__label">Read first</span><span class="site-link-row__title">Pre-commit hooks, formatting &amp; linting</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/coverage-and-test-evidence/index.html" class="site-link-row" title="Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices."><span class="is-card__eyebrow site-link-row__label">Related</span><span class="site-link-row__title">Coverage and tests as evidence</span></a></li>
<li><a href="https://insightsurge-dev.web.app/posts/package-dev-loop-r-cmd-check/index.html" class="site-link-row" title="Use the R package development loop, read R CMD check diagnostics, and fix four recurring problems."><span class="is-card__eyebrow site-link-row__label">Read next</span><span class="site-link-row__title">The package development loop and R CMD check</span></a></li>
</ul>
</div>
</section>
</div>

</section>

 ]]></description>
  <category>R</category>
  <category>R packages</category>
  <category>Best practices</category>
  <guid>https://insightsurge-dev.web.app/posts/testthat-essentials/</guid>
  <pubDate>Fri, 25 Sep 2026 18:30:00 GMT</pubDate>
</item>
</channel>
</rss>
