"""Build the researched CONCLAVE plan from one content source (standard library only)."""
from pathlib import Path
import html
import re

ROOT = Path(__file__).resolve().parents[1] / '01-Plan'
STEM = ROOT / 'Operating-Plan'
SOURCES = [
('S1', 'RSI · Public Test Universe FAQ', 'https://support.robertsspaceindustries.com/hc/en-us/articles/115013195927-Public-Test-Universe-PTU-FAQ', 'Updated 19 Nov 2026. LIVE 4.10.3; PTU 5.0 Wave 3. Testing is separate from LIVE.'),
('S2', 'RSI · Daily Life in the Verse', 'https://support.robertsspaceindustries.com/hc/en-us/articles/16444523494423-Daily-Life-in-the-Verse', 'Updated 27 Jul 2026. Current activity and equipment-crafting guidance.'),
('S3', 'CIG · Alpha 4.6 LIVE release notes', 'https://robertsspaceindustries.com/comm-link/Patch-Notes/20969-Star-Citizen-Alpha-46', 'Official indexed release text confirms engineering gameplay. Direct page extraction was limited.'),
('S4', 'RSI · Loaner Ship Matrix', 'https://support.robertsspaceindustries.com/hc/en-us/articles/360003093114-Loaner-Ship-Matrix', 'Updated 12 Nov 2026. Check actual hull availability; this list also includes loaners for released ships.'),
('S5', 'RSI · Ship Insurance FAQs', 'https://support.robertsspaceindustries.com/hc/en-us/articles/360000093467-Ship-Insurance-FAQs', 'Updated 2 Jun 2026. Alpha coverage, claim costs and separately insured custom loadouts.'),
('S6', 'RSI · Playing with Friends', 'https://support.robertsspaceindustries.com/hc/en-us/articles/360008166874-Playing-with-Friends', 'Updated 24 Jul 2026. Party formation and joining friends; no mass-assembly service guarantee.'),
('S7', 'CIG · Public Roadmap', 'https://robertsspaceindustries.com/roadmap/board/1-Star-CitizenRoadmap', 'Updated 21 Nov 2026. Release labels and scheduling caveats verified through official indexed text.'),
('S8', 'RSI · Organizations', 'https://support.robertsspaceindustries.com/hc/en-us/articles/115010675447-Organizations', 'Updated 10 Feb 2026. Organization identity, membership, ranks and management roles.'),
('S9', 'CIG · Multiple Organization Membership', 'https://robertsspaceindustries.com/en/comm-link/transmission/13856-Multiple-Organization-Membership-Launched', 'Historical official explanation of public, redacted and hidden memberships; public rosters have visibility limits.'),
('S10', 'Discord · Permissions specification', 'https://docs.discord.com/developers/topics/permissions', 'Owner/Administrator access, channel overwrite calculation and bot role hierarchy.'),
('S11', 'Discord · OAuth2 documentation', 'https://docs.discord.com/developers/topics/oauth2', 'Discord identity authorization; it does not establish RSI account control or organization entitlement.'),
('S12', 'Discord · Forum Channels FAQ', 'https://support.discord.com/hc/en-us/articles/6208479917079-Forum-Channels-FAQ', 'Community-server requirement, tagged posts and access settings.'),
('S13', 'Discord · Scheduled Events', 'https://support.discord.com/hc/en-us/articles/4409494125719-Scheduled-Events', 'Event creation/management permissions and visibility for restricted voice events.'),
('S14', 'ISC · Published charter', 'https://robertsspaceindustries.com/en/orgs/INGLSPCECO', 'Independent organizations, equal votes and practical assistance without compulsory war participation.'),
('S15', 'IAC · Published charter', 'https://robertsspaceindustries.com/en/orgs/THEIAC', 'Trial events with different partners, defined briefs, fulfilled roster commitments and debriefs.'),
('S16', 'S.P.A.C.E · Published treaty', 'https://robertsspaceindustries.com/en/orgs/SPACEALL', 'No mandatory organization tax; joint-purpose contributions and feasible assistance.'),
('S17', 'Medrunner · FAQ', 'https://www.medrunner.space/faq', 'Volunteer specialist organization: no required ship pledge, optional participation and in-game contributions.'),
]
pages = []
def page(title, subtitle, *blocks): pages.append((title, subtitle, list(blocks)))
def p(s): return ('p', s)
def h(s): return ('h', s)
def note(s): return ('note', s)
def ul(*items): return ('ul', list(items))
def table(headers, rows): return ('table', (headers, rows))

page('CONCLAVE', 'STAR CITIZEN ALLIANCE OPERATING PLAN', *[('cover', None),
 ('note', '**Independent organizations. Practical trade. Defensive support.**'),
 ('p',
  'Launch a small Star Citizen alliance around useful trade relationships and a bounded quick reaction force (QRF). Help '
  'resource-focused groups find dependable counterparties, move goods and request defensive help. Events and wider '
  'specialist activity grow from what members choose to contribute.'),
 ('table',
  (['Launch model', 'Operating promise'],
   [['Start with 3; pilot cap of 5',
     'Including UNN. Full, Trial and retained Dormant orgs count; no more than two simultaneous trials.'],
    ['Trade first; staffed QRF second',
     'Negotiated deals and explicitly accepted defensive calls. No guaranteed discounts, coverage or response time.'],
    ['One vote per independent full org',
     'Equal voice for trade-only members. No founder veto or compulsory combat service.'],
    ['Scoped trust and simple tools',
     'A separate Discord, staged intake and private task access. Build automation only when useful.']])),
 ('p',
  '**Research baseline: 22 November 2026 · Revision 4.** Trade-and-QRF operating proposal for founder adoption. Target new '
  'resource/trade partners with fewer than 50 listed RSI members, then verify activity and willingness to trade. No '
  'committed partners, staffed service or deployed system is implied.'),
 ('p',
  'Founded with The Unnamed (UNN.). CONCLAVE retains its approved council emblem, five SIG identities and distinct '
  'red/white/black brand. Existing filenames remain compatible; future 1.0 capabilities are not launch dependencies.')])

