exports.id=5185,exports.ids=[5185],exports.modules={9940:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{$3:()=>n,$G:()=>m,XJ:()=>l});var e=c(60105),f=c(81774),g=a([e]);function h(a){return String(a??"").replace(/[&<>"']/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[a])}e=(g.then?(await g)():g)[0];let o=new Set(["passport_number","national_id","ssn","tax_id"]);function i({title:a,kicker:b,bodyHtml:c}){return`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>${h(a)}</title>
<style>
  :root {
    color-scheme: light;
    --bg: #0e0d0c;
    --panel: #f7f4ee;
    --ink: #1a1817;
    --ink-soft: #5f5a55;
    --line: #d9d4cb;
    --accent: #b3261e;
    --pill-bg: #ece6d9;
  }
  body {
    margin: 0;
    background: var(--bg);
    color: var(--ink);
    font: 14px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
    padding: 32px 16px;
  }
  .art {
    max-width: 720px;
    margin: 0 auto;
    background: var(--panel);
    border-radius: 18px;
    box-shadow: 0 24px 60px rgba(0,0,0,0.35);
    padding: 40px 44px 48px;
  }
  .art-kicker {
    text-transform: uppercase;
    letter-spacing: 0.12em;
    font-size: 11px;
    color: var(--ink-soft);
    margin: 0 0 12px;
  }
  .art h1 {
    font-size: 26px;
    margin: 0 0 6px;
    letter-spacing: -0.01em;
  }
  .art h2 {
    font-size: 18px;
    margin: 28px 0 12px;
    border-top: 1px solid var(--line);
    padding-top: 18px;
  }
  .art .muted { color: var(--ink-soft); }
  .art .meta {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 16px;
    color: var(--ink-soft);
    font-size: 12px;
    margin-bottom: 24px;
  }
  .art .meta span { display: inline-flex; gap: 4px; }
  .art .pill {
    display: inline-block;
    padding: 3px 10px;
    background: var(--pill-bg);
    border-radius: 999px;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: var(--ink);
  }
  .art .pill.warn { background: #f1d6a8; }
  .art .pill.bad  { background: #f1c5c0; color: #6e1410; }
  .art .pill.ok   { background: #cfe7c8; color: #1e4a17; }
  .art .field {
    margin: 0 0 14px;
  }
  .art .field-label {
    display: block;
    font-weight: 600;
    color: var(--ink);
    margin-bottom: 2px;
  }
  .art .field-help {
    color: var(--ink-soft);
    font-size: 12px;
    margin: 2px 0 6px;
  }
  .art .field-value {
    color: var(--ink);
    font-size: 14px;
  }
  .art .req::after { content: " *"; color: var(--accent); }
  .art-table {
    width: 100%;
    border-collapse: collapse;
    margin: 6px 0 0;
  }
  .art-table th, .art-table td {
    text-align: left;
    padding: 6px 10px;
    border-bottom: 1px solid var(--line);
    font-size: 13px;
  }
  .art-table th {
    color: var(--ink-soft);
    text-transform: uppercase;
    letter-spacing: 0.06em;
    font-size: 11px;
  }
  .art .note {
    background: #fff;
    border-left: 3px solid var(--accent);
    padding: 10px 14px;
    margin: 18px 0;
    color: var(--ink-soft);
    font-size: 12px;
    border-radius: 4px;
  }
  .art pre {
    background: #181615;
    color: #f1ece1;
    padding: 12px 14px;
    border-radius: 8px;
    overflow-x: auto;
    font-size: 12px;
    line-height: 1.45;
  }
  .art code { font-size: 13px; }
  .art ul { padding-left: 20px; }
  .art .row { display: flex; gap: 24px; flex-wrap: wrap; }
  .art .row > div { flex: 1 1 220px; }
  .art-footer {
    margin-top: 28px;
    color: var(--ink-soft);
    font-size: 11px;
    border-top: 1px solid var(--line);
    padding-top: 14px;
  }
</style>
</head>
<body>
  <article class="art">
    ${b?`<p class="art-kicker">${h(b)}</p>`:""}
    ${c}
  </article>
</body>
</html>`}function j(a){if(null==a)return"";let b=String(a).toLowerCase();return["pass","ok","auto_pass","clear"].includes(b)?`<span class="pill ok">${h(b)}</span>`:["fail","reject","rejected","hit","denied"].includes(b)?`<span class="pill bad">${h(b)}</span>`:["needs_info","manual_review","review","warning"].includes(b)?`<span class="pill warn">${h(b)}</span>`:`<span class="pill">${h(b)}</span>`}function k(a){try{let b=(0,e.Dg)(a);return b?.artifact_id||null}catch{return null}}function l({definition:a,schema:b,caseRow:c,settings:d=null,submit_endpoint:e=null,submit_token:f=null}){if(!a||!c)return null;let g=function({definition:a,schema:b,caseRow:c,settings:d=null,submit_endpoint:e=null,submit_token:f=null}){return function({definition:a,schema:b,caseRow:c,settings:d,submit_endpoint:e,submit_token:f}){let g=Array.isArray(b?.fields)?b.fields:[],i=d?.brand||{},j=i.accent_hex||"#c2452a",k=i.sender_name||"Madarx OS",l=i.logo_url||"",m=i.cover_image_url||"",n=i.cover_copy?.title||b?.title||`${a?.name||"Process"} — Intake`,o=i.cover_copy?.subtitle||b?.description||"Submit the details below to start.",p=g.map(a=>`
    <div class="bi-field">
      <label class="bi-label" for="bi-${h(a.name)}">${h(a.label||a.name)}${a.required?' <span class="bi-req">*</span>':""}</label>
      ${a.help?`<p class="bi-help">${h(a.help)}</p>`:""}
      ${function(a){let b=String(a.name||"").replace(/[^a-zA-Z0-9_-]/g,"");if(!b)return"";let c=a.required?" required":"",d=a.placeholder?` placeholder="${h(a.placeholder)}"`:"";if("select"===a.type&&Array.isArray(a.options)){let d=['<option value="">Pick one…</option>'].concat(a.options.map(a=>`<option value="${h(a)}">${h(a)}</option>`)).join("");return`<select class="bi-input" name="${h(b)}"${c}>${d}</select>`}if("textarea"===a.type)return`<textarea class="bi-input bi-textarea" name="${h(b)}" rows="5"${d}${c}></textarea>`;if("shareholders"===a.type)return`
      <div class="bi-shareholders" data-shareholders data-name="${h(b)}">
        <div class="bi-shareholders-rows"></div>
        <button type="button" class="bi-add-shareholder">+ Add shareholder</button>
        <div class="bi-shareholders-total"><span>Total share</span><strong data-total>0%</strong></div>
        <p class="bi-shareholders-help">Percentages must total exactly 100.</p>
      </div>`;if("number"===a.type)return`<input class="bi-input" type="number" name="${h(b)}" step="any"${d}${c} />`;let e="email"===a.type?"email":"text";return`<input class="bi-input" type="${e}" name="${h(b)}"${d}${c} />`}(a)}
    </div>
  `).join(""),q=g.find(a=>"shareholders"===a.type)?.name||null,r=JSON.stringify(g.map(a=>({name:a.name,type:a.type,required:!!a.required}))),s=JSON.stringify(e||""),t=JSON.stringify(f||null),u=JSON.stringify(c?.id||""),v=JSON.stringify(q),w=`
(function () {
  var FIELDS = ${r};
  var ENDPOINT = ${s};
  var TOKEN = ${t};
  var CASE_ID = ${u};
  var SHAREHOLDER_FIELD = ${v};

  function el(tag, attrs, parent) {
    var n = document.createElement(tag);
    if (attrs) Object.keys(attrs).forEach(function (k) {
      if (k === 'class') n.className = attrs[k];
      else if (k === 'text') n.textContent = attrs[k];
      else n.setAttribute(k, attrs[k]);
    });
    if (parent) parent.appendChild(n);
    return n;
  }

  function addShareholderRow(container) {
    var rows = container.querySelector('.bi-shareholders-rows');
    var row = el('div', { class: 'bi-shareholders-row' });
    el('span', { class: 'bi-shareholders-index', text: String(rows.children.length + 1) }, row);
    el('input', { class: 'bi-input bi-shareholders-name', placeholder: 'Full name' }, row);
    el('input', { class: 'bi-input bi-shareholders-pct', type: 'number', min: '0', max: '100', step: 'any', placeholder: '%' }, row);
    var rm = el('button', { type: 'button', class: 'bi-shareholders-remove', 'aria-label': 'Remove shareholder', text: '\\u00d7' }, row);
    rows.appendChild(row);
    rm.addEventListener('click', function () {
      rows.removeChild(row);
      updateTotal(container);
      reindex(container);
    });
    row.querySelectorAll('input').forEach(function (i) { i.addEventListener('input', function () { updateTotal(container); }); });
  }

  function reindex(container) {
    var rs = container.querySelectorAll('.bi-shareholders-row');
    rs.forEach(function (r, i) { r.querySelector('.bi-shareholders-index').textContent = String(i + 1); });
  }

  function updateTotal(container) {
    var rs = container.querySelectorAll('.bi-shareholders-row');
    var total = 0;
    rs.forEach(function (r) { total += Number(r.querySelector('.bi-shareholders-pct').value || 0); });
    var elTotal = container.querySelector('[data-total]');
    elTotal.textContent = (Math.round(total * 100) / 100) + '%';
    elTotal.classList.toggle('bi-ok', Math.abs(total - 100) < 0.01);
    elTotal.classList.toggle('bi-bad', rs.length > 0 && Math.abs(total - 100) >= 0.01);
  }

  function collectShareholders(container) {
    var rs = container.querySelectorAll('.bi-shareholders-row');
    var out = [];
    rs.forEach(function (r) {
      var name = r.querySelector('.bi-shareholders-name').value.trim();
      var pct = Number(r.querySelector('.bi-shareholders-pct').value || 0);
      if (name || pct) out.push({ name: name, percentage: pct });
    });
    return out;
  }

  function showError(msg) {
    var elError = document.querySelector('[data-bi-error]');
    elError.textContent = msg || '';
    elError.style.display = msg ? 'block' : 'none';
  }

  document.querySelectorAll('[data-shareholders]').forEach(function (c) {
    c.querySelector('.bi-add-shareholder').addEventListener('click', function () { addShareholderRow(c); });
    addShareholderRow(c);
  });

  document.querySelector('[data-bi-form]').addEventListener('submit', function (ev) {
    ev.preventDefault();
    showError('');
    var btn = document.querySelector('[data-bi-submit]');
    btn.disabled = true;
    btn.textContent = 'Submitting…';

    var payload = {};
    FIELDS.forEach(function (f) {
      if (f.type === 'shareholders') return;
      var ctl = document.querySelector('[name="' + f.name + '"]');
      var v = ctl ? ctl.value : '';
      if (f.type === 'number') v = v === '' ? null : Number(v);
      payload[f.name] = v;
    });
    if (SHAREHOLDER_FIELD) {
      var c = document.querySelector('[data-shareholders]');
      payload[SHAREHOLDER_FIELD] = collectShareholders(c);
    }

    var missing = [];
    FIELDS.forEach(function (f) {
      if (!f.required) return;
      var v = payload[f.name];
      if (v == null || v === '' || (Array.isArray(v) && v.length === 0)) missing.push(f.name);
    });
    if (missing.length) {
      showError('Missing required fields: ' + missing.join(', '));
      btn.disabled = false;
      btn.textContent = 'Submit case';
      return;
    }
    if (SHAREHOLDER_FIELD) {
      var sh = payload[SHAREHOLDER_FIELD];
      var sum = sh.reduce(function (a, s) { return a + Number(s.percentage || 0); }, 0);
      if (sh.length > 0 && Math.abs(sum - 100) > 0.01) {
        showError('Shareholder percentages must total 100 (got ' + sum + ').');
        btn.disabled = false;
        btn.textContent = 'Submit case';
        return;
      }
    }

    var body = { payload: payload };
    if (TOKEN) body.token = TOKEN;
    fetch(ENDPOINT + (TOKEN ? '?token=' + encodeURIComponent(TOKEN) : ''), {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    }).then(function (r) {
      return r.json().then(function (j) { return { ok: r.ok, body: j }; });
    }).then(function (res) {
      if (!res.ok) throw new Error(res.body && res.body.error ? res.body.error : 'submit_failed');
      document.querySelector('[data-bi-form]').style.display = 'none';
      document.querySelector('[data-bi-thanks]').style.display = 'block';
      try { if (window.parent && window.parent !== window) window.parent.postMessage({ type: 'madarx_intake_submitted', case_id: CASE_ID }, '*'); } catch (e) {}
    }).catch(function (err) {
      showError(String((err && err.message) || err));
      btn.disabled = false;
      btn.textContent = 'Submit case';
    });
  });
})();
`;return`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>${h(n)}</title>
<style>
  :root { color-scheme: light; --bi-accent: ${h(j)}; --bi-ink: #1a1817; --bi-ink-soft: #5f5a55; --bi-bg: #f7f4ee; --bi-panel: #fff; --bi-line: #e2dccf; }
  *, *::before, *::after { box-sizing: border-box; }
  body { margin: 0; background: var(--bi-bg); color: var(--bi-ink); font: 14.5px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
  .bi-shell { max-width: 760px; margin: 0 auto; padding: 32px 18px 80px; }
  .bi-header { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 18px; border-radius: 14px; background: var(--bi-panel); border: 1px solid var(--bi-line); margin-bottom: 18px; }
  .bi-header-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
  .bi-header img { height: 28px; max-width: 140px; object-fit: contain; }
  .bi-header b { font-weight: 700; font-size: 14px; }
  .bi-header small { color: var(--bi-ink-soft); font-size: 11.5px; letter-spacing: 0.05em; text-transform: uppercase; }
  .bi-cover { border-radius: 16px; background: var(--bi-panel); border: 1px solid var(--bi-line); overflow: hidden; margin-bottom: 18px; }
  .bi-cover-image { width: 100%; aspect-ratio: 3 / 1; background: linear-gradient(135deg, var(--bi-accent) 0%, #2a1310 100%); background-size: cover; background-position: center; }
  .bi-cover-image[data-img] { background-image: var(--bi-cover-img); }
  .bi-cover-body { padding: 22px 24px 24px; }
  .bi-cover-body h1 { margin: 0 0 6px; font-size: 26px; letter-spacing: -0.01em; }
  .bi-cover-body p { margin: 0; color: var(--bi-ink-soft); font-size: 14px; }
  .bi-card { background: var(--bi-panel); border: 1px solid var(--bi-line); border-radius: 16px; padding: 22px 22px 26px; }
  .bi-card h2 { font-size: 17px; margin: 0 0 14px; }
  .bi-field { margin: 0 0 14px; }
  .bi-label { display: block; font-weight: 600; font-size: 13.5px; margin-bottom: 4px; color: var(--bi-ink); }
  .bi-req { color: var(--bi-accent); font-weight: 700; }
  .bi-help { margin: 0 0 6px; color: var(--bi-ink-soft); font-size: 12px; }
  .bi-input { width: 100%; padding: 9px 12px; border: 1px solid var(--bi-line); border-radius: 10px; font: inherit; background: #fff; color: var(--bi-ink); transition: border-color .12s, box-shadow .12s; }
  .bi-input:focus { outline: 0; border-color: var(--bi-accent); box-shadow: 0 0 0 3px rgba(194,69,42,.18); }
  .bi-textarea { resize: vertical; min-height: 90px; }
  .bi-shareholders { border: 1px dashed var(--bi-line); border-radius: 10px; padding: 12px 14px; }
  .bi-shareholders-rows { display: flex; flex-direction: column; gap: 8px; margin-bottom: 8px; }
  .bi-shareholders-row { display: grid; grid-template-columns: 24px 1fr 90px 28px; gap: 8px; align-items: center; }
  .bi-shareholders-index { font-size: 11.5px; color: var(--bi-ink-soft); text-align: center; }
  .bi-shareholders-remove { width: 28px; height: 28px; border: 1px solid var(--bi-line); border-radius: 8px; background: #fff; cursor: pointer; font-size: 14px; line-height: 1; color: var(--bi-ink-soft); }
  .bi-shareholders-remove:hover { background: #f5eee2; color: var(--bi-accent); }
  .bi-add-shareholder { border: 0; background: transparent; color: var(--bi-accent); font-weight: 600; cursor: pointer; padding: 4px 0; }
  .bi-shareholders-total { display: flex; justify-content: space-between; padding: 6px 0; border-top: 1px dashed var(--bi-line); margin-top: 6px; font-size: 13px; }
  .bi-shareholders-total .bi-ok { color: #1e4a17; }
  .bi-shareholders-total .bi-bad { color: var(--bi-accent); }
  .bi-shareholders-help { margin: 6px 0 0; color: var(--bi-ink-soft); font-size: 11.5px; }
  .bi-submit-row { margin-top: 22px; display: flex; align-items: center; justify-content: space-between; gap: 16px; }
  .bi-submit { background: var(--bi-ink); color: #fff; border: 0; border-radius: 999px; padding: 11px 22px; font: 600 14px/1 inherit; cursor: pointer; transition: transform .08s, background .12s; }
  .bi-submit:hover { background: var(--bi-accent); }
  .bi-submit:active { transform: scale(.97); }
  .bi-submit:disabled { background: var(--bi-ink-soft); cursor: not-allowed; }
  .bi-error { display: none; background: #fff2ef; border: 1px solid #f0c0b6; color: #6e1410; padding: 10px 12px; border-radius: 10px; font-size: 13px; margin-bottom: 14px; }
  .bi-thanks { display: none; padding: 36px 22px; text-align: center; color: var(--bi-ink); }
  .bi-thanks h2 { font-size: 22px; margin: 0 0 8px; }
  .bi-thanks p { color: var(--bi-ink-soft); margin: 0; }
  .bi-footer { margin-top: 22px; color: var(--bi-ink-soft); font-size: 11.5px; text-align: center; }
</style>
</head>
<body>
  <div class="bi-shell">
    <header class="bi-header">
      <div class="bi-header-left">
        ${l?`<img src="${h(l)}" alt="${h(k)}" />`:`<b>${h(k)}</b>`}
      </div>
      <small>Intake \xb7 ${h(a?.name||a?.slug||"Process")}</small>
    </header>
    <section class="bi-cover">
      <div class="bi-cover-image"${m?` data-img style="--bi-cover-img: url('${h(m)}')"`:""}></div>
      <div class="bi-cover-body">
        <h1>${h(n)}</h1>
        <p>${h(o)}</p>
      </div>
    </section>
    <form class="bi-card" data-bi-form>
      <div class="bi-error" data-bi-error role="alert"></div>
      ${p||"<p>No fields configured.</p>"}
      <div class="bi-submit-row">
        <small style="color: var(--bi-ink-soft);">Case <code>${h(c?.id||"")}</code></small>
        <button type="submit" class="bi-submit" data-bi-submit>Submit case</button>
      </div>
    </form>
    <div class="bi-card bi-thanks" data-bi-thanks>
      <h2>Thank you</h2>
      <p>We've received your submission. You can close this window.</p>
    </div>
    <p class="bi-footer">Powered by ${h(k)} \xb7 case <code>${h(c?.id||"")}</code></p>
  </div>
  <script>${w}</script>
</body>
</html>`}({definition:a,schema:b,caseRow:c,settings:d,submit_endpoint:e,submit_token:f})}({definition:a,schema:b,caseRow:c,settings:d,submit_endpoint:e,submit_token:f}),i=`${a.name||a.slug||"Process"} — intake form — ${c.title||c.id.slice(-8)}`;return k({title:i,kind:"html",content:g,project_id:c.project_id,dedupe_key:`process_intake_form:${c.id}`})}function m({definition:a,schema:b,caseRow:c,intake:d}){if(!a||!c)return null;let e=function({definition:a,schema:b,caseRow:c,intake:d}){let e=(Array.isArray(b?.fields)?b.fields:[]).map(a=>{let b=d?d[a.name]:void 0;return`
        <div class="field">
          <span class="field-label">${h(a.label||a.name)}</span>
          <div class="field-value">${function(a,b){if(null==b||""===b)return'<em class="muted">— not provided —</em>';if(o.has(a?.name))return`<code>${h((0,f.$)(b))}</code>`;if(a?.type==="shareholders"&&Array.isArray(b)){if(0===b.length)return'<em class="muted">— none —</em>';let a=b.map((a,b)=>`
        <tr>
          <td>${b+1}</td>
          <td>${h(a?.name||"")}</td>
          <td>${h(String(a?.percentage??""))}%</td>
        </tr>`).join("");return`
      <table class="art-table">
        <thead><tr><th>#</th><th>Name</th><th>Share</th></tr></thead>
        <tbody>${a}</tbody>
      </table>`}return Array.isArray(b)?`<ul>${b.map(a=>`<li>${h(JSON.stringify(a))}</li>`).join("")}</ul>`:"object"==typeof b?`<pre>${h(JSON.stringify(b,null,2))}</pre>`:a?.type==="textarea"?`<p style="white-space:pre-wrap">${h(b)}</p>`:h(b)}(a,b)}</div>
        </div>`}).join(""),g=new Date().toISOString(),j=`
    <h1>${h(`Intake submitted — ${c?.title||a?.name||""}`)}</h1>
    <div class="meta">
      <span><strong>Process:</strong>&nbsp;${h(a?.name||a?.slug||"")}</span>
      <span><strong>Case:</strong>&nbsp;${h(c?.title||"")}</span>
      <span><strong>Submitted:</strong>&nbsp;${h(g)}</span>
      <span class="pill ok">submitted</span>
    </div>
    <div class="note">
      Sensitive identifiers (passport / national IDs) are <strong>redacted</strong> in this artifact.
      Full values are retained only inside the engine's <code>process_cases.intake_payload_json</code> row
      and are subject to the project's encryption + ACL policy.
    </div>
    <h2>Submitted fields</h2>
    ${e||'<p class="muted">No structured fields in this intake.</p>'}
    <div class="art-footer">
      Case <code>${h(c?.id||"")}</code> \xb7 definition <code>${h(a?.slug||"")}</code>
    </div>
  `;return i({title:`Intake submission — ${c?.title||""}`,kicker:"Intake submission \xb7 receipt",bodyHtml:j})}({definition:a,schema:b,caseRow:c,intake:d}),g=`${a.name||a.slug||"Process"} — intake submission — ${c.title||c.id.slice(-8)}`;return k({title:g,kind:"html",content:e,project_id:c.project_id,dedupe_key:`process_intake_submission:${c.id}`})}function n({caseRow:a,stage:b,output:c,agentSlug:d}){if(!a||!b)return null;let e=function({stage:a,output:b,intake:c,agentSlug:d}){let e;return e="completeness-agent"===d?function({output:a,intake:b}){let c=Array.isArray(a?.missing_fields)?a.missing_fields:[],d=Array.isArray(a?.warnings)?a.warnings:[],e=b?.proposed_company_name||"";return`
    <h1>Completeness analysis${e?` — ${h(e)}`:""}</h1>
    <div class="meta">
      <span><strong>Outcome:</strong></span>${j(a?.outcome)}
      <span><strong>Missing fields:</strong>&nbsp;${c.length}</span>
      <span><strong>Warnings:</strong>&nbsp;${d.length}</span>
    </div>
    <h2>Summary</h2>
    <p>${h(a?.summary||"No summary provided.")}</p>
    ${c.length?`<h2>Missing fields</h2><ul>${c.map(a=>`<li><code>${h(a)}</code></li>`).join("")}</ul>`:""}
    ${d.length?`<h2>Warnings</h2><ul>${d.map(a=>`<li>${h(a)}</li>`).join("")}</ul>`:""}
    <h2>Raw output</h2>
    <pre>${h(JSON.stringify(a,null,2))}</pre>
  `}({output:b,intake:c}):"kyc-risk-verifier"===d?function({output:a,intake:b}){let c="number"==typeof a?.risk_score?a.risk_score:null,d=a?.recommended_action,e=b?.proposed_company_name||"";return`
    <h1>KYC / risk analysis${e?` — ${h(e)}`:""}</h1>
    <div class="meta">
      <span><strong>Risk score:</strong>&nbsp;${null!=c?c.toFixed(2):"—"}</span>
      <span><strong>Recommended action:</strong></span>${j(d)}
      <span><strong>PEP check:</strong></span>${j(a?.pep_check||"clear")}
    </div>
    <div class="note">
      Demo mode — no external KYC services were contacted. Risk score is a deterministic
      function of the intake payload.
    </div>
    <h2>Rationale</h2>
    <p>${h(a?.rationale||"No rationale provided.")}</p>
    ${Array.isArray(a?.flags)&&a.flags.length?`<h2>Flags</h2><ul>${a.flags.map(a=>`<li>${h(a)}</li>`).join("")}</ul>`:""}
    ${Array.isArray(a?.sanctioned_list_hits)&&a.sanctioned_list_hits.length?`<h2>Sanctioned-list hits</h2><ul>${a.sanctioned_list_hits.map(a=>`<li>${h(JSON.stringify(a))}</li>`).join("")}</ul>`:""}
    <h2>Raw output</h2>
    <pre>${h(JSON.stringify(a,null,2))}</pre>
  `}({output:b,intake:c}):function({stage:a,output:b}){return`
    <h1>${h(a?.name||"Agent analysis")}</h1>
    <div class="meta">
      <span><strong>Stage:</strong>&nbsp;${h(a?.slug||"")}</span>
      <span><strong>Outcome:</strong></span>${j(b?.outcome||"pass")}
    </div>
    ${b?.summary?`<h2>Summary</h2><p>${h(b.summary)}</p>`:""}
    <h2>Raw output</h2>
    <pre>${h(JSON.stringify(b,null,2))}</pre>
  `}({stage:a,output:b}),i({title:`${a?.name||"Analysis"} — ${c?.proposed_company_name||""}`,kicker:`${a?.kind?.replace("_"," ")||"agent"} \xb7 ${a?.slug||""}`,bodyHtml:e})}({stage:b,output:c,intake:a.intake_payload||{},agentSlug:d}),f=`${b.name||b.slug} — analysis — ${a.title||a.id.slice(-8)}`;return k({title:f,kind:"html",content:e,project_id:a.project_id,dedupe_key:`process_analysis:${a.id}:${b.slug}:${Date.now()}`})}d()}catch(a){d(a)}})},18748:(a,b,c)=>{"use strict";c.d(b,{Jh:()=>g,Xx:()=>d,Zt:()=>e,hW:()=>f});let d={intake:"neutral",running:"info",awaiting_approval:"warning",complete:"success",rejected:"danger",failed:"danger",cancelled:"neutral"},e={intake:"Intake",running:"Running",awaiting_approval:"Awaiting approval",complete:"Complete",rejected:"Rejected",failed:"Failed",cancelled:"Cancelled"},f=new Set(["complete","rejected","failed","cancelled"]),g=new Set(["pass","fail","skipped","cancelled"])},21530:(a,b,c)=>{var d={"./agent-run.js":[24562,2181],"./human-approval.js":[84752,4752],"./intake-form.js":[306,306],"./package.js":[80455,455],"./policy-dsl-legacy.js":[46355,6355],"./policy-gate.js":[65257,5257]};function e(a){if(!c.o(d,a))return Promise.resolve().then(()=>{var b=Error("Cannot find module '"+a+"'");throw b.code="MODULE_NOT_FOUND",b});var b=d[a],e=b[0];return c.e(b[1]).then(()=>c(e))}e.keys=()=>Object.keys(d),e.id=21530,a.exports=e},25185:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{Cv:()=>i.Cv,Fj:()=>A,NZ:()=>x,eX:()=>t,fx:()=>y,pX:()=>E,qz:()=>s,wG:()=>G,x0:()=>B,zH:()=>D,zK:()=>r});var e=c(34255),f=c(40563),g=c(9001),h=c(8437),i=c(9013),j=c(9940),k=c(95826),l=c(80002),m=c(73899),n=c(18748),o=a([e,f,g,h,i,j,k,l]);function p(a){return a?{...a,intake_payload:(0,m.oi)(a.intake_payload_json,null),context:(0,m.oi)(a.context_json,{})}:null}function q(a){return a?{...a,artifact_ids:(0,m.oi)(a.artifact_ids_json,[]),output:(0,m.oi)(a.output_json,null)}:null}function r(a){return a?p((0,e.getDb)().prepare("SELECT * FROM process_cases WHERE id = ?").get(a)):null}function s({project_id:a,status:b,definition_slug:c,limit:d=50}={}){let f=(0,e.getDb)(),g=[],h=[];return a&&(g.push("project_id = ?"),h.push(a)),b&&(g.push("status = ?"),h.push(b)),c&&(g.push("definition_slug = ?"),h.push(c)),h.push(Math.max(1,Math.min(200,Number(d)||50))),f.prepare(`
    SELECT * FROM process_cases
    ${g.length?`WHERE ${g.join(" AND ")}`:""}
    ORDER BY updated_at DESC
    LIMIT ?
  `).all(...h).map(p)}function t(a){return a?(0,e.getDb)().prepare("SELECT * FROM process_stage_executions WHERE case_id = ? ORDER BY created_at ASC").all(a).map(q):[]}function u(a){return a?q((0,e.getDb)().prepare("SELECT * FROM process_stage_executions WHERE id = ?").get(a)):null}function v({case_id:a,stage_id:b=null,action:c,status:d="success",summary:f,meta:g={},project_id:h=null,user_id:i=null}){let j=(0,e.getDb)(),k=(0,e.newId)("audit"),l=(0,e.nowIso)(),m={case_id:a,stage_id:b,...g};try{j.prepare(`
      INSERT INTO audit_logs (id, at, type, summary, status, meta, project_id, user_id, action_target_id, action_target_type)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'process_case')
    `).run(k,l,c,f,d,JSON.stringify(m),h,i,a)}catch(b){try{console.warn("[process.audit] failed to write audit row:",b?.message||b,{case_id:a,action:c})}catch{}}}function w(a,b){try{(0,g.AC)({type:a,...b}),(0,g.jO)("processes")}catch{}}function x({definition_slug:a,project_id:b,title:c,intake_payload:d=null,created_by_user_id:f=null,created_by_agent_id:g=null}){if(!a)throw Error("startCase: definition_slug is required");if(!b)throw Error("startCase: project_id is required");let h=(0,i.Ao)(a);if(!h)throw Error(`startCase: definition "${a}" not found`);let l=(0,i.Po)(h.id);if(!l)throw Error(`startCase: definition "${a}" has no stages`);let m=(0,e.getDb)(),n=(0,e.newId)("case"),o=(0,e.nowIso)(),p=c&&String(c).trim()||`${h.name} — ${o.slice(0,19).replace("T"," ")}`,q="intake_form"!==l.kind||d?"running":"intake";m.prepare(`
    INSERT INTO process_cases
      (id, definition_id, definition_slug, project_id, title, status,
       current_stage_id, current_stage_slug, intake_payload_json, context_json,
       created_by_user_id, created_by_agent_id, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(n,h.id,h.slug,b,p,q,l.id,l.slug,d?JSON.stringify(d):null,JSON.stringify({}),f,g,o,o);let s=(0,k.mt)({definition_id:h.id,project_id:b}),t=(0,k.wD)({settings:s}),u=s?{...s,brand:t}:{brand:t},x={definition_settings_snapshot:u},A=function({definition:a,firstStage:b,caseRow:c,snapshot:d}){if("intake_form"!==b.kind)return null;try{let e=z(a);return(0,j.XJ)({definition:a,schema:e,caseRow:c,settings:d,submit_endpoint:`/api/processes/${c.id}/stages/${b.slug}/submit`})}catch{return null}}({definition:h,firstStage:l,caseRow:{id:n,title:p,project_id:b},snapshot:u});if(A&&(x.intake_form_artifact_id=A),Object.keys(x).length>0)try{m.prepare(`
        UPDATE process_cases
           SET context_json = ?, updated_at = ?
         WHERE id = ?
      `).run(JSON.stringify(x),(0,e.nowIso)(),n)}catch{}return(v({case_id:n,stage_id:l.id,action:"process.case.created",summary:`Started case "${p}" (${h.slug})`,project_id:b,user_id:f,meta:{definition_slug:h.slug,first_stage_slug:l.slug}}),w("process.case.created",{case_id:n,definition_slug:h.slug,project_id:b}),w("process.stage.entered",{case_id:n,stage_slug:l.slug,kind:l.kind}),d&&"intake_form"===l.kind)?y({case_id:n,payload:d,user_id:f}):("intake_form"!==l.kind&&D({case_id:n,stage:l}),r(n))}function y({case_id:a,payload:b,user_id:c=null}){let d;if(!a)throw Error("submitIntake: case_id is required");if(!b||"object"!=typeof b)throw Error("submitIntake: payload is required");let f=r(a);if(!f)throw Error(`submitIntake: case "${a}" not found`);if(n.hW.has(f.status))throw Error(`submitIntake: case is ${f.status}`);let g=(0,i.XC)(f.current_stage_id);if(!g||"intake_form"!==g.kind)throw Error("submitIntake: current stage is not an intake_form");let h=(0,i.Ao)(f.definition_id),k=z(h),m=function(a,b){let c,d=[];try{c=JSON.stringify(b)}catch{return d.push("payload: not JSON-serializable"),d}if(c&&c.length>262144)return d.push("payload: exceeds 262144 bytes"),d;if(!a||!Array.isArray(a.fields))return d;for(let c of a.fields){let a=b?.[c.name];if(null!=a)if("shareholders"===c.type)if(Array.isArray(a))if(a.length>50)d.push(`${c.name}: exceeds 50 entries`);else{let b=a.reduce((a,b)=>a+Number(b?.percentage||0),0);a.length>0&&Math.abs(b-100)>.01&&d.push(`${c.name}: percentages must sum to 100 (got ${b})`)}else d.push(`${c.name}: must be an array`);else"number"===c.type?"number"!=typeof a&&("string"!=typeof a||Number.isNaN(Number(a)))&&d.push(`${c.name}: must be a number`):"string"==typeof a&&a.length>1e4&&d.push(`${c.name}: exceeds 10000 characters`)}return d}(k,b);if(m.length>0){let a=Error(`submitIntake: intake validation failed — ${m.join("; ")}`);throw a.code="INTAKE_VALIDATION_FAILED",a}let o=(0,e.getDb)(),p=(0,e.nowIso)();o.exec("BEGIN");try{o.prepare(`
      UPDATE process_cases
         SET intake_payload_json = ?, updated_at = ?
       WHERE id = ?
    `).run(JSON.stringify(b),p,a),d=B({case_id:a,stage:g,status:"pass",outcome:"pass",output:{intake_submitted:!0}}),o.exec("COMMIT")}catch(a){try{o.exec("ROLLBACK")}catch{}throw a}try{let c=r(a),f=(0,j.$G)({definition:h,schema:k,caseRow:c,intake:b}),g=[],i=c?.context?.intake_form_artifact_id;i&&g.push(i),f&&g.push(f),g.length>0&&o.prepare(`
        UPDATE process_stage_executions
           SET artifact_ids_json = ?, updated_at = ?
         WHERE id = ?
      `).run(JSON.stringify(g),(0,e.nowIso)(),d)}catch{}try{(0,l.io)({case_id:a,stage_id:g.id})}catch{}w("process.stage.completed",{case_id:a,stage_slug:g.slug,outcome:"pass",execution_id:d});let q=(0,i.GM)(g);return q?E({case_id:a,from_stage_id:g.id,next_stage:q,reason:"intake_submitted",user_id:c}):F({case_id:a,status:"complete",user_id:c})}function z(a){if(!a)return null;if(a.intake_form_schema)return a.intake_form_schema;if(a.intake_form_schema_json)try{return JSON.parse(a.intake_form_schema_json)}catch{}return null}function A({case_id:a,reason:b=null,user_id:c=null}){let d=r(a);if(!d)throw Error(`cancelCase: case "${a}" not found`);if("cancelled"===d.status)return d;if(n.hW.has(d.status))throw Error(`cancelCase: case is ${d.status}`);return F({case_id:a,status:"cancelled",reason:b,user_id:c})}function B({case_id:a,stage:b,status:c="queued",outcome:d=null,output:f=null,heartbeat_task_id:g=null,attempt:h=1,artifact_ids:i=null}){let j=(0,e.getDb)(),k=(0,e.newId)("pse"),l=(0,e.nowIso)(),m="queued"===c?null:l,o=n.Jh.has(c)?l:null,p=Array.isArray(i)&&i.length>0?JSON.stringify(i.filter(Boolean)):null;return j.prepare(`
    INSERT INTO process_stage_executions
      (id, case_id, stage_id, stage_slug, attempt, status, outcome,
       heartbeat_task_id, output_json, artifact_ids_json, started_at, completed_at, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(k,a,b.id,b.slug,h,c,d,g,f?JSON.stringify(f):null,p,m,o,l,l),k}function C(a,b={}){if(!a)throw Error("updateStageExecution: execution_id is required");let c=u(a);if(!c)throw Error(`updateStageExecution: execution "${a}" not found`);if(n.Jh.has(c.status))throw Error(`updateStageExecution: execution is already ${c.status}`);let d=(0,e.nowIso)(),f={status:b.status??c.status,outcome:b.outcome??c.outcome,output_json:void 0!==b.output?b.output?JSON.stringify(b.output):null:c.output_json,artifact_ids_json:b.artifact_ids?JSON.stringify(b.artifact_ids):c.artifact_ids_json,approval_request_id:b.approval_request_id??c.approval_request_id,agent_run_id:b.agent_run_id??c.agent_run_id,error:b.error??c.error},g=n.Jh.has(f.status)?d:c.completed_at,h=c.started_at||("running"===f.status?d:null);return(0,e.getDb)().prepare(`
    UPDATE process_stage_executions
       SET status = ?, outcome = ?, output_json = ?, artifact_ids_json = ?,
           approval_request_id = ?, agent_run_id = ?, error = ?,
           started_at = ?, completed_at = ?, updated_at = ?
     WHERE id = ?
  `).run(f.status,f.outcome,f.output_json,f.artifact_ids_json,f.approval_request_id,f.agent_run_id,f.error,h,g,d,a),u(a)}function D({case_id:a,stage:b,attempt:c=1,priority:d=5}){let g=r(a);if(!g)throw Error(`enqueueStageExecution: case "${a}" not found`);let h=B({case_id:a,stage:b,status:"queued",attempt:c}),i=(0,f.aJ)({type:"process_stage",priority:d,payload:{type:"process_stage",case_id:a,stage_id:b.id,stage_slug:b.slug,execution_id:h}}),j=(0,e.getDb)();return j.prepare(`
    UPDATE heartbeat_tasks SET project_id = ?, updated_at = ? WHERE id = ?
  `).run(g.project_id,(0,e.nowIso)(),i.id),j.prepare(`
    UPDATE process_stage_executions SET heartbeat_task_id = ?, updated_at = ? WHERE id = ?
  `).run(i.id,(0,e.nowIso)(),h),{execution_id:h,heartbeat_task_id:i.id}}function E({case_id:a,from_stage_id:b=null,next_stage:c=null,terminal_status:d=null,reason:f=null,user_id:g=null,append_context:h=null}){if(!a)throw Error("transitionTo: case_id is required");if(!c&&!d)throw Error("transitionTo: either next_stage or terminal_status is required");let i=(0,e.getDb)(),j=(0,e.nowIso)();i.exec("BEGIN");try{let e=i.prepare("SELECT * FROM process_cases WHERE id = ?").get(a);if(!e)throw Error(`transitionTo: case "${a}" not found`);if(n.hW.has(e.status))throw Error(`transitionTo: case is ${e.status}`);if(b&&e.current_stage_id!==b){let a=Error(`transitionTo: conflict — expected current_stage_id ${b}, got ${e.current_stage_id}`);throw a.code="PROCESS_TRANSITION_CONFLICT",a}let f=h?{...(0,m.oi)(e.context_json,{})||{},...h}:(0,m.oi)(e.context_json,{});d?i.prepare(`
        UPDATE process_cases
           SET status = ?, current_stage_id = NULL, current_stage_slug = NULL,
               context_json = ?, completed_at = ?, updated_at = ?
         WHERE id = ?
      `).run(d,JSON.stringify(f),j,j,a):i.prepare(`
        UPDATE process_cases
           SET status = 'running', current_stage_id = ?, current_stage_slug = ?,
               context_json = ?, updated_at = ?
         WHERE id = ?
      `).run(c.id,c.slug,JSON.stringify(f),j,a),i.exec("COMMIT")}catch(a){try{i.exec("ROLLBACK")}catch{}throw a}let k=r(a);return d?(v({case_id:a,action:"process.case.complete",summary:`Case ${k.title} reached terminal status ${d}`+(f?` (${f})`:""),project_id:k.project_id,user_id:g,meta:{terminal_status:d,reason:f}}),w("process.case.complete",{case_id:a,status:d})):(v({case_id:a,stage_id:c.id,action:"process.stage.entered",summary:`Entered stage ${c.slug} (${c.kind})`,project_id:k.project_id,user_id:g,meta:{stage_slug:c.slug,kind:c.kind,reason:f}}),w("process.stage.entered",{case_id:a,stage_slug:c.slug,kind:c.kind}),"intake_form"!==c.kind&&"human_approval"!==c.kind?D({case_id:a,stage:c}):"human_approval"===c.kind&&D({case_id:a,stage:c,priority:10})),k}function F({case_id:a,status:b,reason:c=null,user_id:d=null}){return E({case_id:a,terminal_status:b,reason:c,user_id:d})}async function G({case_id:a,stage_id:b,execution_id:c,heartbeat_task_id:d}){let e=await H({case_id:a,stage_id:b,execution_id:c,heartbeat_task_id:d});return e.envelope?e.envelope:function({case:a,stage:b,execution_id:c,outcome:d}){let e=a.id;if(d?.approval_required)return C(c,{status:"awaiting_approval",approval_request_id:d.approval_required.approval_request_id,output:d.output||null}),{ok:!0,status:"approval_required",approval_request_id:d.approval_required.approval_request_id,reason:d.approval_required.summary||"Awaiting human approval"};let f=d?.kind==="fail"||d?.terminal_status==="rejected"||d?.terminal_status==="failed",g=f?"fail":"pass",h=d?.output||{outcome:g};if(C(c,{status:g,outcome:g,output:d?.output||null,artifact_ids:d?.artifact_ids,agent_run_id:d?.agent_run_id,error:f?d?.error||null:void 0}),w("process.stage.completed",{case_id:e,stage_slug:b.slug,outcome:g,execution_id:c}),f){let a=(0,i.z9)(b);return a?E({case_id:e,from_stage_id:b.id,next_stage:a,reason:"stage_fail_routed",append_context:{[b.slug]:h}}):E({case_id:e,from_stage_id:b.id,terminal_status:d?.terminal_status||"rejected",reason:d?.error||"stage_failed",append_context:{[b.slug]:h}}),{ok:!0,status:"stage_failed"}}let j=(0,i.GM)(b);return j?E({case_id:e,from_stage_id:b.id,next_stage:j,reason:"stage_pass",append_context:{[b.slug]:h}}):E({case_id:e,from_stage_id:b.id,terminal_status:"complete",reason:"final_stage_pass",append_context:{[b.slug]:h}}),{ok:!0,status:"stage_passed"}}({case:e.case,stage:e.stage,execution_id:c,outcome:e.outcome})}async function H({case_id:a,stage_id:b,execution_id:c,heartbeat_task_id:d}){let e=r(a);if(!e)return{envelope:{ok:!1,reason:"case_not_found"}};if(n.hW.has(e.status))return{envelope:{ok:!0,skipped:!0,reason:`case_${e.status}`}};let f=(0,i.XC)(b);if(!f)return{envelope:{ok:!1,reason:"stage_not_found"}};let g=u(c);if(!g)return{envelope:{ok:!1,reason:"execution_not_found"}};if(n.Jh.has(g.status))return{envelope:{ok:!0,skipped:!0,reason:`execution_${g.status}`}};C(c,{status:"running"});let h=await I(f.kind);if("function"!=typeof h)return C(c,{status:"fail",outcome:"fail",error:`no handler for kind ${f.kind}`}),{envelope:{ok:!1,reason:"handler_missing"}};let j=await h({case:e,stage:f,execution:g,heartbeat_task_id:d});return{case:e,stage:f,outcome:j}}[e,f,g,h,i,j,k,l]=o.then?(await o)():o;let J=new Map;async function I(a){if(J.has(a))return J.get(a);let b=(await c(21530)(`./${function(a){switch(a){case"intake_form":return"intake-form";case"agent_run":return"agent-run";case"policy_gate":return"policy-gate";case"human_approval":return"human-approval";case"package":return"package";default:throw Error(`unknown stage kind: ${a}`)}}(a)}.js`)).executeStage;return"function"!=typeof b?null:(J.set(a,b),b)}(0,h.zU)(({approval_request_id:a,decision:b,row:c})=>{c?.action_type==="process.stage.approve"&&function({approval_request_id:a,decision:b}){if(!a)return;let c=(0,e.getDb)(),d=c.prepare(`
    SELECT * FROM process_stage_executions WHERE approval_request_id = ? AND status = 'awaiting_approval'
    ORDER BY created_at DESC LIMIT 1
  `).get(a);if(!d)return;let f=q(d),g=r(f.case_id);if(g&&"denied"===b){let a=(0,i.XC)(f.stage_id);if(C(f.id,{status:"fail",outcome:"fail",error:"approval denied"}),f.heartbeat_task_id)try{c.prepare(`
          UPDATE heartbeat_tasks
             SET status = 'cancelled', completed_at = ?, error = 'approval denied', updated_at = ?
           WHERE id = ? AND status = 'approval_required'
        `).run((0,e.nowIso)(),(0,e.nowIso)(),f.heartbeat_task_id)}catch{}let b=(0,i.z9)(a);b?E({case_id:g.id,from_stage_id:a.id,next_stage:b,reason:"approval_denied"}):E({case_id:g.id,from_stage_id:a.id,terminal_status:"rejected",reason:"approval_denied"})}}({approval_request_id:a,decision:b})}),d()}catch(a){d(a)}})},80002:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{$H:()=>m,Ph:()=>o,QZ:()=>n,XN:()=>q,e4:()=>r,io:()=>p});var e=c(77598),f=c(34255),g=c(87181),h=a([f]);function i(a){return a.toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}function j(a){let b=a.replace(/-/g,"+").replace(/_/g,"/");for(;b.length%4!=0;)b+="=";return Buffer.from(b,"base64")}function k(a){let b=(0,g.K2)();return(0,e.createHmac)("sha256",b).update(a).digest()}function l(a){return(0,e.createHash)("sha256").update(a).digest("hex")}function m({case_id:a,stage_id:b,expires_at_iso:c=null,minted_by_user_id:d=null}){let g;if(!a)throw Error("mintShareToken: case_id required");if(!b)throw Error("mintShareToken: stage_id required");if(c){if(g=Date.parse(c),Number.isNaN(g))throw Error("mintShareToken: invalid expires_at_iso");let a=Date.now()+7776e6;if(g>a)throw Error("mintShareToken: expiry exceeds 90 days")}else g=Date.now()+12096e5;if(g<=Date.now())throw Error("mintShareToken: expiry must be in the future");let h={v:1,c:a,s:b,e:g,n:(0,e.randomBytes)(8).toString("hex")},j=i(Buffer.from(JSON.stringify(h))),m=i(k(j)),n=`${j}.${m}`,o=new Date(g).toISOString();return(0,f.getDb)().prepare(`
    INSERT INTO share_link_consumptions
      (id, case_id, stage_id, token_hash, expires_at, minted_by_user_id, minted_at)
    VALUES (?, ?, ?, ?, ?, ?, ?)
  `).run((0,f.newId)("slc"),a,b,l(n),o,d,(0,f.nowIso)()),{token:n,expires_at:o}}function n(a){let b,c;if("string"!=typeof a)return null;let d=a.indexOf(".");if(d<=0||d===a.length-1)return null;let f=a.slice(0,d),g=a.slice(d+1);try{b=j(g)}catch{return null}let h=k(f);if(b.length!==h.length)return null;try{if(!(0,e.timingSafeEqual)(b,h))return null}catch{return null}try{c=JSON.parse(j(f).toString("utf8"))}catch{return null}return!c||1!==c.v||"string"!=typeof c.c||"string"!=typeof c.s||"number"!=typeof c.e||c.e<=Date.now()?null:c}function o({token:a,consumer_ip:b=null}){let c=n(a);if(!c)throw Error("share_token: invalid_or_expired");let d=l(a),e=(0,f.getDb)();e.prepare("BEGIN").run();let g=!1;try{let a=e.prepare("SELECT * FROM share_link_consumptions WHERE token_hash = ?").get(d);if(!a)throw Error("share_token: unknown");if(a.revoked_at)throw Error("share_token: revoked");if(a.consumed_at)throw Error("share_token: already_consumed");if(a.case_id!==c.c)throw Error("share_token: case_mismatch");if(a.stage_id!==c.s)throw Error("share_token: stage_mismatch");if(Date.parse(a.expires_at)<=Date.now())throw Error("share_token: expired");let h=e.prepare(`
      UPDATE share_link_consumptions
         SET consumed_at = ?, consumer_ip = ?
       WHERE token_hash = ? AND consumed_at IS NULL
    `).run((0,f.nowIso)(),b,d);if(1!==h.changes)throw Error("share_token: race_lost");return e.prepare("COMMIT").run(),g=!0,c}finally{if(!g)try{e.prepare("ROLLBACK").run()}catch{}}}function p({case_id:a,stage_id:b}){if(!a)return 0;let c=[(0,f.nowIso)(),a],d="UPDATE share_link_consumptions SET revoked_at = ? WHERE case_id = ? AND consumed_at IS NULL AND revoked_at IS NULL";return b&&(d+=" AND stage_id = ?",c.push(b)),(0,f.getDb)().prepare(d).run(...c).changes}function q({case_id:a,limit:b=50}={}){return a?(0,f.getDb)().prepare("SELECT id, case_id, stage_id, expires_at, minted_at, consumed_at, revoked_at, minted_by_user_id FROM share_link_consumptions WHERE case_id = ? ORDER BY minted_at DESC LIMIT ?").all(a,b):[]}f=(h.then?(await h)():h)[0];let r=14;d()}catch(a){d(a)}})},81774:(a,b,c)=>{"use strict";function d(a){let b=String(a||"");return b.length<=4?"****":`${b.slice(0,2)}${"*".repeat(Math.max(4,b.length-4))}${b.slice(-2)}`}c.d(b,{$:()=>d})},95826:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{bo:()=>m,mt:()=>l,wD:()=>j});var e=c(34255),f=c(9013),g=c(91648),h=c(73899),i=a([e,f,g]);[e,f,g]=i.then?(await i)():i;let n=Object.freeze({sender_name:null,cover_image_url:null,cover_copy:{title:null,subtitle:null},accent_hex:null,logo_url:null});function j({settings:a=null}={}){let b=(0,g.$F)(),c=a?.brand||{},d=c.accent_hex||(0,h.lp)(b),e=c.logo_url||b.logo_data_url||b.logo_path||null,f=c.sender_name||b.company_name||"Madarx OS";return{accent_hex:d,sender_name:f,logo_url:e,cover_image_url:c.cover_image_url||null,cover_copy:{title:c.cover_copy?.title||null,subtitle:c.cover_copy?.subtitle||null},fonts:Array.isArray(b.fonts)?b.fonts:[],tagline:b.tagline||null,company_name:b.company_name||null,voice:Array.isArray(b.voice)?b.voice:[]}}function k(a,b){if(null==a||""===a)return b;try{return JSON.parse(a)}catch{return b}}function l({definition_id:a,project_id:b}){var c;return a&&b?(c=(0,e.getDb)().prepare("SELECT * FROM process_definition_settings WHERE definition_id = ? AND project_id = ?").get(a,b))?{id:c.id,definition_id:c.definition_id,project_id:c.project_id,default_for_project:1===c.default_for_project,brand:{...n,...k(c.brand_json,{})},template_html:c.template_html||null,template_version:c.template_version||1,agent_overrides:k(c.agent_overrides_json,{}),auto_approve_rules:k(c.auto_approve_rules_json,[]),share_link_enabled:1===c.share_link_enabled,share_link_default_expiry_days:c.share_link_default_expiry_days||14,created_by_user_id:c.created_by_user_id,created_at:c.created_at,updated_at:c.updated_at}:null:null}function m({definition_id:a,project_id:b,default_for_project:c=null,brand:d=null,template_html:f=null,agent_overrides:g=null,auto_approve_rules:h=null,share_link_enabled:i=null,share_link_default_expiry_days:j=null,user_id:k=null}){if(!a)throw Error("upsertSettings: definition_id required");if(!b)throw Error("upsertSettings: project_id required");if(null!==d&&("object"!=typeof d||Array.isArray(d)))throw Error("upsertSettings: brand must be an object");if(null!==g&&("object"!=typeof g||Array.isArray(g)))throw Error("upsertSettings: agent_overrides must be an object");if(null!==h&&!Array.isArray(h))throw Error("upsertSettings: auto_approve_rules must be an array");if(null!==j){let a=Number(j);if(!Number.isInteger(a)||a<1||a>365)throw Error("upsertSettings: share_link_default_expiry_days must be an integer 1..365")}let m=(0,e.getDb)(),o=(0,e.nowIso)(),p=(0,e.getDb)().prepare("SELECT * FROM process_definition_settings WHERE definition_id = ? AND project_id = ?").get(a,b);return p?m.prepare(`
      UPDATE process_definition_settings
         SET default_for_project = COALESCE(?, default_for_project),
             brand_json = COALESCE(?, brand_json),
             template_html = COALESCE(?, template_html),
             template_version = template_version + (CASE WHEN ? IS NOT NULL THEN 1 ELSE 0 END),
             agent_overrides_json = COALESCE(?, agent_overrides_json),
             auto_approve_rules_json = COALESCE(?, auto_approve_rules_json),
             share_link_enabled = COALESCE(?, share_link_enabled),
             share_link_default_expiry_days = COALESCE(?, share_link_default_expiry_days),
             updated_at = ?
       WHERE id = ?
    `).run(null==c?null:+!!c,null==d?null:JSON.stringify({...n,...d}),f,f,null==g?null:JSON.stringify(g),null==h?null:JSON.stringify(h),null==i?null:+!!i,null==j?null:Number(j),o,p.id):m.prepare(`
      INSERT INTO process_definition_settings
        (id, definition_id, project_id, default_for_project, brand_json,
         template_html, template_version, agent_overrides_json,
         auto_approve_rules_json, share_link_enabled, share_link_default_expiry_days,
         created_by_user_id, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run((0,e.newId)("pds"),a,b,+!!c,null==d?null:JSON.stringify({...n,...d}),f,1,null==g?null:JSON.stringify(g),null==h?null:JSON.stringify(h),+!!i,null==j?14:Number(j),k,o,o),l({definition_id:a,project_id:b})}d()}catch(a){d(a)}})}};