page('Make the trade relationship useful', '01 / TRADE BENEFITS & TRANSACTIONS', *[('p',
  'The initial benefit is a small, reliable network of resource suppliers, buyers, haulers and escorts. Mining, salvage, '
  'hauling and equipment fabrication provide practical cooperation opportunities in the documented game baseline. [S2] '
  'Value comes from fulfilled agreements and repeat counterparties.'),
 ('table',
  (['Offer', 'Honest limit'],
   [['Contact and demand directory', 'Named org contacts and dated offers; no complete rosters or stockpiles.'],
    ['Resource and supply matching',
     'Members negotiate specifications, availability, price and quantity per deal. No guaranteed buyer or buyback.'],
    ['Combined orders and haul coordination',
     'Pool demand only when parties agree. Discounts and spare capacity are opportunities, not entitlements.'],
    ['Escort and QRF requests',
     'Available crews assess the job or call. Membership does not insure cargo or guarantee recovery.']])),
 ('h', 'A deal has six explicit steps'),
 ('ul',
  ['**List:** share item/specification, approximate quantity, broad area, availability and contact on the sanitized trade '
   'board. Separate stock on hand from forecast supply.',
   '**Agree privately:** counterparties record exact pickup/delivery, quantity, quality, aUEC price, ownership, deadlines, '
   'payment stages and cancellation terms.',
   '**Limit exposure:** set a numeric maximum acceptable loss before a trial deal. Use modest batches and agreed handoffs; '
   'never share account access or hand over a common treasury.',
   '**Plan transport:** identify who carries cargo risk and arranges escort. Precise routes, manifests, cargo values and '
   'movement times stay with the people doing the job.',
   '**Complete:** both parties confirm delivery and payment; record the outcome. Settled trades count as alliance '
   'participation without an event requirement.',
   '**Resolve:** keep necessary receipts; agree a remedy or use the dispute process. The alliance mediates rather than '
   'guaranteeing every private contract.']),
 ('note',
  'No mandatory tax, guaranteed margin, blanket preferred price, unlimited stockpile or automatic reimbursement. Any '
  'approved QRF expenses or support cap are agreed separately. Voluntary joint-purpose funding has a published alliance '
  'precedent. [S16]')])

page('The alliance charter', '02 / PURPOSE, AUTONOMY & CONDUCT', *[('h', 'A trade and defensive-assistance pact'),
 ('p',
  'CONCLAVE initially coordinates resource trading, logistics, escorts and feasible QRF. Optional events and training '
  'support these relationships. [S14] Member organizations keep their recruitment, internal ranks, home Discords, treasury '
  'and property. The council governs shared spaces and agreed activities; it cannot appoint another org’s officers or seize '
  'its assets.'),
 ('h', 'Participation is voluntary; accepted commitments matter'),
 ('p',
  'No individual event or combat quota applies. A full org may contribute through trade/logistics only and keep its equal '
  'vote. Accepted deliveries, event slots and QRF shifts must be fulfilled or the coordinator warned promptly. An operation '
  'leader commands participating crews for that event only. A council vote cannot conscript another org’s pilots, ships or '
  'funds.'),
 ('h', 'Recommended playstyle boundary'),
 ('p',
  'Use a defensive, commercially cooperative alliance posture. Joint PvE, escorts, rescue, consensual training and '
  'explicitly briefed contested-area PvP are in scope. Publish legal/crime-stat consequences before RSVP. Alliance-branded '
  'attacks on neutral haulers, ransom operations and unsolicited piracy are outside the launch charter. Any later change '
  'requires a charter vote and fresh participant consent.'),
 ('ul',
  ['Member orgs may run independent activities within the shared conduct rules, but must not portray them as CONCLAVE '
   'operations or use alliance resources without agreement.',
   'A private feud does not automatically become an alliance war. Respond to a current threat where feasible; diplomacy '
   'reviews escalation separately.',
   'No intentional allied attacks, theft or sabotage outside a clearly agreed exercise. Confirm targets through the '
   'operation roster and comms; an external “friendly” label is not a guaranteed in-game IFF system.',
   'Stop and clarify friendly-fire incidents. Restitution follows evidence and agreed responsibility, not an automatic '
   'unlimited debt.',
   'No exploits, targeted harassment, pad-ramming abuse, stream-sniping, doxxing or discriminatory abuse. Report game '
   'violations through the appropriate official channels.']),
 ('note',
  'Mutual aid means feasible assistance, not guaranteed recovery. Publish QRF windows with a dispatcher, available crew, '
  'area and end time. Record request, acceptance, launch and arrival separately. Outside staffed windows, requests are best '
  'effort. Party tools do not guarantee co-location or response time. [S6]')])

page('Small groups, controlled growth', '03 / TARGETING & PILOT CAP', *[('p',
  'Seek active resource and trade groups that can name what they supply, what they need and when they play. Prioritize '
  '**1–49 listed RSI members** for new partners. A dated public count is a discovery filter, not proof of active strength. '
  'Verify activity and leadership directly; growth past 49 after joining prompts a fit review, not automatic expulsion.'),
 ('h', 'A five-org cap for the first 90 days'),
 ('p',
  'Start with three founding orgs including UNN. Allow at most five retained org relationships, counting Full, Trial and '
  'Dormant, with no more than two simultaneous trials. Suspend intake when full. One-off outside counterparties receive no '
  'standing alliance access. Raising the cap requires the charter vote and evidence that intake, trade administration and '
  'QRF staffing can support growth.'),
 ('table',
  (['Relationship', 'What it means'],
   [['Counterparty / guest', 'Only the agreed deal or event. No vote, shared directory or general alliance access.'],
    ['Trial org',
     '30-day limited trial with two low-risk interactions involving different partners. No vote or operational archive.'],
    ['Full org',
     'Recorded approval, delegate/alternate and one vote per independent bloc. Operational access stays task-specific.'],
    ['Dormant / departed',
     'Dormant orgs keep a cap slot pending offboarding. Remove unsupported access; preserve other valid sponsorships.']])),
 ('h', 'Treat AI search lists as leads'),
 ('p',
  'Record SID, primary source URL, date checked, public count, recent activity evidence, resource specialty, time window '
  'and leadership contact. Confirm trade interest directly before calling a group willing or vetted. Never infer activity '
  'from headcount, a polished profile or an AI summary. This revision has not verified or contacted actual target orgs.'),
 ('h', 'A practical opening offer'),
 ('p',
  '“We are building a small resource-trading and mutual-assistance network. Keep your org and choose your involvement. '
  'Start with a modest trade or delivery, then try another partner. Defensive help depends on the crews actually '
  'available.”'),
 ('note',
  'No minimum pledge value or combat-attendance requirement. Under-50 targeting applies to new prospect selection; founder '
  'status brings no extra vote or blanket trust.')])

page('Vetting with a recorded decision', '04 / SCREEN → TRIAL → APPROVAL', *[('table',
  (['Gate', 'Evidence and decision owner'],
   [['1 · Screen',
     'Intake checks SID, dated size/activity evidence, resource focus, contact and fit. Mark unsupported claims unknown.'],
    ['2 · Fit conversation',
     'Confirm realistic trades, time windows, conduct, material conflicts, 18+ self-attestation and scoped-access '
     'expectations.'],
    ['3 · Authorize trial',
     'A sponsor nominates; two existing-org representatives from different orgs approve, at least one outside the sponsor. '
     'Check the cap; record risk limit, permissions, conditions and review date.'],
    ['4 · Observe 30 days',
     'Complete two modest interactions with different partners: trades, deliveries, logistics, escort or a drill. Combat is '
     'unnecessary. Record outcomes and counterpart feedback.'],
    ['5 · Assess',
     'Two reviewers from different existing orgs, at least one outside the sponsor, assess reliability, conduct and '
     'commitments. The same representatives may serve; the sponsor cannot decide alone.'],
    ['6 · Decide',
     'Seven-day full-admission ballot: ceil(2N ÷ 3) YES from eligible full blocs. Applicant has no vote. Record approve, '
     'defer with conditions, or decline. No automatic promotion.']])),
 ('h', 'Bounded outcomes'),
 ('p',
  'Permit one trial extension of up to 30 days, with written conditions and an end date. If unresolved, close the trial and '
  'remove trial-derived access. A later application may restart when evidence is available. A declined group may remain an '
  'ordinary counterparty where appropriate, without alliance privileges.'),
 ('h', 'Founding approval and evidence limits'),
 ('p',
  'Before a council exists, the three founders complete equivalent checks and pairwise trade/support trials, then '
  'unanimously ratify the charter. Do not label an unknown group a founder to bypass review. Vetting reduces uncertainty; '
  'it cannot guarantee that infiltration or misconduct will never occur.'),
 ('p',
  'Judge relevant evidence and observed behavior. Hidden RSI affiliations are supported privacy choices, not proof of '
  'hostility. Request material conflicts, never credentials or intrusive personal records. Players remain free to transfer; '
  'prohibit targeted solicitation using alliance access, not voluntary choices. [S8] [S9]')])

page('Small council, clear decisions', '04 / GOVERNANCE & DISPUTES', *[('p',
  'Each full independent org appoints one delegate and one alternate; together they cast one vote. Common-controlled orgs '
  'share one voting bloc until independent leadership and a distinct active crew are demonstrated. Count overlapping '
  'players once in coalition attendance. Freeze the eligible voter list when each ballot opens.'),
 ('table',
  (['Decision', 'Required YES votes from all N eligible blocs', 'Window'],
   [['Ordinary policy, appointments, spending within an approved budget', 'floor(N ÷ 2) + 1', '72 hours'],
    ['Full admissions, cap/charter changes, external commitments, spending outside budget', 'ceil(2N ÷ 3)', '7 days'],
    ['Dissolution / disposal of shared resources',
     'ceil(2N ÷ 3), plus owner consent for property not owned by the alliance',
     '14 days']])),
 ('p',
  '**For 3 / 4 / 5 voting blocs:** ordinary decisions need **2 / 3 / 3** YES; major decisions need **2 / 3 / 4**. '
  'Abstention and non-response are not assent. Ties and under-threshold motions fail. The chair has no extra vote or veto. '
  'A coalition campaign still needs explicit resource commitments from each participating org.'),
 ('h', 'Accountable coordinators, not another high command'),
 ('p',
  'Elect a meeting coordinator for three months, normally rotating between orgs. Appoint operations, membership/diplomacy, '
  'logistics and technical custodians for 90-day reviewable terms. Functions can be combined initially; financial approval '
  'and receipt of payment cannot be combined for the same transaction. UNN experience is relevant, but UNN ranks do not '
  'automatically confer alliance authority.'),
 ('h', 'Decision record and fast action'),
 ('p',
  'Log the motion, proposer, affected resources, eligible blocs, deadline, votes and result. Publish non-sensitive minutes. '
  'Event leaders may adapt a mission, defend participants and retreat immediately within its agreed scope and budget. '
  'Emergencies do not grant power to rewrite the charter.'),
 ('note',
  'Example: with five eligible orgs, a charter motion needs four YES votes. Three YES, one NO and one abstention fails. The '
  'chair cannot convert it into a pass. If fewer than three active independent orgs remain, continue approved events and '
  'necessary maintenance, but pause new major commitments until partners expressly re-ratify a smaller pact.')])

page('Fair process when things go wrong', '05 / DISPUTES, INACTIVE SEATS & EXIT', *[('h', 'Contain harm without indefinite suspension'),
 ('p',
  'A moderator may restrict access immediately. An uninvolved reviewer must examine the evidence within 72 hours; an '
  'unreviewed restriction expires then. Each approved extension lasts at most 14 days and needs fresh written reasons and '
  'independent review. All restrictions expire on their stated date; restarting one cannot be used to evade review.'),
 ('h', 'Separate evidence review from political disagreement'),
 ('p',
  'Use 2–3 reviewers who did not investigate or take part in the incident. Share the allegation and relevant evidence with '
  'the respondent, protecting unrelated personal data; allow a response. Mere disagreement about a policy is not a '
  'conflict. A directly involved delegate steps aside for an uninvolved alternate where possible.'),
 ('h', 'Permanent removal and appeal'),
 ('p',
  'For expulsion, give seven days to respond. Exclude the accused org and any unresolved personal accusation, control '
  'relationship or direct personal financial interest; witnessing misconduct alone is not a conflict. Use an uninvolved '
  'alternate where possible. Freeze electorate R at opening. Removal needs **max(2, ceil(2R ÷ 3))** YES votes. With fewer '
  'than two eligible blocs, seek voluntary separation or mediation whose authority all parties accept.'),
 ('p',
  'Allow one appeal within 14 days for new evidence or procedural error. Acknowledge within three days; two different '
  'unconflicted reviewers report within 14 days. Any permanent remedy goes to a seven-day ballot of the original eligible '
  'blocs, using the same threshold. New members cannot decide the appeal. If reviewers are unavailable, seek agreed '
  'external mediation. Interim restrictions remain time-limited.'),
 ('h', 'Inactive seats: notice before change'),
 ('p',
  'After **60 days without a meaningful contribution**, give delegate and alternate 14 days’ notice, even if they still '
  'chat. Trades, deliveries, logistics, agreed staffed QRF windows, drills and events qualify. A QRF shift counts without '
  'an emergency; unsolicited pings do not impose attendance. A reply alone does not reset activity. A dated return/leave '
  'agreement may pause review for up to 30 days.'),
 ('p',
  'Otherwise an ordinary vote marks the org dormant: suspend future voting and revoke unsupported access, preserving other '
  'valid sponsorships. Dormant orgs still count toward the cap. At **120 days since the last contribution**, review '
  'inactivity offboarding with seven days’ notice and the removal/appeal safeguards. Record inactivity, not misconduct.'),
 ('p',
  'Restore for future ballots after two partner representatives verify a renewed contribution and leadership contact. Once '
  'offboarded, re-entry needs a free slot and admission review. Never alter an open ballot’s electorate.'),
 ('h', 'A clean exit'),
 ('p',
  'An org may leave immediately; seven days’ notice is requested where practical for handovers. Revoke relevant access, '
  'return owned property and reconcile accepted contracts. Offer a mutual 30-day non-aggression agreement; it is not '
  'automatically binding on a departed party. No retaliatory harassment. Voluntary transfers by individual pilots never '
  'require leader permission.')])

page('QRF with a clear boundary', '06 / REQUEST, ASSESS & RESPOND', *[('p',
  'QRF means feasible defensive assistance: escort reinforcement, extraction, rescue or disengagement support. It is not a '
  'standing war commitment. Trade-only full members can request help without joining combat. Request eligibility gives no '
  'access to dispatch, other routes or responder readiness. Trial calls receive case assessment without wider permissions.'),
 ('h', 'Publish only coverage that is staffed'),
 ('p',
  'Name a dispatcher and response lead, actual UTC start/end, service area and risk limits. Confirm suitable hulls, crew, '
  'supplies and access before opening the window; close it if staffing falls short. Outside coverage, requests are best '
  'effort. No 24/7 promise, guaranteed 15-minute arrival, cargo recovery or mandatory fight.'),
 ('table',
  (['Step', 'Required action'],
   [['Request privately',
     'Contact the named dispatcher: caller identity, location, region/party access, threat, number at risk and requested '
     'help. Give exact cargo/route details only when needed.'],
    ['Validate',
     'Confirm caller/sponsor and situation. Assess hostile bait, private disputes, crew capability, legal/crime-stat risk '
     'and evacuation options.'],
    ['Accept or decline',
     'The response lead accepts a bounded task with named crews and abort conditions, or explains limits and suggests an '
     'alternative. A request is not a dispatch order.'],
    ['Deploy',
     'Use an expiring private call room for named responders and the caller as needed. Check access, IFF, staging and '
     'recovery. Wider escalation needs fresh consent.'],
    ['Close',
     'Record request/accept/launch/arrival or decline times, outcome, costs and a lesson. Revoke task access. Include '
     'declined and aborted calls in aggregate reporting.']])),
 ('h', 'Drill first, then one repeatable window'),
 ('p',
  'Rehearse intake, identity checks, muster, escort/extraction and a failed-join fallback before advertising routine cover. '
  'Train the actual engineering and other crew roles the selected hull requires. A pledged fleet list is not confirmed '
  'operators. [S3] [S4]'),
 ('note',
  'Party tools support joining friends, not a guaranteed assembly time. Keep a smaller fallback; the lead may decline or '
  'abort unsafe or unworkable calls. No automatic retaliation, coalition war or open-ended pursuit. [S6]')])

page('Five identities, useful jobs', '06 / SPECIALIST CORPS & APPROVED BRAND', *[('sigs', None),
 ('table',
  (['SIG', 'Launch role and useful measure'],
   [['Black Ops · The Veiled Raven',
     'Briefed interdiction, boarding and precision missions within charter ROE. Measure rehearsed teams and completed '
     'objectives, not secrecy or kill totals.'],
    ['Capital Armada · The Dreadnought',
     'Captains, engineers, gunners and escorts. Track fully crewed, supplied sorties and recovery drills.'],
    ['Medevac Angels · The Guardian Seraph',
     'Triage, extraction, security and transport. Track accepted rescues, outcomes and reasons for declining unsafe tasks.'],
    ['Recon Ghosts · The Night Watch',
     'Route scouting, observation and time-stamped reports. No assumed “cloaking” mechanic; report confidence and expiry.'],
    ['Pioneer Corps · The Forgehand',
     'Mining, salvage, refining, hauling and equipment fabrication. Track fulfilled requests and actual margins. '
     'Construction activates only after capability verification.']])),
 ('h', 'Choose involvement; earn task clearance'),
 ('p',
  '**Trade/logistics:** supply, buy, haul or coordinate deliveries without event attendance. **Events:** opt into '
  'individual sessions. **QRF response:** volunteer for a screened, practiced job and accepted shift. Choices may overlap; '
  'they are not ranks or voting weights. Prioritize Pioneer logistics and QRF rescue/recon/escort skills. A standing SIG '
  'needs a host/deputy, playbook and two completed contributions in 30 days. Badges grant no task access; each deal, event '
  'or call gets named, expiring permissions.'),
 ('h', 'Use the approved art consistently'),
 ('p',
  'CONCLAVE uses **#D71932 red, #FFFFFF white and #000000 black**, Rajdhani lettering and the clean council emblem. The '
  'three figures express shared purpose, not founder rank or a fixed org count. Use supplied shield lettering without '
  'stretching. Text-free avatars work better at small sizes.'),
 ('p',
  'Masters: **../04-Brand/Primary**. Unit SVGs, transparent PNGs, patches, banners and avatars: **../04-Brand/SIGs**. Keep '
  'UNN’s Squiddy Blue identity separate; all partner marks receive balanced attribution. Never overwrite the Unnamed Brand '
  'Folder masters.')])

page('Fund the operation, not promises', '07 / LOGISTICS, PAYOUTS & LOSS SUPPORT', *[('h', 'Keep ownership clear'),
 ('p',
  'Ships, cargo and currency remain with their owners unless a specific transfer is recorded. A shared ledger describes '
  'custody; it does not create an in-game alliance bank or automatic asset rights. Avoid a common stockpile until a '
  'custodian, access rules and recovery plan are agreed. Never require real-money dues or pooled pledge purchases.'),
 ('h', 'Agree the economics before launch'),
 ('p',
  'The brief specifies cargo owner, authorized expenses, the payout formula, payment timing and who carries uninsured '
  'losses. Pay by agreed work/roles or equal crew shares, not org size or pledge value. Log gross proceeds, permitted costs '
  'and net distribution; disclose transactions with an officer’s own org.'),
 ('note',
  'Example only: 600,000 aUEC realized revenue − 120,000 approved costs = 480,000 distributable. With eight agreed equal '
  'shares, pay 60,000 each. Do not promise forecast commodity prices or returns.'),
 ('h', 'Operation Support Fund: voluntary and capped'),
 ('p',
  'Start with pay-as-you-go events. Create a reserve only after contributors agree its purpose, custody and spending cap. '
  'Two people from different orgs approve a withdrawal; neither approves a payment to themselves. Publish a monthly balance '
  'and transaction summary. This is an operating rule, not a claim of native two-signature transfer enforcement.'),
 ('ul',
  ['Coverage applies only to a named approved operation and its published cap: agreed consumables, claim/expedite fees, '
   'unrecovered equipment or cargo.',
   'Use game insurance and recovery first. Alpha hull coverage and custom-loadout rules make automatic full hull-value '
   'reimbursement inappropriate. Confirm the current insured loadout before deployment. [S5]',
   'Submit a short cost record within seven days. The reviewer checks authorization, actual loss, insurance recovery and '
   'remaining budget. Approve, partially approve or explain a refusal within seven days where staffing permits.',
   'Reserve the operation allocation before departure. Cap each claim at eligible net loss or the published per-pilot cap, '
   'whichever is lower. If total eligible claims within seven days exceed that reserve, pay them proportionally. Disclose '
   'this rule in the brief; no first-claim priority, double recovery or retrospective coverage.',
   'Private missions, speculative cargo, rule-breaking and real-money pledge value are outside coverage. Game wipes or bugs '
   'trigger reconciliation and a funding review, not an automatic unlimited reimbursement obligation.']),
 ('h', 'Publish what is actually available'),
 ('p',
  'Maintain a small offers-and-requests board: quantity, location, deadline, owner, price or contribution terms and status. '
  'Store accessible inventory, not everyone’s entire hangar. Recheck after major patches and retire stale offers.')])

page('A Discord people can navigate', '08 / 12 PERMANENT CHANNELS AT LAUNCH', *[('p',
  'Use a neutral alliance server. Enable Community for forums; keep public Discovery off at launch. Scheduled Events supply '
  'the calendar. Give approved hosts Create Events rather than general administration. [S12] [S13]'),
 ('table',
  (['Channel / room', 'Use and audience'],
   [['#start-here', 'Public charter, joining route and help. Verification details go privately to staff.'],
    ['#announcements', 'Read-only alliance updates and event links for verified participants.'],
    ['#lounge', 'Full-member social conversation and casual grouping.'],
    ['#operations · forum',
     'Sanitized optional event invitations for full members. No exact staging, manifests or live dispatch.'],
    ['#trade-board · forum',
     'Member/trial supply and demand: broad area, item, availability and contact. Move deal details private.'],
    ['#guides-and-debriefs · forum', 'Sanitized learning and minutes for members/trials. No sensitive operational history.'],
    ['#delegates · private', 'Council discussion and recorded ballots; delegate and alternate access.'],
    ['#staff-and-verification · private', 'Narrowly appointed intake and moderation staff; access-change records.'],
    ['Social · voice', 'Informal full-member grouping.'],
    ['Briefing · voice', 'General member briefings; sensitive tasks use private rooms.'],
    ['Team Alpha · voice', 'Mission crew room.'],
    ['Team Bravo · voice', 'Second mission crew room.']])),
 ('h', 'Only add space for a real task'),
 ('p',
  'Keep **12 permanent channels**. Trials see start-here, announcements, trade-board and sanitized guides only. '
  'Guests/counterparties see only their named deal or event. Add private temporary rooms for trades, QRF, events or cases; '
  'remove access at the recorded end. Ordinary threads are not automatically private.'),
 ('p',
  'Post actual staffed QRF windows and a dispatcher contact in announcements. Intake is private; only named participants '
  'see call details. Keep Conclave servers/data separate from org home systems. Org/SIG/ping badges grant neither trust nor '
  'task access.'),
 ('note',
  'Review channel use monthly. A permanent specialist channel needs an active host and recurring discussion. A new category '
  'is not evidence that a unit exists.')])

page('Trust with honest boundaries', '09 / IDENTITY, ACCESS & TECHNICAL CUSTODY', *[('h', 'Three checks, kept separate'),
 ('table',
  (['Record', 'How it works'],
   [['Identity',
     'Discord user ID plus RSI handle. A short-lived profile code can prove account control; staff can check it manually. '
     'This is a proposed workflow, not official RSI SSO.'],
    ['Membership',
     'A verified org delegate attests current membership; public RSI visibility corroborates where available. Record '
     'sponsor, approver and review date.'],
    ['Authorization',
     'Guest/trial/member access is separate from appointments and sensitive-event permissions. Grant only the needed task '
     'access with an expiry.']])),
 ('p',
  'RSI permits hidden/redacted memberships, so a missing public listing is not proof of departure or wrongdoing. No '
  'supported public RSI OAuth or authoritative membership API was established by this review. Discord OAuth proves Discord '
  'identity only. Never request RSI passwords, cookies or MFA codes. [S9] [S11]'),
 ('h', 'Failures must not cause a mass purge'),
 ('p',
  'Confirmed departure or sponsor withdrawal promptly revokes access derived from that sponsorship; preserve eligibility '
  'through another verified partner or approved guest event. Source errors mark verification **unknown**, preserve the last '
  'check and alert staff. Allow seven days for individual review, never an automatic mass kick. Review delegate '
  'attestations monthly during the pilot. Restricted event access expires independently.'),
 ('h', 'Privileges that actually match the platform'),
 ('p',
  'The Discord owner and Administrator can access restricted channels; a “zero intel access admin” promise is false. Use '
  'one named owner, MFA, a documented succession agreement and a small number of accountable custodians. Do not share an '
  'owner account. Two-person approval of major changes is a governance control, not an enforced Discord two-key feature. '
  '[S10]'),
 ('p',
  'Bots should avoid Administrator and sit below leadership/restricted roles. Test cumulative role combinations: an allow '
  'on another role can defeat a channel deny. Separate cosmetic org/SIG/ping roles from access and staff appointments. '
  'Recheck a guest, trial pilot, member, host and departed member after every permission change. [S10]'),
 ('h', 'Data handling'),
 ('p',
  'Collect only IDs, sponsorship, approvals, event roles, consent and necessary transaction records. Let members '
  'inspect/correct their records. Keep necessary contribution dates/approval records for 180 days to support the 120-day '
  'activity review; delete detailed route/call data within 30 days unless an open case needs it. Review case evidence after '
  'closure. Retain deidentified decisions and accounting summaries. Avoid blanket alt surveillance, private-message '
  'scraping and public accusation lists.')])

page('AllianceHub after the workflow', '10 / INFRASTRUCTURE & IMPLEMENTATION ORDER', *[('p',
  'The alliance must function without a custom website. SquidHub is a useful architectural reference and possible source of '
  'reusable components; integration, hosting effort and maintenance capacity are not established by this plan. UNN may '
  'offer stewardship, subject to named maintainers and shared governance.'),
 ('table',
  (['Stage', 'Deliverable and acceptance gate'],
   [['Day one · no custom build',
     'Discord trade board, a restricted sponsorship/approval register, a trade record, QRF availability sheet and expense '
     'log. No automatic dispatch or roster integration.'],
    ['After the first month · small hub',
     'If useful: charter, partner contacts, trade-board links and current service availability. Keep confidential deal/call '
     'details in restricted records.'],
    ['After recurring pain is measured',
     'Automate only a repeated task with a named owner: approvals, expiring access, trade status or QRF records. Record '
     'time spent and expected benefit first.'],
    ['Later · operational software',
     'Add scoped records, permissions, audit history and exports only after a working manual model and tested access rules. '
     'Use Discord sign-in plus separately validated RSI proof.'],
    ['Future systems',
     'No station/timer service until the underlying LIVE mechanic and trustworthy data source are demonstrated. No '
     'speculative sovereignty dependencies in the MVP.']])),
 ('h', 'Technical discovery before code reuse'),
 ('ul',
  ['Confirm SquidHub ownership, license, deployment boundaries, maintainers and operating cost. Keep coalition data '
   'separate from UNN private data and administrative assumptions.',
   'Specify who can see each field, how a sponsor revokes access, how account changes are recovered, and what happens '
   'during upstream or bot outages.',
   'Use scoped credentials, backups, recorded migrations and tested restore/export procedures. Database or host '
   'administrators may still see stored data; document that trust boundary.',
   'Preserve roster and decision export in ordinary CSV/JSON or documents, with sensitive data restricted to its proper '
   'owner. Do not promise every org an export of other orgs’ private records.']),
 ('h', 'Release checks'),
 ('p',
  'Before any automation controls access, demonstrate manual override, safe handling of unknown verification, a '
  'mass-removal stop, revocation, role expiry, auditability and rollback. Test with non-privileged accounts. Bot failure '
  'must not cancel routine events or unlock sensitive channels.')])

page('Prove trade and QRF before growing', '12 / 90-DAY PILOT', *[('table',
  (['Period', 'Deliverable', 'Accountable function'],
   [['Days 1–14',
     'Screen small resource/trade leads; establish three founders through equivalent checks; agree the five-org cap, '
     'responsibilities and first modest trades.',
     'Founding delegates'],
    ['Days 15–30',
     'Complete initial trades, record delivery/payment outcomes, and rehearse a private QRF call. Publish a window only if '
     'its crew is confirmed.',
     'Trade coordinator + response lead'],
    ['Days 31–60',
     'Admit no more than two trials within the cap. Use trades/hauls/support as evidence. Repeat a workable staffed window; '
     'review access and workload.',
     'Intake + counterparts'],
    ['Days 61–90',
     'Review repeat trade, accepted/declined QRF calls, attendance on agreed shifts, disputes and inactivity notices. Pause '
     'intake if administration or coverage strains.',
     'Council'],
    ['After Day 90',
     'Maintain or raise the cap only by charter vote after a capacity review. Add one org or service window at a time.',
     'Council']])),
 ('h', 'What is and is not a commitment'),
 ('ul',
  ['Each org states a realistic contribution: supplies, buying demand, hauling, trade coordination, event hosting or '
   'trained response crew. No org must offer everything.',
   'Trade-only members remain legitimate full members. Optional events complement trade/QRF; there is no alliance-wide '
   'two-events-per-month promise.',
   'A service opens only with a named owner, actual capacity and a stop condition. Never advertise availability because a '
   'badge, ship list or channel exists.',
   'Prospecting may continue at the cap, but keep candidates on a waiting list without trial/member permissions. No '
   'recruitment campaigns or outreach were executed by this plan.']),
 ('note',
  'The pilot succeeds when groups return to trade, commitments are met and the response service accurately represents its '
  'limits—not when the Discord roster is largest.')])

page('Measure useful participation', '13 / TRADE, COVERAGE & INACTIVITY', *[('table',
  (['Metric', 'Pilot measure'],
   [['Completed and repeat trades',
     'Deals settled as agreed; repeat counterparties; late, disputed or cancelled trades. Do not count advertisements as '
     'activity.'],
    ['Trade reliability',
     'Accepted deliveries completed on time; value/volume only with participant consent. Log price or service benefits only '
     'when evidenced.'],
    ['Real QRF coverage',
     'Published versus actually staffed windows; late withdrawal and closures. A staffed shift qualifies even with zero '
     'calls.'],
    ['Call outcomes',
     'Received, accepted, declined, aborted and completed calls. Record mobilization/arrival only for applicable cases; do '
     'not turn averages into a guarantee.'],
    ['Membership health',
     'Meaningful org contributions in 60/120-day windows; trials, dormant seats, cap usage and review dates. No individual '
     'event quotas.'],
    ['Access and workload',
     'Expired grants closed, incidents resolved, organizer hours and a deputy able to run each essential workflow.'],
    ['Budget discipline',
     'Costs agreed before acceptance, no unfunded reimbursement promises, and settled payments recorded.']])),
 ('h', 'Review before making stronger promises'),
 ('p',
  'Establish the first month’s actual baseline. Choose service targets from observed capacity, rather than claiming an '
  'industry benchmark. Review fortnightly during the pilot and at Day 90. A missed target prompts resizing or closing a '
  'service, not punishment for declining an unaccepted request.'),
 ('h', 'Revision 4: the operating emphasis'),
 ('p',
  'Trade benefits and bounded defensive QRF lead the launch. A five-org cap, two-trial limit and staged approval replace '
  'open-ended growth. Meaningful trade/logistics contribution qualifies without combat events. Trials have narrower shared '
  'access; live trade/QRF details remain private. Inactivity now triggers review even if an org still chats.'),
 ('p',
  'Retained: independent orgs, equal full-org votes, voluntary participation, approved council/SIG artwork, fair disputes '
  'and a small Discord. No return to blanket RSI clearances, 24/7 protection, full-hull reimbursement or unverified '
  'sovereignty infrastructure.')])

page('Keep ambition behind a release gate', '12 / FUTURE READINESS & REVISION RECORD', *[('h', 'Five conditions for a new alliance capability'),
 ('ul',
  ['**Released:** an official LIVE source confirms the specific mechanic. A concept sale, demonstration, PTU test or '
   'scheduled team task is insufficient. [S7]',
   '**Repeatable:** two alliance trials demonstrate access, behavior, persistence/recovery and the failure cases on the '
   'current build.',
   '**Staffed:** a named owner and deputy can operate it without constant compulsory attendance.',
   '**Affordable:** costs, custody, upkeep, loss exposure and an exit plan fit an approved budget.',
   '**Accepted:** the council approves shared commitments and participating orgs explicitly opt into resources or campaign '
   'obligations.']),
 ('h', 'Future-capability register'),
 ('table',
  (['Capability', 'Evidence needed before commitment'],
   [['Base building / land claims',
     'LIVE construction and access rules; persistence; ownership/custody; maintenance and recovery costs.'],
    ['Player stations / territorial defense',
     'Actual control mechanics; access and vulnerability rules; practical defense windows and staffing.'],
    ['New capital hull / production chain',
     'Flyable hull or usable mechanic, accessible inventory, trained crew and two operational trials.'],
    ['Automated timers / live roster sync',
     'Supported or technically validated data source, accuracy/freshness measures, failure handling and manual fallback.'],
    ['Additional systems or timezones',
     'Tested routes, staging supplies and enough confirmed people to sustain a published schedule.']])),
 ('h', 'Document authority'),
 ('p',
  'This revision supersedes conflicting operating claims in earlier alliance plans, recruitment pitches and infrastructure '
  'prototypes. The old SQL is not deployable as-is; its clearance, voting and future-timer assumptions need redesign. Use '
  'the revised companion notes for technical discovery. Recheck capability facts after each major patch and review the '
  'charter at Day 90.')])

page('Sources & evidence', '13 / GAME AND MEMBERSHIP BASELINE', *[('p',
  'All sources accessed 22 November 2026. Official CIG/RSI documentation supplies feature and membership facts; Discord '
  'documentation supplies platform constraints. Proposed thresholds, launch size, staffing windows, budgets and review '
  'periods are CONCLAVE recommendations, not source claims.'),
 ('sources',
  [('S1',
    'RSI · Public Test Universe FAQ',
    'https://support.robertsspaceindustries.com/hc/en-us/articles/115013195927-Public-Test-Universe-PTU-FAQ',
    'Updated 19 Nov 2026. LIVE 4.10.3; PTU 5.0 Wave 3. Testing is separate from LIVE.'),
   ('S2',
    'RSI · Daily Life in the Verse',
    'https://support.robertsspaceindustries.com/hc/en-us/articles/16444523494423-Daily-Life-in-the-Verse',
    'Updated 27 Jul 2026. Current activity and equipment-crafting guidance.'),
   ('S3',
    'CIG · Alpha 4.6 LIVE release notes',
    'https://robertsspaceindustries.com/comm-link/Patch-Notes/20969-Star-Citizen-Alpha-46',
    'Official indexed release text confirms engineering gameplay. Direct page extraction was limited.'),
   ('S4',
    'RSI · Loaner Ship Matrix',
    'https://support.robertsspaceindustries.com/hc/en-us/articles/360003093114-Loaner-Ship-Matrix',
    'Updated 12 Nov 2026. Check actual hull availability; this list also includes loaners for released ships.'),
   ('S5',
    'RSI · Ship Insurance FAQs',
    'https://support.robertsspaceindustries.com/hc/en-us/articles/360000093467-Ship-Insurance-FAQs',
    'Updated 2 Jun 2026. Alpha coverage, claim costs and separately insured custom loadouts.'),
   ('S6',
    'RSI · Playing with Friends',
    'https://support.robertsspaceindustries.com/hc/en-us/articles/360008166874-Playing-with-Friends',
    'Updated 24 Jul 2026. Party formation and joining friends; no mass-assembly service guarantee.'),
   ('S7',
    'CIG · Public Roadmap',
    'https://robertsspaceindustries.com/roadmap/board/1-Star-CitizenRoadmap',
    'Updated 21 Nov 2026. Release labels and scheduling caveats verified through official indexed text.'),
   ('S8',
    'RSI · Organizations',
    'https://support.robertsspaceindustries.com/hc/en-us/articles/115010675447-Organizations',
    'Updated 10 Feb 2026. Organization identity, membership, ranks and management roles.'),
   ('S9',
    'CIG · Multiple Organization Membership',
    'https://robertsspaceindustries.com/en/comm-link/transmission/13856-Multiple-Organization-Membership-Launched',
    'Historical official explanation of public, redacted and hidden memberships; public rosters have visibility limits.')]),
 ('note',
  'Evidence limits: no reliable present-LIVE confirmation of base/station sovereignty mechanics or structure vulnerability '
  'timers was established. No numerical shard capacity or guaranteed fleet-assembly time is assumed. “Not verified” does '
  'not mean “proven absent.”')])

page('Sources & research limits', '14 / PLATFORM AND OPERATING PRACTICES', *[('sources',
  [('S10',
    'Discord · Permissions specification',
    'https://docs.discord.com/developers/topics/permissions',
    'Owner/Administrator access, channel overwrite calculation and bot role hierarchy.'),
   ('S11',
    'Discord · OAuth2 documentation',
    'https://docs.discord.com/developers/topics/oauth2',
    'Discord identity authorization; it does not establish RSI account control or organization entitlement.'),
   ('S12',
    'Discord · Forum Channels FAQ',
    'https://support.discord.com/hc/en-us/articles/6208479917079-Forum-Channels-FAQ',
    'Community-server requirement, tagged posts and access settings.'),
   ('S13',
    'Discord · Scheduled Events',
    'https://support.discord.com/hc/en-us/articles/4409494125719-Scheduled-Events',
    'Event creation/management permissions and visibility for restricted voice events.'),
   ('S14',
    'ISC · Published charter',
    'https://robertsspaceindustries.com/en/orgs/INGLSPCECO',
    'Independent organizations, equal votes and practical assistance without compulsory war participation.'),
   ('S15',
    'IAC · Published charter',
    'https://robertsspaceindustries.com/en/orgs/THEIAC',
    'Trial events with different partners, defined briefs, fulfilled roster commitments and debriefs.'),
   ('S16',
    'S.P.A.C.E · Published treaty',
    'https://robertsspaceindustries.com/en/orgs/SPACEALL',
    'No mandatory organization tax; joint-purpose contributions and feasible assistance.'),
   ('S17',
    'Medrunner · FAQ',
    'https://www.medrunner.space/faq',
    'Volunteer specialist organization: no required ship pledge, optional participation and in-game contributions.')]),
 ('h', 'How the recommendations were chosen'),
 ('p',
  'Public charters show how groups describe their rules, not how well those rules perform. RSI alliance rosters may list '
  'delegates rather than constituent pilots. Published headcounts therefore were not used to rank alliances or predict '
  'CONCLAVE turnout.'),
 ('p',
  'The recommendation favors a small trade-and-assistance federation whose commitments depend on confirmed counterparties, '
  'crews and existing tools. It preserves the useful shared identity while reducing the number of promises, access paths '
  'and administrative tasks that must work before anyone can play.'),
 ('p',
  'The current plan does not assert an official RSI authentication API, verified SquidHub integration, live deployment of '
  'AllianceHub, committed partner organizations or a funded treasury. Those require implementation evidence and actual '
  'participant commitments.')])

def inline(s):
    s = html.escape(s)
    s = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', s)
    return re.sub(r'\[(S\d+)\]', lambda m: f'<a class="cite" href="#{m[1]}">[{m[1]}]</a>', s)

def block_html(b):
    kind, value = b
    if kind in ('p', 'h', 'note'):
        tag = {'p':'p', 'h':'h2', 'note':'aside'}[kind]
        return f'<{tag}>{inline(value)}</{tag}>'
    if kind == 'ul': return '<ul>'+''.join('<li>'+inline(v)+'</li>' for v in value)+'</ul>'
    if kind == 'table':
        heads, rows = value
        widths = ([43, 39, 18] if heads[0]=='Decision' else [19, 60, 21]) if len(heads)==3 else [34,66]
        return '<table><colgroup>'+''.join(f'<col style="width:{w}%">' for w in widths)+'</colgroup><thead><tr>'+''.join('<th>'+inline(v)+'</th>' for v in heads)+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+inline(v)+'</td>' for v in row)+'</tr>' for row in rows)+'</tbody></table>'
    if kind == 'cover': return '<img class="hero" src="../04-Brand/Primary/conclave-primary.svg" alt="Approved Conclave council emblem">'
    if kind == 'sigs':
        slugs=['black-ops','capital-armada','medevac-angels','recon-ghosts','pioneer-corps']
        return '<div class="sig-row">'+''.join(f'<img src="../04-Brand/SIGs/{s}/patch.svg" alt="{s.replace("-", " ")} patch">' for s in slugs)+'</div>'
    if kind == 'sources':
        return '<div class="sources">'+''.join(f'<div class="source" id="{key}"><strong>{key} · <a href="{url}">{html.escape(title)}</a></strong><p>{html.escape(desc)}</p></div>' for key,title,url,desc in value)+'</div>'
    raise ValueError(kind)

def block_md(b):
    kind, value = b
    if kind=='p': return value
    if kind=='h': return '### '+value
    if kind=='note': return '> '+value
    if kind=='ul': return '\n'.join('- '+v for v in value)
    if kind=='table':
        heads,rows=value
        return '| '+' | '.join(heads)+' |\n| '+' | '.join(['---']*len(heads))+' |\n'+'\n'.join('| '+' | '.join(row)+' |' for row in rows)
    if kind=='cover': return '![Approved CONCLAVE council emblem](../04-Brand/Primary/conclave-primary.png)'
    if kind=='sigs': return '[Browse the approved SIG artwork](../04-Brand/SIGs/index.html)'
    if kind=='sources': return '\n\n'.join(f'[{key}]: {url} "{title}"\n\n**{key} — [{title}]({url}).** {desc}' for key,title,url,desc in value)

CSS = '''
@font-face{font-family:Rajdhani;src:url('../04-Brand/Primary/fonts/Rajdhani-Regular.ttf');font-weight:400}
@font-face{font-family:Rajdhani;src:url('../04-Brand/Primary/fonts/Rajdhani-Medium.ttf');font-weight:500}
@font-face{font-family:Rajdhani;src:url('../04-Brand/Primary/fonts/Rajdhani-Bold.ttf');font-weight:700}
@page{size:letter portrait;margin:0}
*{box-sizing:border-box;-webkit-print-color-adjust:exact;print-color-adjust:exact}
body{margin:0;background:#171719;color:#fff;font-family:Rajdhani,Arial,sans-serif;font-size:15.5px;font-weight:500;line-height:1.3}
.page{position:relative;width:816px;height:1056px;padding:34px 43px 30px;background:#000;break-after:page;display:flex;flex-direction:column;overflow:hidden;border-top:7px solid #D71932}
.page:last-child{break-after:auto}.content{flex:1;min-height:0}
.run-header{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #414145;padding-bottom:9px;margin-bottom:21px;color:#b6b6bb;font-size:12px;font-weight:700;letter-spacing:.08em}
.run-header img{width:22px;height:22px;margin-right:8px;vertical-align:middle}.run-header b{color:#fff}
.kicker{color:#ed445a;font-size:12px;letter-spacing:.1em;font-weight:700;margin-bottom:8px}
h1{font-size:32px;line-height:1.05;margin:0 0 18px;font-weight:700;letter-spacing:.015em;text-transform:uppercase}
h2{font-size:18px;line-height:1.15;margin:15px 0 7px;font-weight:700;color:#fff}
p{margin:0 0 10px}strong{font-weight:700}ul{padding-left:19px;margin:8px 0 13px}li{padding-left:3px;margin:0 0 7px}
table{width:100%;border-collapse:collapse;margin:12px 0 15px;table-layout:fixed;font-size:15px;line-height:1.25}
th{text-align:left;background:#D71932;font-size:13px;font-weight:700;padding:8px 10px;text-transform:uppercase;letter-spacing:.03em}
td{padding:7px 10px;border-bottom:1px solid #333338;vertical-align:top}tbody tr:nth-child(2n){background:#111114}td:first-child{font-weight:700}
aside{border-left:4px solid #D71932;background:#131315;padding:10px 13px;margin:13px 0;font-size:15px;line-height:1.3}
a{color:inherit;text-decoration:underline;text-decoration-color:#737378;text-underline-offset:2px}.cite{color:#ff6c7d;font-size:12px;white-space:nowrap;text-decoration:none}
.run-footer{border-top:1px solid #414145;padding-top:9px;margin-top:15px;display:flex;justify-content:space-between;font-size:11px;font-weight:700;color:#a7a7ae;letter-spacing:.055em;flex-shrink:0}
.run-footer b{color:#ed445a}.hero{display:block;height:232px;width:260px;object-fit:contain;margin:2px auto 16px}.cover h1{font-size:64px;letter-spacing:.06em;margin-bottom:4px}.cover .kicker{font-size:16px;letter-spacing:.13em}.cover .run-header{margin-bottom:24px}
.sig-row{display:flex;gap:12px;margin:0 0 16px}.sig-row img{width:calc((100% - 48px)/5);height:140px;object-fit:contain}
.sources{margin-top:7px}.source{padding:9px 0;border-bottom:1px solid #333338;font-size:16px;line-height:1.23}.source strong{color:#fff}.source p{font-size:14px;color:#bfbfc5;margin:4px 0 0}
@media screen{.page{margin:20px auto;box-shadow:0 1px 10px #0008}}
@media print{body{background:#000}.page{margin:0;box-shadow:none}}
'''
N = len(pages)
sections=[]
md=['# CONCLAVE [CNCL] — Star Citizen Alliance Operating Plan', '**Revision 4 · researched 22 November 2026 · recommended operating baseline**', 'The existing filename is retained for link compatibility. This is the current plan; earlier sovereign-bloc drafts are superseded.']
for i,(title,subtitle,blocks) in enumerate(pages,1):
    if i>1: subtitle=re.sub(r'^\d+ /', f'{i-1:02} /', subtitle)
    cls='page cover' if i==1 else 'page'
    sections.append(f'<section class="{cls}"><div class="content"><header class="run-header"><span><img src="../04-Brand/Primary/conclave-primary.svg" alt=""><b>CONCLAVE</b> / INDEPENDENT ORGS. SHARED PURPOSE.</span><span>RESEARCH REVIEW · 22 NOV 2026</span></header><div class="kicker">{subtitle}</div><h1>{title}</h1>'+''.join(block_html(b) for b in blocks)+f'</div><footer class="run-footer"><span>CONCLAVE [CNCL] · FOUNDED WITH THE UNNAMED</span><b>PAGE {i:02} / {N}</b></footer></section>')
    md.append('## '+title+'\n\n'+'\n\n'.join(block_md(b) for b in blocks))
STEM.with_suffix('.html').write_text('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>CONCLAVE — Star Citizen Alliance Operating Plan</title><style>'+CSS+'</style></head><body>'+''.join(sections)+'</body></html>',encoding='utf-8')
STEM.with_suffix('.md').write_text('\n\n'.join(md)+'\n',encoding='utf-8')
print(f'Built {N} pages: {STEM.name}.md / .html')

import json
(ROOT/'CONCLAVE_OPERATING_PLAN_METADATA.json').write_text(json.dumps({'revision':4,'pages':N,'reviewed':'2026-11-22','focus':'Trade and bounded defensive QRF'},indent=2)+'\n',encoding='utf-8')
