Вихідне питання

Як система може прийняти закон або судове рішення, довести повноваження виконавця, перетворити норму на обмежений план дій, змінити фактичний стан і повернути перевірюване підтвердження, зберігши джерело незмінним?

Повна дослідницька основа цієї публічної адаптації доступна на Zenodo: «Конституція коду».

heroголовне зображення

Стаття II перетворює чинне рішення на обмежену дію та повертає доказ виконання

  • artifact: Чинне судове рішення
  • source: Мандат · присяга · повноваження
  • artifact: Обмежений наказ
  • boundary: Межа capability
  • state: Спостережений наслідок
  • artifact: Квитанція виконання
  • state: Розширений remedy
  • judgment executes order
  • authority validates order
  • order requires boundary
  • boundary executes effect
  • effect produces receipt
  • expanded rejects boundary
  • receipt returns judgment
головне зображенняIRON CREED semantic-core · asset.constitution-runtime-06-article-ii.g01 · authorial brief

Карта вимагає руху

Підключення чергової станції до UCA в Death Stranding миттєво змінює карту. На ній з’являються спільна мережа, доступні дані та сліди чужої інфраструктури. Фізичний світ зберігає попередній стан. Дороги досі немає, вантаж залишається на іншому березі, схил продовжує скидати Сема вниз, а чудова державна абревіатура поки що існує переважно в інтерфейсі. Гравець отримує можливість діяти в спільній системі, а потім власними ногами пояснює ландшафту, що рішення вже ухвалено.

Перші п’ять публікацій нашого зворотного складання створили схожу ситуацію. Стаття VII запустила республіку. Стаття VI визначила довірену редакцію. Стаття V навчила систему змінювати нормативне ядро. Стаття IV з’єднала автономні штати. Стаття III прийняла конкретний конфлікт, закрила доказовий record, обрала застосовне право й ухвалила обмежене рішення. На виході виник об’єкт зі статусом judgment-entered, засобом відновлення та адресою article-ii:execute.

Саме рішення ще не змінило світ. Суд установив, що штат, який приймає, може виконати грошове рішення лише з тим ефектом, який воно мало у вихідній юрисдикції. Виконавче відомство досі здатне відкрити маршрут позбавлення волі. Між нормативним і матеріальним станами проходить розрив, у якому живе стаття II.

Виконавча влада отримує небезпечне завдання: вона має вплинути на реальність, зберігши чуже рішення чужим. Вона обирає виконавця, видає наказ, застосовує доступні засоби, фіксує результат і відповідає за відхилення. Виконавець має ініціативу щодо способу дії, однак джерело вже визначило межі цілі, операції та області. Якщо суд заборонив перетворити стягнення грошей на ув’язнення, президентська енергійність не додає до remedy привабливу маленьку камеру з федеральним фінансуванням.

Шоста збірка

Зворотне складання Конституції дійшло до функції execute():

ПублікаціяКонституційна функціяСтан прототипу
VIIbootstrap()Засновує систему після достатньої ратифікації
VIrootOfTrust()Визначає довірену редакцію та порядок верховенства
VupgradeKernel()Змінює нормативне ядро й відокремлює ратифікацію від міграції
IVfederate()Створює автономні вузли та міжюрисдикційні протоколи
IIIresolve()Приймає конкретний спір, формує рішення та remedy
IIexecute()Перетворює чинне джерело на обмежену дію та квитанцію
Ilegislate()Створить загальну норму й завершить модель

Стаття II створює найширший компонент поточного прототипу. Вона засновує одноосібний центр виконавчого повноваження, задає походження президентського мандата, строк, кваліфікації, винагороду та присягу. Вона розподіляє наступництво й тимчасову нездатність, командування, запит письмових висновків, помилування, договори, призначення, тимчасові комісії, відносини з Конгресом, дипломатичний прийом, faithful execution і відкликання повноваження через імпічмент.

У коді з’являються дванадцять основних операцій:

ОпераціяПризначення
constituteExecutive()Пов’язує мандат, кваліфікації, строк, присягу й поточний нормативний root
applyContinuityEvent()Створює нову lineage під час наступництва або тимчасового передання повноважень
appointOfficer()Перевіряє заснування посади, маршрут призначення та окрему комісію
makeRecessAppointment()Створює тимчасову комісію з визначеним строком дії
execute()Компілює судовий remedy у точний виконавчий наказ
confirmExecution()Пов’язує спостережувані наслідки з дозволеними кроками
makeTreaty()Перевіряє президентську дію та поріг двох третин присутніх сенаторів
grantClemency()Обмежує федеральне помилування предметом і винятком імпічменту
commandForces()Атрибутує військовий наказ і класифікує його підставу
requestWrittenOpinion()Адресує питання головному посадовцю відповідного відомства
communicateWithCongress() / receiveDiplomat()Моделює перелічені комунікаційні функції
applyImpeachmentRemoval()Відкликає capability після доведеного двопалатного процесу

Функція execute() залишається центром публікації, а інші операції показують походження виконавця та межі його повноважень. Президент тут є authority holder. Відомства й посадовці є capability-bearing components. Наказ є похідним артефактом. Квитанція є доказом спостережуваного переходу. WARDEN перевіряє цілісність зв’язків і безпечну відмову, зберігаючи за конституційними суб’єктами рішення щодо фактів, необхідності та змісту.

Один виконавчий центр і багато рук

Перше речення статті II наділяє виконавчою владою Президента Сполучених Штатів. Формула створює одноосібний верхній центр, на відміну від двопалатного законодавчого органу й багаторівневої судової системи. Constitution Annotated пов’язує цю структуру з прямо переліченими президентськими повноваженнями, спільними повноваженнями із Сенатом та обов’язком забезпечувати faithful execution через підпорядкованих посадовців.

Програмна модель виражає єдність через один activeAuthority.holderId. Це поле не перетворює Президента на єдиний потік процесу. Федеральна виконавча система охоплює відомства, головних і нижчих посадовців, комісії, делеговані операції, бюджети, процедури та зовнішні підтвердження. Єдність означає атрибуцію верхнього виконавчого повноваження й відповідальності. Практичне виконання залишається розподіленим.

Таке розрізнення захищає модель від двох симетричних дефектів. Повністю автономні відомства поступово втрачають спільний ланцюг відповідальності. Президент, який особисто виконує кожну операцію, перетворює державу на синхронний моноліт з одним виснаженим суперкористувачем. Людська історія охоче додає третю конфігурацію: суперкористувач бадьорий, відомства слухняні, а перевірку повноважень оголошено зайвою розкішшю. Продуктивність зростає до першого масового поховання, після чого метрика зазвичай змінюється.

constituteExecutive() тому створює верхній authority snapshot і реєстр президентських capabilities. Конкретний виконавчий посадовець отримує власну посаду, призначення, комісію та вузький набір операцій. Кожен виклик доводить обидві частини ланцюга: чинний президентський контур і повноваження безпосереднього виконавця.

Мандат передує команді

Вихідна стаття II описувала виборників, спільний бюлетень і механізм обрання Президента та Віцепрезидента. XII поправка замінила спільне голосування окремими голосами за дві посади. XX поправка встановила сучасний початок і завершення строків та додала правила для проблем на момент інавгурації. XXII поправка обмежила повторне обрання. XXV поправка уточнила наступництво й тимчасове передання повноважень. Поточний runtime охоплює вихідний текст разом із цими змінами; запуск за первинним протоколом означав би виконання superseded interface. Повні тексти поправок доступні в Національних архівах США.

Прототип отримує готовий засвідчений об’єкт mandate. Він указує сучасний конституційний маршрут, Президента й Віцепрезидента, а також digest сертифікованого результату. Підрахунок голосів ми поки не моделюємо: відповідний producer перебуває на боці виборників, штатів і Конгресу та буде пов’язаний з останньою публікацією. Виконавчий модуль діє як consumer і відхиляє будь-яке самопризначення.

Наступний поріг перевіряє кваліфікації: засвідчене визначення natural-born citizenship, вік щонайменше тридцять п’ять років, чотирнадцять років проживання, відсутність чинної дискваліфікації та дотримання XXII поправки. Ці поля представляють результати правових і фактичних процедур. JavaScript не отримує повноваження самостійно вирішувати спір щодо громадянства або застосування XIV поправки. Він вимагає походження рішення.

Строк пов’язується із сучасною часовою схемою XX поправки. Винагорода залишається фіксованою протягом строку; інший федеральний або штатний emolument блокує snapshot. Присяга або урочисте підтвердження завершує активацію. Об’єкт може перемогти на виборах та існувати як President-elect, однак виконувати повноваження він починає після початку строку й засвідченої присяги.

flowchart TD
    A["Сертифікований мандат"] --> B["Конституційна придатність"]
    B --> C["Чотирирічний строк"]
    C --> D["Присяга або урочисте підтвердження"]
    D --> E["Активний носій виконавчого повноваження"]
lifecycleактивація виконавчого повноваження

Президентське повноваження виникає з мандата, придатності, строку та присяги

  • artifact: Мандат · XII та XXII
  • decision: Придатність
  • state: Початок строку · XX
  • process: Присяга · стаття II §1
  • state: Президентське повноваження
  • mandate produces eligibility
  • eligibility produces term
  • term produces oath
  • oath produces authority
активація виконавчого повноваженняIRON CREED semantic-core · asset.constitution-runtime-06-article-ii.g02 · authorial brief

Наступництво зберігає identity системи

Смерть, відставка або усунення Президента створюють вакансію самої посади. XXV поправка робить Віцепрезидента Президентом. Нездатність виконувати обов’язки створює інший перехід: Віцепрезидент діє як Acting President, а носій посади зберігається. Різниця впливає на титул, тривалість, спосіб відновлення повноважень і подальшу lineage.

applyContinuityEvent() ніколи не переписує вихідний executive snapshot. Вона створює новий об’єкт із parentExecutiveDigest та continuityEventDigest. Подія смерті, відставки або усунення переводить Віцепрезидента в роль president. Добровільна декларація нездатності переводить його в роль acting-president. Декларація Віцепрезидента й більшості головних посадовців запускає маршрут розділу 4 XXV поправки. Оспорене відновлення потребує двох третин обох палат у встановлений строк для продовження тимчасового передання.

Подвійна вакансія звертається до плану, встановленого законом на підставі вихідної статті II; XX поправка додає окремі правила для моменту початку строку. Код обирає першого придатного учасника й блокує стрибок через ранішого придатного наступника. Ця ділянка підкреслює залежність статті II від статті I: виконавчий runtime використовує зовнішній statutory artifact, походження якого остання публікація ще має побудувати.

stateDiagram-v2
    [*] --> Президент
    Президент --> НовийПрезидент: смерть, відставка або усунення
    Президент --> ВиконувачОбовязків: підтверджена нездатність
    ВиконувачОбовязків --> Президент: відновлення повноважень
    ВиконувачОбовязків --> ВиконувачОбовязків: дві третини обох палат
    НовийПрезидент --> [*]
lineagelineage наступництва

XXV поправка розрізняє наступництво посади та тимчасове виконання повноважень

  • state: Вакансія або нездатність
  • source: XXV поправка
  • artifact: Посада перейшла · digest A
  • artifact: Повноваження тимчасово виконуються · digest B
  • state: Незмінний lineage
  • event requires review
  • review produces office
  • review produces acting
  • office derives lineage
  • acting derives lineage
lineage наступництваIRON CREED semantic-core · asset.constitution-runtime-06-article-ii.g03 · authorial brief

Faithful execution як обов’язок і межа

Take Care Clause вимагає, щоб Президент забезпечував faithful execution законів. Вона створює позитивний обов’язок і водночас обмежує форму виконавчого розсуду. Виконавча влада має перетворити чинну норму на практику, зберігаючи її походження, область і обмеження. Огляд Take Care Clause підкреслює зв’язок цього обов’язку з устроєм виконавчого контролю, правозастосуванням і ставленням Президента до законодавчих приписів.

Слово faithfully не перетворюється на булеве поле, здатне оцінити будь-яке політичне рішення. Реальне виконання охоплює пріоритети, обмежені ресурси, тлумачення, процесуальні гарантії та іноді несумісні обов’язки. Прототип обирає область, де вірність можна перевірити структурно: виконавець приймає вже визначене джерело, не змінює його digest, не розширює target, operation і scope, використовує посадовця з потрібною capability та повертає спостережувану квитанцію.

Для конфліктів між президентською дією та волею Конгресу код використовує інженерну версію рамки Youngstown. За чинного законодавчого дозволу влада перебуває в найсильнішому становищі. Мовчання Конгресу створює область, що потребує окремої конституційної класифікації. Дія всупереч Конгресу потребує доведеного джерела виключного президентського повноваження. Constitution Annotated описує цю тричастинну рамку як спосіб аналізу обсягу президентської влади.

WARDEN перевіряє наявність атрибутованого визначення та відповідність його структурі. Він не встановлює, чи існувала надзвичайна необхідність, чи був удар неминучим і чи належить конкретна дія до виключної президентської області. Ці питання потребують фактів, права й відповідального рішення. Автоматичний тест зберігає скромну гідність: червона лампа корисніша за цифрового генерала, особливо коли цифрового генерала написали ввечері в п’ятницю.

Судове рішення входить до виконавчої межі

Інтеграційний сценарій продовжує один і той самий артефакт із четвертої та п’ятої публікацій. Штат Franklin ухвалив грошове рішення. Штат Hamilton отримав засвідчену копію й спробував замінити стягнення ув’язненням боржника. federate() визнав автентичність і зупинив розширений ефект зі статусом requires-resolution. resolve() розглянув конкретний спір, пов’язав findings із record, застосував статтю IV і федеральний статут, заборонив розширення ефекту й створив injunction.

Remedy містить п’ять виконавчих полів:

ПолеЗначення у сценарії
targetHamilton Enforcement Office
operationlimit-execution-to-enforce-money-judgment
scopejudgment:franklin:42
executableByarticle-ii:marshal-service
reversibleUntilFinaltrue

Стаття II перевіряє integrity усього judgment через той самий canonical digest, збіг нормативного root, стан pending-separate-execution і точний handoff. Stay або remand зупиняє маршрут. Наявність апеляції без stay зберігає виконуваність, однак кожен крок залишається зворотним до остаточності рішення. Посадовець має бути чинним, призначеним і комісованим усередині того самого executive snapshot, мати capability execute-federal-judgment і представляти endpoint, указаний судом.

flowchart TD
    A["Рішення статті III"] --> B{"Цілісність і чинність"}
    B -->|"Зупинено"| C["Очікування нового судового наказу"]
    B -->|"Чинне"| D["Уповноважений виконавець"]
    D --> E["Обмежений план"]
    E --> F["Спостережені наслідки"]
    F --> G["Квитанція до статті III"]
flowповний виконавчий маршрут

Виконавча влада перевіряє рішення, обмежує наказ і повертає суду квитанцію фактичного виконання

  • source: Lineage статті IV
  • artifact: Judgment · sourceDigest
  • process: Перевірка рішення
  • artifact: План виконання
  • artifact: Обмежений наказ
  • boundary: Межа матеріального світу
  • state: Фактичний наслідок
  • artifact: Квитанція суду
  • article-iv produces judgment
  • judgment produces validation
  • validation produces plan
  • plan produces order
  • order produces world
  • world produces effect
  • effect produces receipt
повний виконавчий маршрутIRON CREED semantic-core · asset.constitution-runtime-06-article-ii.g04 · authorial brief

execute() компілює remedy

Функція отримує executive, judgment, officer і plan. Вона порівнює план із remedy за точною рівністю цілі, операції та області. Окремий прапорець забороняє додаткову санкцію. План потребує least-force determination і підтвердженої бюджетної межі. Кожен крок посилається на той самий target і scope. Зворотний remedy допускає лише зворотні кроки.

Результат execution-ordered містить власний digest і три незалежні відбитки джерела: усього judgment, holdings і remedy. Виконавчий наказ є похідним артефактом і зберігає судовий об’єкт незмінним. Така форма допускає локальне планування, зберігаючи можливість довести, що локальна процедура виконала конкретне рішення.

confirmExecution() приймає спостереження окремо. Кожне спостереження вказує дозволений stepId, проходить authentication і повідомляє фактичний ефект. Відсутній або неуспішний крок створює execution-incomplete. Повне виконання створює execution-confirmed і handoff article-iii:execution-receipt. Судовий контур отримує підставу перевірити compliance, а виконавчий контур зберігає відповідальність за власну операцію.

const order = execute({
	executive,
	judgment,
	officer: marshal,
	plan,
});

const receipt = confirmExecution({
	executive,
	order,
	observations,
	confirmedAt: '2026-08-12T10:00:00Z',
});

console.log(receipt.status);
// execution-confirmed

console.log(receipt.handoff);
// article-iii:execution-receipt

Ця модель навмисно розводить три події: правовий дозвіл дії, матеріальну дію та доказ результату. У звичайному застосунку їх часто зливають в один виклик сервісу. У системі з примусом таке злиття приховує найважливішу ділянку відповідальності. Судовий наказ, натискання кнопки й людина за зачиненими дверима належать до одного ланцюга, однак є різними фактами.

Посада існує раніше за посадовця

Appointments Clause відокремлює створення федеральної посади від її заповнення. Головні посадовці проходять маршрут президентської номінації та Senate advice and consent. Нижча посада зберігає цей загальний маршрут, доки Конгрес законом не передасть її призначення Президенту одноосібно, суду або главі відомства. Огляд Appointments Clause пов’язує цей поділ із балансом гілок і відмінністю principal та inferior officers.

appointOfficer() тому починає з об’єкта office. Посада має засвідчене законодавче джерело, класифікацію, відомчу належність, endpoint і capability. Кандидат має окреме засвідчене визначення придатності. Номінація, згода Сенату, акт призначення й комісія є різними артефактами.

Комісія Президента завершує маршрут і робить його спостережуваним. Вона не засновує відсутню посаду, не виправляє непридатного кандидата й не замінює пропущену згоду Сенату. Нижчий посадовець зберігає суб’єкта призначення, визначеного законом. Глава одного відомства не отримує право заповнити посаду іншого відомства через упевнено заповнене поле actorKind.

flowchart TD
    A["Посада, створена законом"] --> B{"Головна чи нижча?"}
    B -->|"Головна"| C["Номінація Президента"]
    C --> D["Порада і згода Сенату"]
    B -->|"Нижча"| E["Призначувач, визначений законом"]
    D --> F["Акт призначення"]
    E --> F
    F --> G["Президентська комісія"]
lineageпоходження посадового повноваження

Посада, кандидат, призначення та комісія утворюють різні ланки повноваження

  • artifact: Посада · digest
  • actor: Кандидат · digest
  • artifact: Номінація · digest
  • human-decision: Згода · digest
  • artifact: Призначення · digest
  • artifact: Комісія · digest
  • state: Capability
  • office produces candidate
  • candidate produces nomination
  • nomination produces consent
  • consent produces appointment
  • appointment produces commission
  • commission produces capability
походження посадового повноваженняIRON CREED semantic-core · asset.constitution-runtime-06-article-ii.g05 · authorial brief

Recess Appointments Clause створює тимчасовий допоміжний маршрут. Комісія спливає наприкінці наступної сесії Сенату. Сучасна доктрина враховує заяву самого Сенату про стан сесії та фактичну здатність вести справи; проміжок довший за три, але коротший за десять днів вважається ймовірно надто коротким. Наш код використовує консервативну межу в десять днів і блокує комісію, коли Сенат вважає себе таким, що перебуває в сесії, і здатен діяти. Це інженерна політика прототипу, заснована на огляді Recess Appointments Clause, а не буквальний додатковий рядок статті II.

Спільне повноваження потребує незалежного підтвердження

Президент укладає договори за порадою і згодою Сенату, коли дві третини присутніх сенаторів підтримують договір. Код обчислює ceil(2 × senatorsPresent / 3) і зберігає фактичну кількість присутніх, голоси та digest запису. Рівно шістдесят голосів із дев’яноста завершують маршрут; п’ятдесят дев’ять залишають договір у стані treaty-not-made. Поле historicVictory: true не впливає на арифметику.

Після підтвердження програма розрізняє treaty making і внутрішнє виконання. Self-executing treaty повертається до статті VI для реєстрації серед чинних джерел. Договір, що потребує implementing legislation, передається до статті I. Це розрізнення запобігає прихованому створенню внутрішньої норми виконавчим компонентом. Огляд treaty-making power і матеріал про self-executing та non-self-executing treaties дають правову основу цьому поділу.

flowchart TD
    A["Текст договору"] --> B["Президентська атрибуція"]
    B --> C{"Дві третини присутніх сенаторів"}
    C -->|"Поріг досягнуто"| D["Договір укладено"]
    C -->|"Поріг не досягнуто"| E["Договір не укладено"]
    D --> F{"Внутрішня дія"}
    F -->|"Самовиконуваний"| G["Реєстр статті VI"]
    F -->|"Потрібен закон"| H["Стаття I"]
topologyshared power

Незалежне підтвердження Сенату завершує спільне повноваження, а внутрішня дія договору визначає наступний маршрут

  • artifact: Текст договору
  • human-decision: ⅔ присутніх сенаторів
  • state: Ратифікація
  • decision: Внутрішня дія?
  • state: Безпосередня дія
  • artifact: Імплементаційний закон
  • artifact: Номінація
  • human-decision: Згода Сенату
  • artifact: Призначення
  • treaty requires senate
  • senate validates ratification
  • ratification requires domestic
  • domestic produces direct
  • domestic requires legislation
  • nomination requires consent
  • consent validates appointment
shared powerIRON CREED semantic-core · asset.constitution-runtime-06-article-ii.g06 · authorial brief

Помилування як обмежений виняток

Стаття II дозволяє Президенту надавати reprieves і pardons за offenses against the United States, крім випадків impeachment. Сучасна практика охоплює кілька форм clemency, тому прототип розрізняє pardon, reprieve та commutation. Усі вони потребують федерального предмета. Правопорушення штату отримує clemency-rejected. Імпічмент отримує окрему підставу відмови. Федеральне помилування також не переписує незалежні цивільно-правові наслідки без окремого повноваження. Constitution Annotated формулює дві явні текстуальні межі: федеральні правопорушення та виняток справ імпічменту.

Самопомилування залишається нерозв’язаним конституційним питанням. Код повертає requires-constitutional-determination і handoff до статті III за наявності належного case or controversy. Він не оголошує таку дію чинною й не створює заборону з власного естетичного почуття. WARDEN може показати відсутність установленої відповіді. Здатність витримати невизначеність є важливою властивістю нормативної системи; упевнена галюцинація особливо неприємна, коли до неї додається державна печатка.

Commander in Chief отримує командування, а не root-доступ

Президент командує армією та флотом, а також ополченням штатів після його призову на дійсну федеральну службу. Стаття I водночас надає Конгресу повноваження оголошувати війну, створювати й утримувати збройні сили, регулювати їхню діяльність, організовувати ополчення та здійснювати асигнування. Виконавчий наказ тому існує всередині спільної архітектури. Конституційний термін Militia тут означає збройне ополчення штатів; пострадянське тлумачення слова «міліція» як назви поліції стосується іншого інституту.

commandForces() вимагає атрибутований наказ, точну силу, операцію та область, перевірку права збройних конфліктів і бюджетну межу. Для ополчення додається стан calledIntoActualService. Потім дія отримує одну з категорій authority: дозвіл Конгресу, обмежену відповідь на засвідчений напад, область мовчання або дію всупереч Конгресу. Мовчання повертає конституційне визначення. Конфлікт блокується без доведеного виключного повноваження Президента.

Функція не визначає наявність нападу й пропорційність відповіді. Ці значення надходять як атрибутовані рішення. Результат прямо повідомляє declarationOfWar: "not-created-by-executive-order". Текст статей I та II і матеріали про Commander in Chief Clause показують, чому коротка формула командування потребує спільного прочитання з повноваженнями Конгресу.

Виконавча влада також говорить, запитує й приймає

Стаття II дає Президенту право вимагати письмові висновки головних посадовців відомств щодо питань їхніх обов’язків. requestWrittenOpinion() перевіряє principal status, відомство та предмет. Результат створює запит і зберігає поле opinion: "not-manufactured-by-request". Сам факт президентського питання ще не створює зручну відповідь експерта.

State of the Union, рекомендації заходів, надзвичайне скликання та обмежена влада визначити час відкладення в разі незгоди палат моделюються через communicateWithCongress(). Повідомлення зберігає власний digest і значення legislation: "not-created-by-recommendation". Рекомендація може запустити законодавчий процес, однак закон з’явиться лише після статті I.

receiveDiplomat() перевіряє дипломатичні credentials і створює запис прийому. Прототип свідомо залишає поза автоматизацією складні питання визнання держав і зовнішньополітичного розсуду. Тут моделюється походження конкретної події, а не вся зовнішня політика Сполучених Штатів в одному об’єкті з прапорцем reasonable: true.

Імпічмент відкликає capability

Розділ 4 статті II встановлює усунення Президента, Віцепрезидента та цивільних посадовців після імпічменту й засудження за державну зраду, хабарництво або інші high Crimes and Misdemeanors. Провадження імпічменту належить статті I: Палата має виключне право impeachment, Сенат проводить trial. Виконавчий модуль приймає засвідчений результат і застосовує наслідок до authority registry.

applyImpeachmentRemoval() вимагає обидві події й точного суб’єкта. Для звичайного посадовця виникає vacancy. Для Президента з’являється handoff до наступництва. pardonAvailable отримує значення false, оскільки виняток імпічменту вже встановлено в Pardon Clause. WARDEN може перевірити повноту вхідного record. Зміст обвинувачення та рішення палат залишаються за їхніми конституційними процедурами. Огляд Impeachment Clause пов’язує усунення з двопалатним процесом і межею помилування.

Виконуваний шар статті II

Нижче наведено повний ESM-модуль шостої збірки. Він імпортує лише digest() зі статті IV і приймає результат статті III через публічний immutable contract. Попередні модулі залишаються незмінними.

import { digest } from './article-iv.mjs';

export const ARTICLE_II = deepFreeze({
	id: 'U.S.Const.art.II',
	rules: {
		vesting:
			'II.1.1: the executive power is vested in one President of the United States for a four-year term',
		electionAndEligibility:
			'II.1: the presidential mandate must arise through the constitutional election process and the officeholder must satisfy the constitutional qualifications',
		succession:
			'II.1: presidential vacancy and inability require a constitutional succession route, including the law Congress may provide for a dual vacancy',
		compensation:
			'II.1.7: presidential compensation may not be increased or diminished during the elected term and no other federal or state emolument may be received',
		oath: 'II.1.8: before executing the office, the President swears or affirms faithful execution and preservation, protection, and defense of the Constitution',
		commanderInChief:
			'II.2.1: the President commands the armed forces and commands state militia only when called into the actual service of the United States',
		writtenOpinions:
			'II.2.1: the President may require written opinions from principal department officers on subjects relating to their duties',
		clemency:
			'II.2.1: the President may grant reprieves and pardons for offenses against the United States, except impeachment',
		treaties:
			'II.2.2: treaties require presidential action and the concurrence of two thirds of Senators present',
		appointments:
			'II.2.2: principal officers follow presidential nomination and Senate advice and consent; Congress may vest appointment of inferior officers in specified actors',
		recessAppointments:
			"II.2.3: a recess commission is temporary and expires at the end of the Senate's next session",
		congressionalCommunication:
			'II.3: the President reports on the state of the Union, recommends measures, and has specified powers concerning extraordinary sessions and adjournment',
		diplomaticReception: 'II.3: the President receives ambassadors and other public ministers',
		takeCare: 'II.3: the President must take care that the laws are faithfully executed',
		commissions: 'II.3: the President commissions officers of the United States',
		impeachmentRemoval:
			'II.4: the President, Vice President, and civil officers are removed upon impeachment and conviction for constitutionally specified misconduct',
	},
	amendments: {
		twelfth:
			'Amendment XII replaces the original joint presidential ballot with distinct votes for President and Vice President',
		twentieth:
			'Amendment XX fixes the modern commencement and termination of presidential terms and supplies inauguration-day continuity rules',
		twentySecond:
			"Amendment XXII limits election to the presidency, including the specified rule for more than two years of another person's term",
		twentyFifth:
			'Amendment XXV distinguishes succession to the presidency from temporary transfer of presidential powers during inability',
	},
	doctrine: {
		youngstown:
			'Youngstown framework: executive authority is strongest with congressional authorization, uncertain in a zone of concurrent silence, and weakest when contrary to Congress absent exclusive constitutional power',
		supervision:
			'The Take Care duty is performed through lawfully appointed subordinate officers whose authority remains attributable and reviewable',
		finalJudgment:
			"A final judicial act cannot be silently revised by the executive branch; execution preserves the judgment's lineage and bounded remedy",
		appointmentClasses:
			'Appointments doctrine distinguishes principal officers from inferior officers and preserves the constitutionally assigned appointing actor',
		treatyEffect:
			'Treaty making and domestic execution are distinct; some treaty obligations require implementing legislation',
		pardonBoundary:
			'Federal clemency reaches offenses against the United States and excludes impeachment; unresolved self-directed clemency requires constitutional adjudication rather than a test-runner assumption',
		senateSession:
			"For recess-appointment analysis, the Senate's own session determination and practical capacity to transact business are constitutionally relevant",
	},
	engineering: {
		mandateNotSelfAsserted:
			'Constitution of Code II.1: executive authority begins from an authenticated mandate and oath, never from a self-declared role field',
		boundedCapabilities:
			'Constitution of Code II.2: every executive operation identifies its source, actor, target, scope, and review route',
		sourcePreservingExecution:
			'Constitution of Code II.3: execute compiles a valid law or judgment into a bounded order without rewriting the source artifact',
		executionReceipt:
			'Constitution of Code II.4: material execution returns an immutable receipt that links every observed effect to the authorized step',
		continuityLineage:
			'Constitution of Code II.5: succession and inability create a new authority snapshot linked to the prior executive state',
		safeSharedPower:
			'Constitution of Code II.6: advice-and-consent operations fail safely when the independent confirmation is absent or below its required threshold',
		wardenBoundary:
			'WARDEN verifies executive invariants but cannot create a mandate, determine disputed necessity, invent Senate consent, or enlarge a judicial remedy',
	},
});

export const PRESIDENTIAL_CAPABILITIES = Object.freeze([
	'execute-federal-law',
	'execute-federal-judgment',
	'supervise-executive-officers',
	'request-written-department-opinion',
	'command-armed-forces',
	'command-federalized-militia',
	'grant-federal-clemency',
	'negotiate-treaty',
	'nominate-principal-officer',
	'appoint-authorized-officer',
	'issue-officer-commission',
	'communicate-with-congress',
	'receive-diplomat',
]);

const APPOINTING_ACTORS = Object.freeze([
	'president-with-senate-consent',
	'president-alone',
	'court-of-law',
	'department-head',
]);

const CLEMENCY_KINDS = Object.freeze(['pardon', 'reprieve', 'commutation']);
const MILITARY_FORCES = Object.freeze(['army', 'navy', 'state-militia']);
const CONGRESSIONAL_MESSAGES = Object.freeze([
	'state-of-union',
	'recommend-measure',
	'convene-extraordinary-session',
	'adjourn-after-house-disagreement',
]);

function deepFreeze(value) {
	if (value && typeof value === 'object' && !Object.isFrozen(value)) {
		Object.freeze(value);

		for (const nested of Object.values(value)) {
			deepFreeze(nested);
		}
	}

	return value;
}

function requireObject(value, label) {
	if (!value || typeof value !== 'object' || Array.isArray(value)) {
		throw new TypeError(`${label} must be an object`);
	}
}

function requireNonEmptyString(value, label) {
	if (typeof value !== 'string' || value.trim() === '') {
		throw new TypeError(`${label} must be a non-empty string`);
	}
}

function requireBoolean(value, label) {
	if (typeof value !== 'boolean') {
		throw new TypeError(`${label} must be a boolean`);
	}
}

function requireArray(value, label) {
	if (!Array.isArray(value)) {
		throw new TypeError(`${label} must be an array`);
	}
}

function requireUniqueStrings(values, label) {
	requireArray(values, label);

	for (const value of values) {
		requireNonEmptyString(value, `${label} item`);
	}

	if (new Set(values).size !== values.length) {
		throw new TypeError(`${label} must contain unique values`);
	}
}

function requireIsoDate(value, label) {
	requireNonEmptyString(value, label);

	if (Number.isNaN(Date.parse(value))) {
		throw new TypeError(`${label} must be an ISO-compatible date`);
	}
}

function assertNormativeRoot(root) {
	requireNonEmptyString(root?.constitutionId, 'normativeRoot.constitutionId');
	requireNonEmptyString(root?.digest, 'normativeRoot.digest');

	if (root.status !== 'in-force') {
		throw new TypeError('normativeRoot must be in force');
	}
}

function snapshotRoot(root) {
	return {
		constitutionId: root.constitutionId,
		digest: root.digest,
		status: root.status,
		parentDigest: root.parentDigest ?? null,
		amendmentDigest: root.amendmentDigest ?? null,
		lineage: [...(root.lineage ?? [root.digest])],
	};
}

function normalizeEligibility(person, label, { applyElectionLimit }) {
	requireObject(person, label);
	requireNonEmptyString(person.id, `${label}.id`);

	if (person.naturalBornCitizenDetermination !== true) {
		throw new TypeError(`${label} lacks a natural-born-citizen determination`);
	}

	if (!Number.isInteger(person.ageAtTermStart) || person.ageAtTermStart < 35) {
		throw new TypeError(`${label} must be at least thirty-five at term start`);
	}

	if (!Number.isInteger(person.yearsResident) || person.yearsResident < 14) {
		throw new TypeError(`${label} must have at least fourteen years of residence`);
	}

	if (person.fourteenthAmendmentEligible !== true) {
		throw new TypeError(
			`${label} lacks an authenticated Fourteenth Amendment eligibility determination`,
		);
	}

	const priorElections = person.priorElectionsToPresidency ?? 0;

	if (!Number.isInteger(priorElections) || priorElections < 0) {
		throw new TypeError(`${label}.priorElectionsToPresidency must be a non-negative integer`);
	}

	if (applyElectionLimit) {
		if (priorElections >= 2) {
			throw new TypeError(`${label} is barred from another election by Amendment XXII`);
		}

		if (person.actedMoreThanTwoYearsOfAnotherTerm === true && priorElections >= 1) {
			throw new TypeError(`${label} is barred from another election by Amendment XXII`);
		}
	}

	return {
		id: person.id,
		name: person.name ?? person.id,
		naturalBornCitizenDetermination: true,
		ageAtTermStart: person.ageAtTermStart,
		yearsResident: person.yearsResident,
		fourteenthAmendmentEligible: true,
		priorElectionsToPresidency: priorElections,
		actedMoreThanTwoYearsOfAnotherTerm: person.actedMoreThanTwoYearsOfAnotherTerm === true,
	};
}

function normalizeMandate(mandate, presidentId, vicePresidentId, rootDigest) {
	requireObject(mandate, 'mandate');
	requireNonEmptyString(mandate.id, 'mandate.id');
	requireNonEmptyString(mandate.method, 'mandate.method');
	requireNonEmptyString(mandate.certificationDigest, 'mandate.certificationDigest');

	if (mandate.authenticated !== true) {
		throw new TypeError('Presidential mandate must be authenticated');
	}

	if (mandate.rootDigest !== rootDigest) {
		throw new TypeError('Presidential mandate belongs to another normative root');
	}

	if (mandate.method !== 'amendment-xii-certified-count') {
		throw new TypeError('Presidential mandate must use the current constitutional election route');
	}

	if (mandate.presidentElectId !== presidentId) {
		throw new TypeError('Mandate names another President-elect');
	}

	if (mandate.vicePresidentElectId !== vicePresidentId) {
		throw new TypeError('Mandate names another Vice-President-elect');
	}

	return {
		id: mandate.id,
		method: mandate.method,
		presidentElectId: mandate.presidentElectId,
		vicePresidentElectId: mandate.vicePresidentElectId,
		certificationDigest: mandate.certificationDigest,
		rootDigest: mandate.rootDigest,
		authenticated: true,
	};
}

function normalizeTerm(term) {
	requireObject(term, 'term');
	requireIsoDate(term.startsAt, 'term.startsAt');
	requireIsoDate(term.endsAt, 'term.endsAt');

	if (Date.parse(term.endsAt) <= Date.parse(term.startsAt)) {
		throw new TypeError('Presidential term must end after it begins');
	}

	if (term.constitutionalDurationYears !== 4) {
		throw new TypeError('Article II presidential term must be four years');
	}

	if (term.twentiethAmendmentScheduleVerified !== true) {
		throw new TypeError('Modern presidential term requires an Amendment XX schedule determination');
	}

	return {
		startsAt: term.startsAt,
		endsAt: term.endsAt,
		constitutionalDurationYears: 4,
		twentiethAmendmentScheduleVerified: true,
	};
}

function normalizeOath(oath, presidentId, termStart) {
	requireObject(oath, 'oath');
	requireIsoDate(oath.takenAt, 'oath.takenAt');

	if (oath.authenticated !== true || oath.officeholderId !== presidentId) {
		throw new TypeError('Presidential oath must be authenticated for the officeholder');
	}

	if (
		oath.swornOrAffirmed !== true ||
		oath.faithfullyExecute !== true ||
		oath.preserveProtectDefend !== true
	) {
		throw new TypeError('Presidential oath lacks the Article II commitments');
	}

	if (Date.parse(oath.takenAt) < Date.parse(termStart)) {
		throw new TypeError('This model activates the executive only after the term begins');
	}

	return {
		officeholderId: oath.officeholderId,
		takenAt: oath.takenAt,
		authenticated: true,
		swornOrAffirmed: true,
		faithfullyExecute: true,
		preserveProtectDefend: true,
	};
}

function normalizeCompensation(compensation) {
	requireObject(compensation, 'compensation');

	if (compensation.fixedDuringTerm !== true) {
		throw new TypeError('Presidential compensation must remain fixed during the term');
	}

	if (compensation.otherFederalOrStateEmolumentAccepted === true) {
		throw new TypeError(
			'President may not accept another federal or state emolument during the term',
		);
	}

	return {
		compensationRecordDigest: compensation.compensationRecordDigest ?? null,
		fixedDuringTerm: true,
		otherFederalOrStateEmolumentAccepted: false,
	};
}

function normalizeSuccessionPlan(plan, rootDigest) {
	requireObject(plan, 'successionPlan');
	requireNonEmptyString(plan.statuteDigest, 'successionPlan.statuteDigest');
	requireArray(plan.entries, 'successionPlan.entries');

	if (plan.establishedByLaw !== true) {
		throw new TypeError('Dual-vacancy succession plan must be established by law');
	}

	if (plan.rootDigest !== rootDigest) {
		throw new TypeError('Succession plan belongs to another normative root');
	}

	const entries = plan.entries.map((entry, index) => {
		requireNonEmptyString(entry.officerId, `successionPlan.entries[${index}].officerId`);
		requireNonEmptyString(entry.officeId, `successionPlan.entries[${index}].officeId`);

		return {
			rank: index + 1,
			officerId: entry.officerId,
			officeId: entry.officeId,
			eligibleToAct: entry.eligibleToAct === true,
		};
	});
	requireUniqueStrings(
		entries.map((entry) => entry.officerId),
		'succession officer ids',
	);

	return {
		establishedByLaw: true,
		statuteDigest: plan.statuteDigest,
		rootDigest: plan.rootDigest,
		entries,
	};
}

function executiveContent(executive) {
	return {
		executiveId: executive.executiveId,
		normativeRoot: executive.normativeRoot,
		federationId: executive.federationId,
		federationTopologyDigest: executive.federationTopologyDigest,
		mandate: executive.mandate,
		president: executive.president,
		vicePresident: executive.vicePresident,
		term: executive.term,
		oath: executive.oath,
		compensation: executive.compensation,
		successionPlan: executive.successionPlan,
		activeAuthority: executive.activeAuthority,
		parentExecutiveDigest: executive.parentExecutiveDigest ?? null,
		continuityEventDigest: executive.continuityEventDigest ?? null,
	};
}

export function constituteExecutive({
	normativeRoot,
	federation,
	mandate,
	president,
	vicePresident,
	term,
	oath,
	compensation,
	successionPlan,
}) {
	assertNormativeRoot(normativeRoot);
	requireObject(federation, 'federation');

	if (federation.normativeRoot?.digest !== normativeRoot.digest) {
		throw new TypeError('Executive and federation must share the same normative root');
	}

	const normalizedPresident = normalizeEligibility(president, 'president', {
		applyElectionLimit: true,
	});
	const normalizedVicePresident = normalizeEligibility(vicePresident, 'vicePresident', {
		applyElectionLimit: false,
	});
	const normalizedMandate = normalizeMandate(
		mandate,
		normalizedPresident.id,
		normalizedVicePresident.id,
		normativeRoot.digest,
	);
	const normalizedTerm = normalizeTerm(term);
	const normalizedOath = normalizeOath(oath, normalizedPresident.id, normalizedTerm.startsAt);
	const normalizedCompensation = normalizeCompensation(compensation);
	const normalizedSuccessionPlan = normalizeSuccessionPlan(successionPlan, normativeRoot.digest);
	const seed = {
		rootDigest: normativeRoot.digest,
		federationId: federation.federationId,
		mandateDigest: digest(normalizedMandate),
		term: normalizedTerm,
	};
	const content = {
		executiveId: `executive:${digest(seed).slice(7, 23)}`,
		normativeRoot: snapshotRoot(normativeRoot),
		federationId: federation.federationId,
		federationTopologyDigest: federation.topologyDigest,
		mandate: normalizedMandate,
		president: normalizedPresident,
		vicePresident: normalizedVicePresident,
		term: normalizedTerm,
		oath: normalizedOath,
		compensation: normalizedCompensation,
		successionPlan: normalizedSuccessionPlan,
		activeAuthority: {
			holderId: normalizedPresident.id,
			role: 'president',
			mode: 'president',
			authoritySince: normalizedOath.takenAt,
			authorityBasis: 'authenticated-mandate-and-oath',
		},
		parentExecutiveDigest: null,
		continuityEventDigest: null,
	};

	return deepFreeze({
		status: 'executive-constituted',
		...content,
		executiveDigest: digest(content),
		capabilities: [...PRESIDENTIAL_CAPABILITIES],
		trace: [
			ARTICLE_II.rules.vesting,
			ARTICLE_II.rules.electionAndEligibility,
			ARTICLE_II.rules.compensation,
			ARTICLE_II.rules.oath,
			ARTICLE_II.amendments.twelfth,
			ARTICLE_II.amendments.twentieth,
			ARTICLE_II.amendments.twentySecond,
			ARTICLE_II.engineering.mandateNotSelfAsserted,
		],
	});
}

function assertExecutive(executive) {
	if (executive?.status !== 'executive-constituted') {
		throw new TypeError('A constituted Article II executive is required');
	}

	if (executive.executiveDigest !== digest(executiveContent(executive))) {
		throw new TypeError('Executive integrity check failed');
	}

	if (
		!PRESIDENTIAL_CAPABILITIES.every((capability) => executive.capabilities.includes(capability))
	) {
		throw new TypeError('Executive capability registry is incomplete');
	}
}

function requireDeclarationRecipients(event) {
	requireUniqueStrings(event.recipients, 'event.recipients');
	const recipients = new Set(event.recipients);

	if (!recipients.has('speaker-of-the-house') || !recipients.has('president-pro-tempore')) {
		throw new TypeError('Inability declaration must reach both constitutional recipients');
	}
}

function continuitySnapshot(
	executive,
	event,
	activeAuthority,
	constitutionalSources = [ARTICLE_II.amendments.twentyFifth],
) {
	const eventContent = {
		id: event.id,
		kind: event.kind,
		effectiveAt: event.effectiveAt,
		evidenceDigest: event.evidenceDigest,
		activeAuthority,
	};
	const content = {
		...executiveContent(executive),
		activeAuthority,
		parentExecutiveDigest: executive.executiveDigest,
		continuityEventDigest: digest(eventContent),
	};

	return deepFreeze({
		status: 'executive-constituted',
		...content,
		executiveDigest: digest(content),
		capabilities: [...PRESIDENTIAL_CAPABILITIES],
		trace: [...executive.trace, ...constitutionalSources, ARTICLE_II.engineering.continuityLineage],
	});
}

export function applyContinuityEvent({ executive, event }) {
	assertExecutive(executive);
	requireObject(event, 'event');
	requireNonEmptyString(event.id, 'event.id');
	requireNonEmptyString(event.kind, 'event.kind');
	requireIsoDate(event.effectiveAt, 'event.effectiveAt');
	requireNonEmptyString(event.evidenceDigest, 'event.evidenceDigest');

	if (event.authenticated !== true) {
		throw new TypeError('Continuity event must be authenticated');
	}

	if (['death', 'resignation', 'impeachment-removal'].includes(event.kind)) {
		if (event.subjectId !== executive.president.id) {
			throw new TypeError('Succession event concerns another President');
		}

		return continuitySnapshot(executive, event, {
			holderId: executive.vicePresident.id,
			role: 'president',
			mode: 'succeeded-to-presidency',
			authoritySince: event.effectiveAt,
			authorityBasis: `amendment-xxv-section-1:${event.kind}`,
		});
	}

	if (event.kind === 'voluntary-inability') {
		requireDeclarationRecipients(event);

		if (event.declarantId !== executive.president.id) {
			throw new TypeError('Voluntary inability declaration must come from the President');
		}

		return continuitySnapshot(executive, event, {
			holderId: executive.vicePresident.id,
			role: 'acting-president',
			mode: 'voluntary-inability',
			authoritySince: event.effectiveAt,
			authorityBasis: 'amendment-xxv-section-3',
		});
	}

	if (event.kind === 'involuntary-inability') {
		requireDeclarationRecipients(event);
		requireArray(event.concurringPrincipalOfficerIds, 'event.concurringPrincipalOfficerIds');
		requireUniqueStrings(
			event.concurringPrincipalOfficerIds,
			'event.concurringPrincipalOfficerIds',
		);

		if (event.vicePresidentJoined !== true) {
			throw new TypeError('Vice President must join an Amendment XXV section 4 declaration');
		}

		if (!Number.isInteger(event.principalOfficersTotal) || event.principalOfficersTotal < 1) {
			throw new TypeError('principalOfficersTotal must be a positive integer');
		}

		const required = Math.floor(event.principalOfficersTotal / 2) + 1;

		if (event.concurringPrincipalOfficerIds.length < required) {
			throw new TypeError('Involuntary inability lacks a majority of principal officers');
		}

		return continuitySnapshot(executive, event, {
			holderId: executive.vicePresident.id,
			role: 'acting-president',
			mode: 'involuntary-inability',
			authoritySince: event.effectiveAt,
			authorityBasis: 'amendment-xxv-section-4-initial-declaration',
		});
	}

	if (event.kind === 'presidential-recovery') {
		requireDeclarationRecipients(event);

		if (event.declarantId !== executive.president.id) {
			throw new TypeError('Recovery declaration must come from the President');
		}

		if (event.challengeWithinFourDays === true) {
			const houseSatisfied =
				event.congressionalDecision?.authenticated === true &&
				event.congressionalDecision.houseTwoThirds === true;
			const senateSatisfied =
				event.congressionalDecision?.authenticated === true &&
				event.congressionalDecision.senateTwoThirds === true;
			const timely = event.congressionalDecision?.withinTwentyOneDays === true;

			if (houseSatisfied && senateSatisfied && timely) {
				return continuitySnapshot(executive, event, {
					holderId: executive.vicePresident.id,
					role: 'acting-president',
					mode: 'inability-sustained-by-congress',
					authoritySince: event.effectiveAt,
					authorityBasis: 'amendment-xxv-section-4-congressional-decision',
				});
			}
		}

		return continuitySnapshot(executive, event, {
			holderId: executive.president.id,
			role: 'president',
			mode: 'presidential-authority-resumed',
			authoritySince: event.effectiveAt,
			authorityBasis: 'amendment-xxv-recovery',
		});
	}

	if (event.kind === 'dual-vacancy') {
		const successor = executive.successionPlan.entries.find(
			(entry) => entry.officerId === event.successorId,
		);

		if (!successor || successor.eligibleToAct !== true) {
			throw new TypeError('Dual-vacancy successor is not eligible under the authenticated plan');
		}

		const earlierEligible = executive.successionPlan.entries.some(
			(entry) => entry.rank < successor.rank && entry.eligibleToAct,
		);

		if (earlierEligible) {
			throw new TypeError('Dual-vacancy event skipped an earlier eligible successor');
		}

		return continuitySnapshot(
			executive,
			event,
			{
				holderId: successor.officerId,
				role: 'acting-president',
				mode: 'statutory-dual-vacancy',
				authoritySince: event.effectiveAt,
				authorityBasis: `succession-statute:${executive.successionPlan.statuteDigest}`,
			},
			[ARTICLE_II.rules.succession, ARTICLE_II.amendments.twentieth],
		);
	}

	throw new TypeError(`Unsupported continuity event: ${event.kind}`);
}

function assertActivePresidentialActor(executive, actorId) {
	requireNonEmptyString(actorId, 'actorId');

	if (actorId !== executive.activeAuthority.holderId) {
		throw new TypeError('Operation was not issued by the active presidential authority holder');
	}
}

function normalizeOffice(office, rootDigest) {
	requireObject(office, 'office');
	requireNonEmptyString(office.id, 'office.id');
	requireNonEmptyString(office.name ?? office.id, 'office.name');
	requireNonEmptyString(office.classification, 'office.classification');
	requireNonEmptyString(office.establishmentDigest, 'office.establishmentDigest');
	requireUniqueStrings(office.capabilities, 'office.capabilities');

	if (!['principal', 'inferior'].includes(office.classification)) {
		throw new TypeError('Office classification must be principal or inferior');
	}

	if (office.establishedByLaw !== true) {
		throw new TypeError('An office must exist by authenticated law before it can be filled');
	}

	if (office.establishmentRootDigest !== rootDigest) {
		throw new TypeError('Office was established under another normative root');
	}

	if (office.classification === 'inferior') {
		if (!APPOINTING_ACTORS.includes(office.appointmentVestedIn)) {
			throw new TypeError('Inferior office requires a constitutionally permitted appointing actor');
		}

		if (office.appointmentVestingAuthenticated !== true) {
			throw new TypeError('Inferior-office appointment vesting must be authenticated');
		}
	}

	return {
		id: office.id,
		name: office.name ?? office.id,
		classification: office.classification,
		establishedByLaw: true,
		establishmentDigest: office.establishmentDigest,
		establishmentRootDigest: office.establishmentRootDigest,
		appointmentVestedIn: office.classification === 'inferior' ? office.appointmentVestedIn : null,
		appointmentVestingAuthenticated: office.classification === 'inferior' ? true : null,
		departmentId: office.departmentId ?? null,
		courtId: office.courtId ?? null,
		executionEndpoint: office.executionEndpoint ?? null,
		capabilities: [...office.capabilities],
	};
}

function normalizeCandidate(candidate, officeId) {
	requireObject(candidate, 'candidate');
	requireNonEmptyString(candidate.id, 'candidate.id');

	if (candidate.eligibilityVerified !== true) {
		throw new TypeError(`Candidate for ${officeId} lacks an eligibility determination`);
	}

	return {
		id: candidate.id,
		name: candidate.name ?? candidate.id,
		eligibilityVerified: true,
		conflictReviewDigest: candidate.conflictReviewDigest ?? null,
	};
}

function normalizeCommission(executive, office, candidate, commission) {
	requireObject(commission, 'commission');
	requireNonEmptyString(commission.id, 'commission.id');
	requireIsoDate(commission.issuedAt, 'commission.issuedAt');

	if (commission.authenticated !== true) {
		throw new TypeError('Officer commission must be authenticated');
	}

	assertActivePresidentialActor(executive, commission.signedBy);

	if (commission.officeId !== office.id || commission.candidateId !== candidate.id) {
		throw new TypeError('Commission does not match the appointment');
	}

	return {
		id: commission.id,
		issuedAt: commission.issuedAt,
		signedBy: commission.signedBy,
		officeId: commission.officeId,
		candidateId: commission.candidateId,
		authenticated: true,
	};
}

function officerContent(officer) {
	return {
		officerId: officer.officerId,
		executiveDigest: officer.executiveDigest,
		rootDigest: officer.rootDigest,
		office: officer.office,
		candidate: officer.candidate,
		appointmentPath: officer.appointmentPath,
		appointmentDigest: officer.appointmentDigest,
		commission: officer.commission,
		temporary: officer.temporary,
		expiresAt: officer.expiresAt,
		active: officer.active,
	};
}

export function appointOfficer({
	executive,
	office,
	candidate,
	nomination = null,
	senateConsent = null,
	appointment,
	commission,
}) {
	assertExecutive(executive);
	const normalizedOffice = normalizeOffice(office, executive.normativeRoot.digest);
	const normalizedCandidate = normalizeCandidate(candidate, normalizedOffice.id);
	requireObject(appointment, 'appointment');
	requireNonEmptyString(appointment.id, 'appointment.id');
	requireNonEmptyString(appointment.actorKind, 'appointment.actorKind');
	requireNonEmptyString(appointment.actorId, 'appointment.actorId');
	requireIsoDate(appointment.appointedAt, 'appointment.appointedAt');

	if (appointment.authenticated !== true) {
		throw new TypeError('Appointment act must be authenticated');
	}

	if (
		appointment.officeId !== normalizedOffice.id ||
		appointment.candidateId !== normalizedCandidate.id
	) {
		throw new TypeError('Appointment act does not match office and candidate');
	}

	let appointmentPath;

	const senateRoute =
		normalizedOffice.classification === 'principal' ||
		normalizedOffice.appointmentVestedIn === 'president-with-senate-consent';

	if (senateRoute) {
		requireObject(nomination, 'nomination');
		requireObject(senateConsent, 'senateConsent');

		if (
			nomination.authenticated !== true ||
			nomination.officeId !== normalizedOffice.id ||
			nomination.candidateId !== normalizedCandidate.id
		) {
			throw new TypeError('Principal-office nomination is absent or mismatched');
		}

		assertActivePresidentialActor(executive, nomination.nominatedBy);

		if (
			senateConsent.authenticated !== true ||
			senateConsent.approved !== true ||
			senateConsent.quorumVerified !== true ||
			senateConsent.officeId !== normalizedOffice.id ||
			senateConsent.candidateId !== normalizedCandidate.id
		) {
			throw new TypeError(
				'Principal-office appointment lacks authenticated Senate advice and consent',
			);
		}

		if (
			appointment.actorKind !== 'president' ||
			appointment.actorId !== executive.activeAuthority.holderId
		) {
			throw new TypeError('Principal officer must be appointed by the active President');
		}

		appointmentPath =
			normalizedOffice.classification === 'principal'
				? 'president-with-senate-consent'
				: 'inferior:president-with-senate-consent';
	} else {
		if (appointment.actorKind !== normalizedOffice.appointmentVestedIn) {
			throw new TypeError(
				'Inferior officer was appointed by an actor outside the statutory vesting',
			);
		}

		if (appointment.actorKind === 'president-alone') {
			assertActivePresidentialActor(executive, appointment.actorId);
		} else if (appointment.actorAuthorityVerified !== true) {
			throw new TypeError('Inferior-officer appointing actor lacks verified authority');
		}

		if (
			appointment.actorKind === 'department-head' &&
			appointment.actorDepartmentId !== normalizedOffice.departmentId
		) {
			throw new TypeError('Department head cannot appoint an officer of another department');
		}

		if (
			appointment.actorKind === 'court-of-law' &&
			appointment.actorCourtId !== normalizedOffice.courtId
		) {
			throw new TypeError('Court cannot appoint an officer outside the authenticated vesting');
		}

		appointmentPath = `inferior:${appointment.actorKind}`;
	}

	const normalizedAppointment = {
		id: appointment.id,
		officeId: normalizedOffice.id,
		candidateId: normalizedCandidate.id,
		actorKind: appointment.actorKind,
		actorId: appointment.actorId,
		appointedAt: appointment.appointedAt,
		authenticated: true,
	};
	const normalizedCommission = normalizeCommission(
		executive,
		normalizedOffice,
		normalizedCandidate,
		commission,
	);
	const content = {
		officerId: normalizedCandidate.id,
		executiveDigest: executive.executiveDigest,
		rootDigest: executive.normativeRoot.digest,
		office: normalizedOffice,
		candidate: normalizedCandidate,
		appointmentPath,
		appointmentDigest: digest(normalizedAppointment),
		commission: normalizedCommission,
		temporary: false,
		expiresAt: null,
		active: true,
	};

	return deepFreeze({
		status: 'officer-commissioned',
		...content,
		officerDigest: digest(content),
		trace: [
			ARTICLE_II.rules.appointments,
			ARTICLE_II.rules.commissions,
			ARTICLE_II.doctrine.appointmentClasses,
			ARTICLE_II.engineering.boundedCapabilities,
		],
	});
}

export function makeRecessAppointment({
	executive,
	office,
	candidate,
	senateState,
	appointment,
	commission,
}) {
	assertExecutive(executive);
	const normalizedOffice = normalizeOffice(office, executive.normativeRoot.digest);
	const normalizedCandidate = normalizeCandidate(candidate, normalizedOffice.id);
	requireObject(senateState, 'senateState');
	requireObject(appointment, 'appointment');
	requireIsoDate(appointment.appointedAt, 'appointment.appointedAt');
	requireIsoDate(senateState.recessStartedAt, 'senateState.recessStartedAt');
	requireIsoDate(senateState.recessScheduledEndAt, 'senateState.recessScheduledEndAt');
	requireIsoDate(senateState.nextSessionEndsAt, 'senateState.nextSessionEndsAt');

	if (
		senateState.authenticated !== true ||
		senateState.senateSelfReportsInSession === true ||
		senateState.canTransactBusiness === true
	) {
		throw new TypeError('Senate is constitutionally in session for this model');
	}

	if (!Number.isInteger(senateState.recessDurationDays) || senateState.recessDurationDays < 10) {
		throw new TypeError('This conservative model rejects a recess shorter than ten days');
	}

	if (
		appointment.authenticated !== true ||
		appointment.officeId !== normalizedOffice.id ||
		appointment.candidateId !== normalizedCandidate.id
	) {
		throw new TypeError('Recess appointment act is absent or mismatched');
	}

	assertActivePresidentialActor(executive, appointment.actorId);
	const normalizedCommission = normalizeCommission(
		executive,
		normalizedOffice,
		normalizedCandidate,
		commission,
	);
	const appointmentContent = {
		id: appointment.id,
		actorId: appointment.actorId,
		officeId: normalizedOffice.id,
		candidateId: normalizedCandidate.id,
		appointedAt: appointment.appointedAt,
		recessStateDigest: digest(senateState),
	};
	const content = {
		officerId: normalizedCandidate.id,
		executiveDigest: executive.executiveDigest,
		rootDigest: executive.normativeRoot.digest,
		office: normalizedOffice,
		candidate: normalizedCandidate,
		appointmentPath: 'recess-commission',
		appointmentDigest: digest(appointmentContent),
		commission: normalizedCommission,
		temporary: true,
		expiresAt: senateState.nextSessionEndsAt,
		active: true,
	};

	return deepFreeze({
		status: 'officer-commissioned',
		...content,
		officerDigest: digest(content),
		trace: [
			ARTICLE_II.rules.recessAppointments,
			ARTICLE_II.doctrine.senateSession,
			ARTICLE_II.rules.commissions,
		],
	});
}

function assertOfficer(executive, officer) {
	if (officer?.status !== 'officer-commissioned' || officer.active !== true) {
		throw new TypeError('An active commissioned officer is required');
	}

	if (
		officer.executiveDigest !== executive.executiveDigest ||
		officer.rootDigest !== executive.normativeRoot.digest
	) {
		throw new TypeError('Officer belongs to another executive authority snapshot');
	}

	if (officer.officerDigest !== digest(officerContent(officer))) {
		throw new TypeError('Officer integrity check failed');
	}
}

export function makeTreaty({ executive, instrument, senateConsent }) {
	assertExecutive(executive);
	requireObject(instrument, 'instrument');
	requireObject(senateConsent, 'senateConsent');
	requireNonEmptyString(instrument.id, 'instrument.id');
	requireNonEmptyString(instrument.textDigest, 'instrument.textDigest');
	requireNonEmptyString(instrument.domesticEffect, 'instrument.domesticEffect');

	if (instrument.negotiatedBy !== executive.activeAuthority.holderId) {
		throw new TypeError('Treaty instrument lacks presidential attribution');
	}

	if (instrument.rootDigest !== executive.normativeRoot.digest) {
		throw new TypeError('Treaty instrument belongs to another normative root');
	}

	if (
		instrument.authenticated !== true ||
		instrument.underAuthorityVerified !== true ||
		instrument.constitutionalCompatibilityDetermined !== true
	) {
		throw new TypeError('Treaty instrument lacks authenticated constitutional authority review');
	}

	if (
		senateConsent.authenticated !== true ||
		senateConsent.instrumentId !== instrument.id ||
		senateConsent.quorumVerified !== true
	) {
		throw new TypeError('Treaty lacks authenticated Senate advice and consent');
	}

	if (
		!Number.isInteger(senateConsent.senatorsPresent) ||
		senateConsent.senatorsPresent < 1 ||
		!Number.isInteger(senateConsent.yeas) ||
		senateConsent.yeas < 0 ||
		senateConsent.yeas > senateConsent.senatorsPresent
	) {
		throw new TypeError('Treaty Senate vote counts are invalid');
	}

	const requiredYeas = Math.ceil((2 * senateConsent.senatorsPresent) / 3);

	if (senateConsent.yeas < requiredYeas) {
		return deepFreeze({
			status: 'treaty-not-made',
			reason: 'two-thirds-of-senators-present-not-reached',
			instrumentDigest: digest(instrument),
			requiredYeas,
			actualYeas: senateConsent.yeas,
			trace: [ARTICLE_II.rules.treaties, ARTICLE_II.engineering.safeSharedPower],
		});
	}

	if (
		!['self-executing', 'requires-implementing-legislation'].includes(instrument.domesticEffect)
	) {
		throw new TypeError('Treaty domestic effect must be classified');
	}

	const content = {
		treatyId: instrument.id,
		rootDigest: executive.normativeRoot.digest,
		executiveDigest: executive.executiveDigest,
		textDigest: instrument.textDigest,
		instrumentRootDigest: instrument.rootDigest,
		negotiatedBy: instrument.negotiatedBy,
		senateConsentDigest: digest(senateConsent),
		senatorsPresent: senateConsent.senatorsPresent,
		yeas: senateConsent.yeas,
		requiredYeas,
		domesticEffect: instrument.domesticEffect,
	};

	return deepFreeze({
		status: 'treaty-made',
		...content,
		treatyDigest: digest(content),
		handoff:
			instrument.domesticEffect === 'self-executing'
				? 'article-vi:register-treaty'
				: 'article-i:implementing-legislation',
		trace: [
			ARTICLE_II.rules.treaties,
			ARTICLE_II.doctrine.treatyEffect,
			ARTICLE_II.engineering.safeSharedPower,
		],
	});
}

export function grantClemency({ executive, request }) {
	assertExecutive(executive);
	requireObject(request, 'request');
	requireNonEmptyString(request.id, 'request.id');
	requireNonEmptyString(request.kind, 'request.kind');
	requireNonEmptyString(request.recipientId, 'request.recipientId');
	requireNonEmptyString(request.offenseId, 'request.offenseId');
	requireNonEmptyString(request.criminalEffect, 'request.criminalEffect');

	if (!CLEMENCY_KINDS.includes(request.kind)) {
		throw new TypeError('Unsupported clemency kind');
	}

	if (request.authenticated !== true) {
		throw new TypeError('Clemency request must be authenticated');
	}

	if (request.selfDirected === true) {
		return deepFreeze({
			status: 'requires-constitutional-determination',
			reason: 'self-directed-clemency-remains-constitutionally-unresolved',
			requestDigest: digest(request),
			handoff: 'article-iii:resolve',
			trace: [ARTICLE_II.doctrine.pardonBoundary, ARTICLE_II.engineering.wardenBoundary],
		});
	}

	if (request.offenseSovereign !== 'united-states') {
		return deepFreeze({
			status: 'clemency-rejected',
			reason: 'outside-federal-offense-power',
			requestDigest: digest(request),
			trace: [ARTICLE_II.rules.clemency, ARTICLE_II.doctrine.pardonBoundary],
		});
	}

	if (request.proceedingKind === 'impeachment') {
		return deepFreeze({
			status: 'clemency-rejected',
			reason: 'impeachment-exception',
			requestDigest: digest(request),
			trace: [ARTICLE_II.rules.clemency, ARTICLE_II.rules.impeachmentRemoval],
		});
	}

	const content = {
		clemencyId: `clemency:${request.id}`,
		executiveDigest: executive.executiveDigest,
		rootDigest: executive.normativeRoot.digest,
		issuedBy: executive.activeAuthority.holderId,
		kind: request.kind,
		recipientId: request.recipientId,
		offenseId: request.offenseId,
		offenseSovereign: request.offenseSovereign,
		criminalEffect: request.criminalEffect,
		civilEffect: 'unchanged-unless-independently-authorized',
	};

	return deepFreeze({
		status: 'clemency-issued',
		...content,
		clemencyDigest: digest(content),
		trace: [ARTICLE_II.rules.clemency, ARTICLE_II.doctrine.pardonBoundary],
	});
}

export function requestWrittenOpinion({ executive, principalOfficer, subject }) {
	assertExecutive(executive);
	requireObject(principalOfficer, 'principalOfficer');
	requireObject(subject, 'subject');
	requireNonEmptyString(principalOfficer.officerId, 'principalOfficer.officerId');
	requireNonEmptyString(principalOfficer.departmentId, 'principalOfficer.departmentId');
	requireNonEmptyString(subject.id, 'subject.id');
	requireNonEmptyString(subject.question, 'subject.question');

	if (
		principalOfficer.classification !== 'principal' ||
		principalOfficer.active !== true ||
		principalOfficer.authorityVerified !== true
	) {
		throw new TypeError(
			'Written opinion may be required only from a verified principal department officer',
		);
	}

	if (
		subject.relatesToDepartmentDuties !== true ||
		subject.departmentId !== principalOfficer.departmentId
	) {
		throw new TypeError("Written-opinion subject lies outside the officer's departmental duties");
	}

	const content = {
		requestId: `opinion-request:${subject.id}`,
		executiveDigest: executive.executiveDigest,
		requestedBy: executive.activeAuthority.holderId,
		principalOfficerId: principalOfficer.officerId,
		departmentId: principalOfficer.departmentId,
		question: subject.question,
		subjectDigest: digest(subject),
	};

	return deepFreeze({
		status: 'written-opinion-requested',
		...content,
		requestDigest: digest(content),
		opinion: 'not-manufactured-by-request',
		handoff: `department:${principalOfficer.departmentId}:respond-in-writing`,
		trace: [ARTICLE_II.rules.writtenOpinions, ARTICLE_II.engineering.boundedCapabilities],
	});
}

export function commandForces({ executive, order, authorization }) {
	assertExecutive(executive);
	requireObject(order, 'order');
	requireObject(authorization, 'authorization');
	requireNonEmptyString(order.id, 'order.id');
	requireNonEmptyString(order.force, 'order.force');
	requireNonEmptyString(order.operation, 'order.operation');
	requireNonEmptyString(order.scope, 'order.scope');
	requireNonEmptyString(authorization.kind, 'authorization.kind');

	if (authorization.rootDigest !== executive.normativeRoot.digest) {
		throw new TypeError('Military authorization belongs to another normative root');
	}

	if (!MILITARY_FORCES.includes(order.force)) {
		throw new TypeError('Unsupported military force');
	}

	if (order.issuedBy !== executive.activeAuthority.holderId || order.authenticated !== true) {
		throw new TypeError('Military order lacks active presidential attribution');
	}

	if (order.lawOfArmedConflictReviewVerified !== true) {
		throw new TypeError('Military order lacks an authenticated law-of-armed-conflict review');
	}

	if (order.appropriationVerified !== true) {
		throw new TypeError('Military order lacks an authenticated appropriation boundary');
	}

	if (order.force === 'state-militia' && authorization.calledIntoActualService !== true) {
		return deepFreeze({
			status: 'military-order-blocked',
			reason: 'state-militia-not-called-into-actual-federal-service',
			orderDigest: digest(order),
			trace: [ARTICLE_II.rules.commanderInChief],
		});
	}

	let authorityCategory;

	if (authorization.kind === 'congress-authorized') {
		if (
			authorization.authenticated !== true ||
			authorization.statuteStatus !== 'in-force' ||
			authorization.scopeIncludesOrder !== true
		) {
			throw new TypeError('Congressional military authorization is invalid or outside scope');
		}

		authorityCategory = 'youngstown-category-one';
	} else if (authorization.kind === 'repel-verified-attack') {
		if (
			authorization.authenticated !== true ||
			authorization.hostileAttackVerified !== true ||
			authorization.responseScopeVerified !== true
		) {
			return deepFreeze({
				status: 'military-order-blocked',
				reason: 'attack-or-response-scope-not-verified',
				orderDigest: digest(order),
				trace: [ARTICLE_II.rules.commanderInChief, ARTICLE_II.engineering.wardenBoundary],
			});
		}

		authorityCategory = 'repel-verified-attack';
	} else if (authorization.kind === 'congress-silent') {
		return deepFreeze({
			status: 'requires-constitutional-determination',
			reason: 'youngstown-zone-of-twilight',
			orderDigest: digest(order),
			handoff: 'article-iii:resolve-if-case-or-controversy',
			trace: [ARTICLE_II.doctrine.youngstown, ARTICLE_II.engineering.wardenBoundary],
		});
	} else if (authorization.kind === 'contrary-to-congress') {
		if (
			authorization.authenticated !== true ||
			authorization.exclusivePresidentialPowerDetermination !== true
		) {
			return deepFreeze({
				status: 'military-order-blocked',
				reason: 'youngstown-category-three-without-exclusive-power-determination',
				orderDigest: digest(order),
				trace: [ARTICLE_II.doctrine.youngstown],
			});
		}

		authorityCategory = 'youngstown-category-three-exclusive-power-determined';
	} else {
		throw new TypeError('Unsupported military authority class');
	}

	const content = {
		commandId: `command:${order.id}`,
		executiveDigest: executive.executiveDigest,
		rootDigest: executive.normativeRoot.digest,
		issuedBy: order.issuedBy,
		force: order.force,
		operation: order.operation,
		scope: order.scope,
		authorityCategory,
		authorizationDigest: digest(authorization),
	};

	return deepFreeze({
		status: 'military-order-authorized',
		...content,
		commandDigest: digest(content),
		declarationOfWar: 'not-created-by-executive-order',
		trace: [
			ARTICLE_II.rules.commanderInChief,
			ARTICLE_II.doctrine.youngstown,
			ARTICLE_II.engineering.boundedCapabilities,
		],
	});
}

function judgmentContent(judgment) {
	return {
		judgmentId: judgment.judgmentId,
		judiciaryId: judgment.judiciaryId,
		rootDigest: judgment.rootDigest,
		caseDigest: judgment.caseDigest,
		recordDigest: judgment.recordDigest,
		courtId: judgment.courtId,
		courtTier: judgment.courtTier,
		jurisdictionHead: judgment.jurisdictionHead,
		decidedAt: judgment.decidedAt,
		disposition: judgment.disposition,
		holdings: judgment.holdings,
		remedy: judgment.remedy,
		sourceDigest: judgment.sourceDigest,
		parentJudgmentDigest: judgment.parentJudgmentDigest ?? null,
		appellateOutcome: judgment.appellateOutcome ?? null,
	};
}

function assertExecutableJudgment(executive, judgment) {
	if (judgment?.status !== 'judgment-entered') {
		throw new TypeError('execute requires an entered Article III judgment');
	}

	if (judgment.judgmentDigest !== digest(judgmentContent(judgment))) {
		throw new TypeError('Judgment integrity check failed at the executive boundary');
	}

	if (judgment.rootDigest !== executive.normativeRoot.digest) {
		throw new TypeError('Judgment and executive belong to different normative roots');
	}

	if (judgment.handoff !== 'article-ii:execute') {
		throw new TypeError('Judgment does not authorize an Article II execution handoff');
	}

	if (
		judgment.execution === 'stayed' ||
		judgment.execution === 'suspended-on-remand' ||
		judgment.mandate?.executionStayed === true
	) {
		return false;
	}

	if (
		judgment.execution !== 'pending-separate-execution' ||
		!judgment.remedy ||
		judgment.remedy.type === 'none'
	) {
		throw new TypeError('Judgment has no executable coercive remedy');
	}

	return true;
}

function executionOrderContent(order) {
	return {
		orderId: order.orderId,
		executiveDigest: order.executiveDigest,
		rootDigest: order.rootDigest,
		judgmentDigest: order.judgmentDigest,
		caseDigest: order.caseDigest,
		officerDigest: order.officerDigest,
		executionEndpoint: order.executionEndpoint,
		preparedAt: order.preparedAt,
		target: order.target,
		operation: order.operation,
		scope: order.scope,
		reversibleUntilFinal: order.reversibleUntilFinal,
		steps: order.steps,
	};
}

export function execute({ executive, judgment, officer, plan }) {
	assertExecutive(executive);
	assertOfficer(executive, officer);
	const executable = assertExecutableJudgment(executive, judgment);

	if (!executable) {
		return deepFreeze({
			status: 'execution-stayed',
			judgmentDigest: judgment.judgmentDigest,
			reason: 'article-iii-stay-or-remand',
			handoff: 'article-iii:await-further-order',
			trace: [ARTICLE_II.rules.takeCare, ARTICLE_II.doctrine.finalJudgment],
		});
	}

	requireObject(plan, 'plan');
	requireNonEmptyString(plan.id, 'plan.id');
	requireIsoDate(plan.preparedAt, 'plan.preparedAt');
	requireArray(plan.steps, 'plan.steps');

	if (!officer.office.capabilities.includes('execute-federal-judgment')) {
		throw new TypeError('Commissioned officer lacks judgment-execution capability');
	}

	if (officer.office.executionEndpoint !== judgment.remedy.executableBy) {
		throw new TypeError('Judicial remedy names another executive endpoint');
	}

	if (plan.sourceJudgmentDigest !== judgment.judgmentDigest) {
		throw new TypeError('Execution plan references another judgment');
	}

	if (plan.target !== judgment.remedy.target) {
		throw new TypeError('Execution plan changes the judicial target');
	}

	if (plan.operation !== judgment.remedy.operation) {
		throw new TypeError('Execution plan changes the judicial operation');
	}

	if (plan.scope !== judgment.remedy.scope) {
		throw new TypeError('Execution plan enlarges or changes the judicial scope');
	}

	if (plan.noAdditionalSanction !== true) {
		throw new TypeError('Execution plan may not add an executive sanction');
	}

	if (plan.leastForceVerified !== true) {
		throw new TypeError('Execution plan lacks a least-force determination');
	}

	if (plan.appropriationVerified !== true) {
		throw new TypeError('Execution plan lacks an appropriation boundary');
	}

	requireUniqueStrings(
		plan.steps.map((step) => step.id),
		'execution step ids',
	);

	if (plan.steps.length === 0) {
		throw new TypeError('Execution plan requires at least one bounded step');
	}

	const steps = plan.steps.map((step) => {
		requireNonEmptyString(step.id, 'step.id');
		requireNonEmptyString(step.action, `${step.id}.action`);
		requireNonEmptyString(step.expectedEffect, `${step.id}.expectedEffect`);

		if (
			step.target !== judgment.remedy.target ||
			step.scope !== judgment.remedy.scope ||
			step.withinRemedy !== true
		) {
			throw new TypeError(`${step.id} exceeds the judicial remedy`);
		}

		if (judgment.remedy.reversibleUntilFinal === true && step.reversible !== true) {
			throw new TypeError(`${step.id} must remain reversible while appellate review is available`);
		}

		return {
			id: step.id,
			action: step.action,
			target: step.target,
			scope: step.scope,
			expectedEffect: step.expectedEffect,
			withinRemedy: true,
			reversible: step.reversible === true,
		};
	});
	const content = {
		orderId: `execution-order:${plan.id}`,
		executiveDigest: executive.executiveDigest,
		rootDigest: executive.normativeRoot.digest,
		judgmentDigest: judgment.judgmentDigest,
		caseDigest: judgment.caseDigest,
		officerDigest: officer.officerDigest,
		executionEndpoint: officer.office.executionEndpoint,
		preparedAt: plan.preparedAt,
		target: judgment.remedy.target,
		operation: judgment.remedy.operation,
		scope: judgment.remedy.scope,
		reversibleUntilFinal: judgment.remedy.reversibleUntilFinal,
		steps,
	};

	return deepFreeze({
		status: 'execution-ordered',
		...content,
		orderDigest: digest(content),
		sourceSnapshot: {
			judgmentDigest: judgment.judgmentDigest,
			holdingsDigest: digest(judgment.holdings),
			remedyDigest: digest(judgment.remedy),
		},
		execution: 'pending-observation',
		handoff: 'runtime:perform-authorized-steps',
		trace: [
			ARTICLE_II.rules.takeCare,
			ARTICLE_II.doctrine.finalJudgment,
			ARTICLE_II.engineering.sourcePreservingExecution,
			ARTICLE_II.engineering.boundedCapabilities,
		],
	});
}

export function confirmExecution({ executive, order, observations, confirmedAt }) {
	assertExecutive(executive);
	requireObject(order, 'order');
	requireArray(observations, 'observations');
	requireIsoDate(confirmedAt, 'confirmedAt');

	if (order.status !== 'execution-ordered') {
		throw new TypeError('An Article II execution order is required');
	}

	if (order.executiveDigest !== executive.executiveDigest) {
		throw new TypeError('Execution order belongs to another executive snapshot');
	}

	if (order.orderDigest !== digest(executionOrderContent(order))) {
		throw new TypeError('Execution order integrity check failed');
	}

	requireUniqueStrings(
		observations.map((observation) => observation.stepId),
		'observation step ids',
	);
	const stepIds = new Set(order.steps.map((step) => step.id));

	for (const observation of observations) {
		requireNonEmptyString(observation.stepId, 'observation.stepId');

		if (!stepIds.has(observation.stepId)) {
			throw new TypeError(`Observation references an unauthorized step: ${observation.stepId}`);
		}

		if (observation.authenticated !== true) {
			throw new TypeError(`Observation for ${observation.stepId} is not authenticated`);
		}
	}

	const observationsByStep = new Map(
		observations.map((observation) => [observation.stepId, observation]),
	);
	const stepResults = order.steps.map((step) => {
		const observation = observationsByStep.get(step.id);

		return {
			stepId: step.id,
			observed: observation !== undefined,
			completed: observation?.completed === true,
			observedEffect: observation?.observedEffect ?? null,
			observationDigest: observation ? digest(observation) : null,
		};
	});
	const completed = stepResults.every((result) => result.completed);
	const content = {
		receiptId: `execution-receipt:${order.orderDigest.slice(7, 23)}`,
		executiveDigest: executive.executiveDigest,
		rootDigest: executive.normativeRoot.digest,
		orderDigest: order.orderDigest,
		judgmentDigest: order.judgmentDigest,
		caseDigest: order.caseDigest,
		confirmedAt,
		completed,
		stepResults,
	};

	return deepFreeze({
		status: completed ? 'execution-confirmed' : 'execution-incomplete',
		...content,
		receiptDigest: digest(content),
		handoff: completed ? 'article-iii:execution-receipt' : 'article-ii:remediate-execution',
		trace: [
			ARTICLE_II.rules.takeCare,
			ARTICLE_II.engineering.executionReceipt,
			ARTICLE_II.engineering.sourcePreservingExecution,
		],
	});
}

export function communicateWithCongress({ executive, message }) {
	assertExecutive(executive);
	requireObject(message, 'message');
	requireNonEmptyString(message.id, 'message.id');
	requireNonEmptyString(message.kind, 'message.kind');
	requireNonEmptyString(message.contentDigest, 'message.contentDigest');
	requireIsoDate(message.issuedAt, 'message.issuedAt');

	if (!CONGRESSIONAL_MESSAGES.includes(message.kind)) {
		throw new TypeError('Unsupported Article II congressional communication');
	}

	if (message.authenticated !== true) {
		throw new TypeError('Congressional communication must be authenticated');
	}

	if (
		message.kind === 'convene-extraordinary-session' &&
		message.extraordinaryOccasionVerified !== true
	) {
		throw new TypeError('Extraordinary convening requires an attributed occasion determination');
	}

	if (
		message.kind === 'adjourn-after-house-disagreement' &&
		message.houseDisagreementOnAdjournmentAuthenticated !== true
	) {
		throw new TypeError('Presidential adjournment requires authenticated House disagreement');
	}

	const content = {
		messageId: message.id,
		executiveDigest: executive.executiveDigest,
		issuedBy: executive.activeAuthority.holderId,
		kind: message.kind,
		contentDigest: message.contentDigest,
		issuedAt: message.issuedAt,
	};

	return deepFreeze({
		status: 'congressional-communication-issued',
		...content,
		messageDigest: digest(content),
		legislation: 'not-created-by-recommendation',
		trace: [ARTICLE_II.rules.congressionalCommunication],
	});
}

export function receiveDiplomat({ executive, diplomat }) {
	assertExecutive(executive);
	requireObject(diplomat, 'diplomat');
	requireNonEmptyString(diplomat.id, 'diplomat.id');
	requireNonEmptyString(diplomat.sendingState, 'diplomat.sendingState');
	requireNonEmptyString(diplomat.credentialDigest, 'diplomat.credentialDigest');
	requireIsoDate(diplomat.receivedAt, 'diplomat.receivedAt');

	if (diplomat.credentialsAuthenticated !== true) {
		throw new TypeError('Diplomatic credentials must be authenticated');
	}

	const content = {
		receptionId: `diplomatic-reception:${diplomat.id}`,
		executiveDigest: executive.executiveDigest,
		receivedBy: executive.activeAuthority.holderId,
		diplomatId: diplomat.id,
		sendingState: diplomat.sendingState,
		credentialDigest: diplomat.credentialDigest,
		receivedAt: diplomat.receivedAt,
	};

	return deepFreeze({
		status: 'diplomat-received',
		...content,
		receptionDigest: digest(content),
		trace: [ARTICLE_II.rules.diplomaticReception],
	});
}

export function applyImpeachmentRemoval({ executive, subject, record }) {
	assertExecutive(executive);
	requireObject(subject, 'subject');
	requireObject(record, 'record');
	requireNonEmptyString(subject.id, 'subject.id');
	requireNonEmptyString(subject.officeKind, 'subject.officeKind');
	requireNonEmptyString(record.id, 'record.id');
	requireIsoDate(record.effectiveAt, 'record.effectiveAt');

	if (record.rootDigest !== executive.normativeRoot.digest) {
		throw new TypeError('Impeachment record belongs to another normative root');
	}

	if (
		record.authenticated !== true ||
		record.subjectId !== subject.id ||
		record.houseImpeached !== true ||
		record.senateConvicted !== true
	) {
		throw new TypeError('Removal requires authenticated impeachment and Senate conviction');
	}

	requireNonEmptyString(record.convictionGround, 'record.convictionGround');
	const content = {
		revocationId: `authority-revocation:${record.id}`,
		executiveDigest: executive.executiveDigest,
		subjectId: subject.id,
		officeKind: subject.officeKind,
		convictionGround: record.convictionGround,
		impeachmentRecordDigest: digest(record),
		effectiveAt: record.effectiveAt,
	};
	const presidentialSubject =
		subject.officeKind === 'president' && subject.id === executive.president.id;

	return deepFreeze({
		status: 'authority-revoked',
		...content,
		revocationDigest: digest(content),
		active: false,
		handoff: presidentialSubject ? 'amendment-xxv:presidential-succession' : 'office:vacancy',
		pardonAvailable: false,
		trace: [ARTICLE_II.rules.impeachmentRemoval, ARTICLE_II.rules.clemency],
	});
}

WARDEN: сто двадцять чотири сценарії виконавчої влади

Тестовий корпус статті II перевіряє сім класів інваріантів:

  1. Походження виконавчої влади. Мандат, сучасний виборчий маршрут, кваліфікації, строк, присяга, винагорода та прив’язка вхідних артефактів до нормативного root.
  2. Безперервність. Смерть, відставка, усунення, добровільна й недобровільна нездатність, оспорене відновлення та подвійна вакансія.
  3. Посадове повноваження. Заснування посади, principal та inferior routes, незалежна згода Сенату, суб’єкт призначення, комісія й тимчасовий строк.
  4. Спільні й виключні повноваження. Договори, clemency, written opinions, військове командування, відносини з Конгресом і дипломатичний прийом.
  5. Судовий handoff. Integrity judgment, збіг root, stay, endpoint, capability, точна ціль, операція та область.
  6. Матеріальне підтвердження. Дозволені кроки, зворотність, спостереження, incomplete state і immutable receipt.
  7. Відкликання повноваження. Повний record імпічменту, усунення й наступна вакансія або наступництво.

Повний тестовий файл наведено нижче:

import test from 'node:test';
import assert from 'node:assert/strict';

import {
	ARTICLE_IV,
	digest,
	federate,
	issueInterstateArtifact,
	recognizeInterstateArtifact,
} from './article-iv.mjs';

import {
	ARTICLE_III,
	closeRecord,
	constituteJudiciary,
	docketCase,
	resolve,
} from './article-iii.mjs';

import {
	ARTICLE_II,
	applyContinuityEvent,
	applyImpeachmentRemoval,
	appointOfficer,
	commandForces,
	communicateWithCongress,
	confirmExecution,
	constituteExecutive,
	execute,
	grantClemency,
	makeRecessAppointment,
	makeTreaty,
	receiveDiplomat,
	requestWrittenOpinion,
} from './article-ii.mjs';

function wardenTest(name, sourceClauses, scenario) {
	test(name, () => {
		assert.ok(Array.isArray(sourceClauses) && sourceClauses.length > 0);
		assert.ok(sourceClauses.every((source) => typeof source === 'string'));
		scenario();
	});
}

const normativeRoot = Object.freeze({
	constitutionId: 'Constitution of 1787+amendments:xii+xx+xxii+xxv',
	digest: 'sha256:root-after-article-v',
	parentDigest: 'sha256:root-before-article-v',
	amendmentDigest: 'sha256:amendment-test',
	status: 'in-force',
	lineage: Object.freeze([
		'sha256:root-before-article-v',
		'sha256:amendment:xii',
		'sha256:amendment:xx',
		'sha256:amendment:xxii',
		'sha256:amendment:xxv',
		'sha256:root-after-article-v',
	]),
});

const states = Object.freeze([
	{
		id: 'Franklin',
		constitutionDigest: 'sha256:franklin',
		admittedAt: '1788-01-01',
		republicanFormVerified: true,
	},
	{
		id: 'Hamilton',
		constitutionDigest: 'sha256:hamilton',
		admittedAt: '1788-02-01',
		republicanFormVerified: true,
	},
	{
		id: 'Madison',
		constitutionDigest: 'sha256:madison',
		admittedAt: '1788-03-01',
		republicanFormVerified: true,
	},
]);

const federation = federate({ normativeRoot, states });

const mandate = Object.freeze({
	id: 'mandate:2025',
	method: 'amendment-xii-certified-count',
	presidentElectId: 'president:ada',
	vicePresidentElectId: 'vice-president:grace',
	certificationDigest: 'sha256:certified-electoral-count-2025',
	rootDigest: normativeRoot.digest,
	authenticated: true,
});

const president = Object.freeze({
	id: 'president:ada',
	name: 'Ada',
	naturalBornCitizenDetermination: true,
	ageAtTermStart: 48,
	yearsResident: 30,
	fourteenthAmendmentEligible: true,
	priorElectionsToPresidency: 0,
	actedMoreThanTwoYearsOfAnotherTerm: false,
});

const vicePresident = Object.freeze({
	id: 'vice-president:grace',
	name: 'Grace',
	naturalBornCitizenDetermination: true,
	ageAtTermStart: 46,
	yearsResident: 28,
	fourteenthAmendmentEligible: true,
	priorElectionsToPresidency: 0,
	actedMoreThanTwoYearsOfAnotherTerm: false,
});

const term = Object.freeze({
	startsAt: '2025-01-20T17:00:00Z',
	endsAt: '2029-01-20T17:00:00Z',
	constitutionalDurationYears: 4,
	twentiethAmendmentScheduleVerified: true,
});

const oath = Object.freeze({
	officeholderId: 'president:ada',
	takenAt: '2025-01-20T17:00:00Z',
	authenticated: true,
	swornOrAffirmed: true,
	faithfullyExecute: true,
	preserveProtectDefend: true,
});

const compensation = Object.freeze({
	compensationRecordDigest: 'sha256:compensation:2025-2029',
	fixedDuringTerm: true,
	otherFederalOrStateEmolumentAccepted: false,
});

const successionPlan = Object.freeze({
	establishedByLaw: true,
	statuteDigest: 'sha256:3-usc-19-fixture',
	rootDigest: normativeRoot.digest,
	entries: Object.freeze([
		{ officerId: 'speaker:one', officeId: 'speaker-of-the-house', eligibleToAct: true },
		{
			officerId: 'president-pro-tempore:one',
			officeId: 'president-pro-tempore',
			eligibleToAct: false,
		},
		{ officerId: 'secretary:state', officeId: 'secretary-of-state', eligibleToAct: true },
	]),
});

function executiveFixture(overrides = {}) {
	return constituteExecutive({
		normativeRoot: overrides.normativeRoot ?? normativeRoot,
		federation: overrides.federation ?? federation,
		mandate: overrides.mandate ?? mandate,
		president: overrides.president ?? president,
		vicePresident: overrides.vicePresident ?? vicePresident,
		term: overrides.term ?? term,
		oath: overrides.oath ?? oath,
		compensation: overrides.compensation ?? compensation,
		successionPlan: overrides.successionPlan ?? successionPlan,
	});
}

const executive = executiveFixture();

const courts = Object.freeze([
	{
		id: 'court:district-hamilton',
		name: 'District Court for Hamilton',
		kind: 'inferior',
		tier: 1,
		articleIII: true,
		establishedBy: 'federal-statute',
		establishmentAuthenticated: true,
		originalHeads: ['federal-question'],
		appellateHeads: [],
		venueStates: ['Hamilton'],
	},
	{
		id: 'court:supreme',
		name: 'Supreme Court',
		kind: 'supreme',
		tier: 2,
		articleIII: true,
		establishedBy: 'constitution',
		establishmentAuthenticated: true,
		originalHeads: ['interstate'],
		appellateHeads: ['federal-question'],
		venueStates: [],
	},
]);

const judges = Object.freeze([
	{
		id: 'judge:district',
		courtId: 'court:district-hamilton',
		commissionAuthenticated: true,
		tenure: 'good-behaviour',
		compensationProtection: 'non-diminution',
	},
	{
		id: 'judge:supreme',
		courtId: 'court:supreme',
		commissionAuthenticated: true,
		tenure: 'good-behaviour',
		compensationProtection: 'non-diminution',
	},
]);

const judiciary = constituteJudiciary({
	normativeRoot,
	federation,
	courts,
	judges,
});

const interstateJudgment = issueInterstateArtifact({
	federation,
	issuerState: 'Franklin',
	id: 'judgment:franklin:42',
	artifactClass: 'final-judgment',
	revision: 'r1',
	issuedAt: '2026-08-09',
	issuingAuthority: 'Franklin Superior Court',
	authorityScope: 'civil-money-judgment',
	final: true,
	stayed: false,
	payload: { debtor: 'Ada', creditor: 'Grace', amount: 500 },
	effectAtOrigin: 'enforce-money-judgment',
});

const unresolvedArticleIV = recognizeInterstateArtifact({
	federation,
	receivingState: 'Hamilton',
	artifact: interstateJudgment,
	proof: {
		authenticated: true,
		integrityDigest: interstateJudgment.digest,
		revisionVerified: true,
		originCompetenceVerified: true,
	},
	requestedEffect: 'imprison-debtor',
});

const docket = docketCase({
	judiciary,
	sourceResult: unresolvedArticleIV,
	petition: {
		id: 'grace-v-hamilton',
		filedAt: '2026-08-09',
		courtId: 'court:district-hamilton',
		jurisdictionHead: 'federal-question',
		plaintiff: { id: 'Grace', kind: 'natural-person', state: 'Franklin' },
		defendant: {
			id: 'Hamilton Enforcement Office',
			kind: 'state-agency',
			state: 'Hamilton',
		},
		claim: 'Article IV permits only the effect attached to the judgment at origin',
		requestedRelief: {
			type: 'declaratory-and-injunctive',
			operation: 'limit-local-execution-to-origin-effect',
		},
		caseOrControversy: {
			adverseParties: true,
			injuryInFact: true,
			causation: true,
			redressability: true,
			ripe: true,
			live: true,
			politicalQuestionPotential: false,
		},
	},
});

const record = closeRecord({
	judiciary,
	docket,
	closedAt: '2026-08-10',
	factFinder: { id: 'judge:district', kind: 'judge', authorityVerified: true },
	evidence: [
		{
			id: 'evidence:origin-judgment',
			kind: 'authenticated-judicial-record',
			authenticated: true,
			admitted: true,
			propositions: ['the origin judgment authorizes a money judgment'],
		},
		{
			id: 'evidence:requested-effect',
			kind: 'stipulation',
			authenticated: true,
			admitted: true,
			propositions: ['Hamilton requested imprisonment as the receiving effect'],
		},
	],
	findings: [
		{
			id: 'finding:origin-effect',
			proposition: 'The origin effect is enforcement of a money judgment',
			supportedBy: ['evidence:origin-judgment'],
		},
		{
			id: 'finding:requested-effect',
			proposition: 'Hamilton requested imprisonment',
			supportedBy: ['evidence:requested-effect'],
		},
	],
});

const judgment = resolve({
	judiciary,
	docket,
	record,
	authorities: [
		{
			id: 'authority:article-iv',
			kind: 'constitution',
			citation: 'U.S. Const. art. IV, sec. 1',
			rootDigest: normativeRoot.digest,
			status: 'in-force',
			authorityVerified: true,
			displacedBy: [],
		},
		{
			id: 'authority:28-usc-1738',
			kind: 'federal-statute',
			citation: '28 U.S.C. § 1738',
			status: 'in-force',
			authorityVerified: true,
			madeInPursuanceVerified: true,
			displacedBy: [],
		},
	],
	decision: {
		decidedAt: '2026-08-11',
		disposition: 'grant-relief',
		holdings: [
			{
				id: 'holding:same-effect',
				issue: "May the receiving state enlarge the origin judgment's effect?",
				conclusion: 'A money judgment may not become imprisonment',
				scope: 'This authenticated judgment and requested receiving effect',
				authorityIds: ['authority:article-iv', 'authority:28-usc-1738'],
				findingIds: ['finding:origin-effect', 'finding:requested-effect'],
			},
		],
		remedy: {
			type: 'injunction',
			target: 'Hamilton Enforcement Office',
			operation: 'limit-execution-to-enforce-money-judgment',
			scope: 'judgment:franklin:42',
			executableBy: 'article-ii:marshal-service',
			redressesInjury: true,
			leastScopeVerified: true,
			reversibleUntilFinal: true,
		},
	},
});

const marshalOffice = Object.freeze({
	id: 'office:marshal-hamilton',
	name: 'United States Marshal for Hamilton',
	classification: 'principal',
	establishedByLaw: true,
	establishmentDigest: 'sha256:marshal-office-statute',
	establishmentRootDigest: normativeRoot.digest,
	departmentId: 'justice',
	executionEndpoint: 'article-ii:marshal-service',
	capabilities: ['execute-federal-judgment', 'serve-federal-process'],
});

const marshalCandidate = Object.freeze({
	id: 'officer:marshal-hamilton',
	name: 'Lin',
	eligibilityVerified: true,
	conflictReviewDigest: 'sha256:marshal-conflict-review',
});

const nomination = Object.freeze({
	authenticated: true,
	officeId: marshalOffice.id,
	candidateId: marshalCandidate.id,
	nominatedBy: president.id,
});

const appointmentConsent = Object.freeze({
	authenticated: true,
	approved: true,
	quorumVerified: true,
	officeId: marshalOffice.id,
	candidateId: marshalCandidate.id,
	recordDigest: 'sha256:senate-consent-marshal',
});

const appointment = Object.freeze({
	id: 'appointment:marshal-hamilton',
	actorKind: 'president',
	actorId: president.id,
	officeId: marshalOffice.id,
	candidateId: marshalCandidate.id,
	appointedAt: '2025-02-01T12:00:00Z',
	authenticated: true,
});

const commission = Object.freeze({
	id: 'commission:marshal-hamilton',
	signedBy: president.id,
	officeId: marshalOffice.id,
	candidateId: marshalCandidate.id,
	issuedAt: '2025-02-01T12:05:00Z',
	authenticated: true,
});

function appointedOfficer(overrides = {}) {
	return appointOfficer({
		executive: overrides.executive ?? executive,
		office: overrides.office ?? marshalOffice,
		candidate: overrides.candidate ?? marshalCandidate,
		nomination: overrides.nomination ?? nomination,
		senateConsent: overrides.senateConsent ?? appointmentConsent,
		appointment: overrides.appointment ?? appointment,
		commission: overrides.commission ?? commission,
	});
}

const marshal = appointedOfficer();

function executionPlan(overrides = {}) {
	return {
		id: 'plan:grace-v-hamilton',
		preparedAt: '2026-08-12T09:00:00Z',
		sourceJudgmentDigest: judgment.judgmentDigest,
		target: judgment.remedy.target,
		operation: judgment.remedy.operation,
		scope: judgment.remedy.scope,
		noAdditionalSanction: true,
		leastForceVerified: true,
		appropriationVerified: true,
		steps: [
			{
				id: 'step:serve-order',
				action: 'serve-certified-injunction',
				target: judgment.remedy.target,
				scope: judgment.remedy.scope,
				expectedEffect: 'enforcement office receives the bounded order',
				withinRemedy: true,
				reversible: true,
			},
			{
				id: 'step:disable-imprisonment-route',
				action: 'disable-enlarged-enforcement-route',
				target: judgment.remedy.target,
				scope: judgment.remedy.scope,
				expectedEffect: 'imprisonment is unavailable for this judgment',
				withinRemedy: true,
				reversible: true,
			},
		],
		...overrides,
	};
}

function executionOrder(overrides = {}) {
	return execute({
		executive: overrides.executive ?? executive,
		judgment: overrides.judgment ?? judgment,
		officer: overrides.officer ?? marshal,
		plan: overrides.plan ?? executionPlan(),
	});
}

function successfulObservations(order = executionOrder()) {
	return order.steps.map((step) => ({
		stepId: step.id,
		authenticated: true,
		completed: true,
		observedEffect: step.expectedEffect,
	}));
}

wardenTest(
	'constituteExecutive binds one active President to the current root and federation',
	[ARTICLE_II.rules.vesting, ARTICLE_II.engineering.mandateNotSelfAsserted],
	() => {
		assert.equal(executive.status, 'executive-constituted');
		assert.equal(executive.normativeRoot.digest, normativeRoot.digest);
		assert.equal(executive.federationId, federation.federationId);
		assert.equal(executive.activeAuthority.holderId, president.id);
	},
);

wardenTest(
	'constituted executive is deeply immutable',
	[ARTICLE_II.engineering.continuityLineage],
	() => {
		assert.equal(Object.isFrozen(executive), true);
		assert.equal(Object.isFrozen(executive.activeAuthority), true);
		assert.throws(() => executive.capabilities.push('rule-by-decree'));
	},
);

wardenTest(
	'an executive cannot bind itself to a federation from another root',
	[ARTICLE_II.rules.vesting],
	() => {
		assert.throws(
			() => executiveFixture({ normativeRoot: { ...normativeRoot, digest: 'sha256:other' } }),
			/same normative root/,
		);
	},
);

wardenTest(
	'an out-of-force root cannot constitute the executive',
	[ARTICLE_II.engineering.mandateNotSelfAsserted],
	() => {
		assert.throws(
			() => executiveFixture({ normativeRoot: { ...normativeRoot, status: 'superseded' } }),
			/in force/,
		);
	},
);

wardenTest(
	'a mandate requires authentication',
	[ARTICLE_II.rules.electionAndEligibility, ARTICLE_II.amendments.twelfth],
	() => {
		assert.throws(
			() => executiveFixture({ mandate: { ...mandate, authenticated: false } }),
			/must be authenticated/,
		);
	},
);

wardenTest(
	'an authenticated mandate from another root cannot activate this executive',
	[ARTICLE_II.engineering.mandateNotSelfAsserted],
	() => {
		assert.throws(
			() => executiveFixture({ mandate: { ...mandate, rootDigest: 'sha256:other-root' } }),
			/mandate belongs to another normative root/,
		);
	},
);

wardenTest(
	'the superseded original joint ballot cannot masquerade as the current mandate route',
	[ARTICLE_II.amendments.twelfth],
	() => {
		assert.throws(
			() => executiveFixture({ mandate: { ...mandate, method: 'original-two-person-ballot' } }),
			/current constitutional election route/,
		);
	},
);

wardenTest(
	'mandate must name the President who is about to execute the office',
	[ARTICLE_II.engineering.mandateNotSelfAsserted],
	() => {
		assert.throws(
			() => executiveFixture({ mandate: { ...mandate, presidentElectId: 'president:other' } }),
			/another President-elect/,
		);
	},
);

wardenTest(
	'mandate must name the paired Vice-President-elect',
	[ARTICLE_II.amendments.twelfth],
	() => {
		assert.throws(
			() => executiveFixture({ mandate: { ...mandate, vicePresidentElectId: 'vice:other' } }),
			/another Vice-President-elect/,
		);
	},
);

const presidentialQualificationFailures = [
	[
		'a missing natural-born-citizen determination blocks activation',
		{ naturalBornCitizenDetermination: false },
		/natural-born-citizen/,
	],
	[
		'a thirty-four-year-old candidate cannot enter the office',
		{ ageAtTermStart: 34 },
		/thirty-five/,
	],
	['thirteen years of residence do not satisfy Article II', { yearsResident: 13 }, /fourteen/],
	[
		'an unresolved Fourteenth Amendment disqualification blocks activation',
		{ fourteenthAmendmentEligible: false },
		/Fourteenth Amendment/,
	],
	[
		'two prior elections bar another presidential election',
		{ priorElectionsToPresidency: 2 },
		/Amendment XXII/,
	],
	[
		'more than two years of another term plus one election bars another election',
		{ priorElectionsToPresidency: 1, actedMoreThanTwoYearsOfAnotherTerm: true },
		/Amendment XXII/,
	],
];

for (const [name, mutation, pattern] of presidentialQualificationFailures) {
	wardenTest(name, [ARTICLE_II.rules.electionAndEligibility], () => {
		assert.throws(() => executiveFixture({ president: { ...president, ...mutation } }), pattern);
	});
}

wardenTest(
	'Vice President must independently satisfy presidential baseline qualifications',
	[ARTICLE_II.amendments.twelfth, ARTICLE_II.rules.electionAndEligibility],
	() => {
		assert.throws(
			() => executiveFixture({ vicePresident: { ...vicePresident, ageAtTermStart: 30 } }),
			/thirty-five/,
		);
	},
);

wardenTest(
	'Article II term input is four years',
	[ARTICLE_II.rules.vesting, ARTICLE_II.amendments.twentieth],
	() => {
		assert.throws(
			() => executiveFixture({ term: { ...term, constitutionalDurationYears: 5 } }),
			/four years/,
		);
	},
);

wardenTest(
	'modern term schedule requires an Amendment XX determination',
	[ARTICLE_II.amendments.twentieth],
	() => {
		assert.throws(
			() => executiveFixture({ term: { ...term, twentiethAmendmentScheduleVerified: false } }),
			/Amendment XX schedule/,
		);
	},
);

wardenTest('oath must belong to the officeholder', [ARTICLE_II.rules.oath], () => {
	assert.throws(
		() => executiveFixture({ oath: { ...oath, officeholderId: 'president:other' } }),
		/for the officeholder/,
	);
});

wardenTest('oath must contain faithful execution', [ARTICLE_II.rules.oath], () => {
	assert.throws(
		() => executiveFixture({ oath: { ...oath, faithfullyExecute: false } }),
		/lacks the Article II commitments/,
	);
});

wardenTest(
	'oath must contain preservation, protection, and defense of the Constitution',
	[ARTICLE_II.rules.oath],
	() => {
		assert.throws(
			() => executiveFixture({ oath: { ...oath, preserveProtectDefend: false } }),
			/lacks the Article II commitments/,
		);
	},
);

wardenTest(
	'the model does not activate an oath before the term starts',
	[ARTICLE_II.rules.oath, ARTICLE_II.amendments.twentieth],
	() => {
		assert.throws(
			() => executiveFixture({ oath: { ...oath, takenAt: '2025-01-19T17:00:00Z' } }),
			/only after the term begins/,
		);
	},
);

wardenTest(
	'presidential compensation must remain fixed during the term',
	[ARTICLE_II.rules.compensation],
	() => {
		assert.throws(
			() => executiveFixture({ compensation: { ...compensation, fixedDuringTerm: false } }),
			/remain fixed/,
		);
	},
);

wardenTest(
	'another federal or state emolument blocks the executive snapshot',
	[ARTICLE_II.rules.compensation],
	() => {
		assert.throws(
			() =>
				executiveFixture({
					compensation: { ...compensation, otherFederalOrStateEmolumentAccepted: true },
				}),
			/may not accept/,
		);
	},
);

wardenTest(
	'a statutory succession plan is required for dual vacancy',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		assert.throws(
			() => executiveFixture({ successionPlan: { ...successionPlan, establishedByLaw: false } }),
			/established by law/,
		);
	},
);

wardenTest(
	'succession plan from another root cannot control current continuity',
	[ARTICLE_II.engineering.continuityLineage],
	() => {
		assert.throws(
			() =>
				executiveFixture({
					successionPlan: { ...successionPlan, rootDigest: 'sha256:other-root' },
				}),
			/Succession plan belongs to another normative root/,
		);
	},
);

function continuityEvent(overrides = {}) {
	return {
		id: 'continuity:event',
		kind: 'death',
		subjectId: president.id,
		effectiveAt: '2026-08-12T12:00:00Z',
		evidenceDigest: 'sha256:continuity-evidence',
		authenticated: true,
		...overrides,
	};
}

for (const kind of ['death', 'resignation', 'impeachment-removal']) {
	wardenTest(
		`${kind} makes the Vice President President under Amendment XXV section 1`,
		[ARTICLE_II.amendments.twentyFifth],
		() => {
			const next = applyContinuityEvent({ executive, event: continuityEvent({ kind }) });
			assert.equal(next.activeAuthority.holderId, vicePresident.id);
			assert.equal(next.activeAuthority.role, 'president');
			assert.equal(next.parentExecutiveDigest, executive.executiveDigest);
		},
	);
}

wardenTest(
	'an unauthenticated continuity event cannot move presidential authority',
	[ARTICLE_II.engineering.continuityLineage],
	() => {
		assert.throws(
			() =>
				applyContinuityEvent({
					executive,
					event: continuityEvent({ authenticated: false }),
				}),
			/must be authenticated/,
		);
	},
);

wardenTest(
	'voluntary inability transfers powers to an Acting President',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		const next = applyContinuityEvent({
			executive,
			event: continuityEvent({
				kind: 'voluntary-inability',
				declarantId: president.id,
				recipients: ['speaker-of-the-house', 'president-pro-tempore'],
			}),
		});
		assert.equal(next.activeAuthority.role, 'acting-president');
		assert.equal(next.activeAuthority.mode, 'voluntary-inability');
	},
);

wardenTest(
	'voluntary inability declaration must reach both constitutional recipients',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		assert.throws(
			() =>
				applyContinuityEvent({
					executive,
					event: continuityEvent({
						kind: 'voluntary-inability',
						declarantId: president.id,
						recipients: ['speaker-of-the-house'],
					}),
				}),
			/both constitutional recipients/,
		);
	},
);

wardenTest(
	'involuntary inability requires the Vice President and a majority of principal officers',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		const next = applyContinuityEvent({
			executive,
			event: continuityEvent({
				kind: 'involuntary-inability',
				recipients: ['speaker-of-the-house', 'president-pro-tempore'],
				vicePresidentJoined: true,
				principalOfficersTotal: 5,
				concurringPrincipalOfficerIds: ['officer:1', 'officer:2', 'officer:3'],
			}),
		});
		assert.equal(next.activeAuthority.mode, 'involuntary-inability');
	},
);

wardenTest(
	'two of five principal officers do not establish involuntary inability',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		assert.throws(
			() =>
				applyContinuityEvent({
					executive,
					event: continuityEvent({
						kind: 'involuntary-inability',
						recipients: ['speaker-of-the-house', 'president-pro-tempore'],
						vicePresidentJoined: true,
						principalOfficersTotal: 5,
						concurringPrincipalOfficerIds: ['officer:1', 'officer:2'],
					}),
				}),
			/lacks a majority/,
		);
	},
);

wardenTest(
	'the President resumes authority after an unchallenged recovery declaration',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		const next = applyContinuityEvent({
			executive,
			event: continuityEvent({
				kind: 'presidential-recovery',
				declarantId: president.id,
				recipients: ['speaker-of-the-house', 'president-pro-tempore'],
				challengeWithinFourDays: false,
			}),
		});
		assert.equal(next.activeAuthority.holderId, president.id);
		assert.equal(next.activeAuthority.mode, 'presidential-authority-resumed');
	},
);

wardenTest(
	'two-thirds of both Houses may sustain inability after a contested recovery',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		const next = applyContinuityEvent({
			executive,
			event: continuityEvent({
				kind: 'presidential-recovery',
				declarantId: president.id,
				recipients: ['speaker-of-the-house', 'president-pro-tempore'],
				challengeWithinFourDays: true,
				congressionalDecision: {
					authenticated: true,
					houseTwoThirds: true,
					senateTwoThirds: true,
					withinTwentyOneDays: true,
				},
			}),
		});
		assert.equal(next.activeAuthority.holderId, vicePresident.id);
		assert.equal(next.activeAuthority.mode, 'inability-sustained-by-congress');
	},
);

wardenTest(
	'failure of either congressional threshold restores presidential authority',
	[ARTICLE_II.amendments.twentyFifth],
	() => {
		const next = applyContinuityEvent({
			executive,
			event: continuityEvent({
				kind: 'presidential-recovery',
				declarantId: president.id,
				recipients: ['speaker-of-the-house', 'president-pro-tempore'],
				challengeWithinFourDays: true,
				congressionalDecision: {
					authenticated: true,
					houseTwoThirds: true,
					senateTwoThirds: false,
					withinTwentyOneDays: true,
				},
			}),
		});
		assert.equal(next.activeAuthority.holderId, president.id);
	},
);

wardenTest(
	'dual vacancy activates the first eligible statutory successor',
	[ARTICLE_II.rules.succession, ARTICLE_II.engineering.continuityLineage],
	() => {
		const next = applyContinuityEvent({
			executive,
			event: continuityEvent({ kind: 'dual-vacancy', successorId: 'speaker:one' }),
		});
		assert.equal(next.activeAuthority.holderId, 'speaker:one');
		assert.equal(next.activeAuthority.role, 'acting-president');
	},
);

wardenTest(
	'dual vacancy cannot skip an earlier eligible successor',
	[ARTICLE_II.engineering.continuityLineage],
	() => {
		assert.throws(
			() =>
				applyContinuityEvent({
					executive,
					event: continuityEvent({ kind: 'dual-vacancy', successorId: 'secretary:state' }),
				}),
			/skipped an earlier eligible successor/,
		);
	},
);

wardenTest(
	'principal officer is nominated, confirmed, appointed, and separately commissioned',
	[ARTICLE_II.rules.appointments, ARTICLE_II.rules.commissions],
	() => {
		assert.equal(marshal.status, 'officer-commissioned');
		assert.equal(marshal.appointmentPath, 'president-with-senate-consent');
		assert.equal(marshal.commission.officeId, marshalOffice.id);
	},
);

wardenTest(
	'commissioned officer is deeply immutable',
	[ARTICLE_II.engineering.boundedCapabilities],
	() => {
		assert.equal(Object.isFrozen(marshal), true);
		assert.throws(() => marshal.office.capabilities.push('rewrite-judgment'));
	},
);

wardenTest(
	'an office must exist by law before appointment',
	[ARTICLE_II.rules.appointments],
	() => {
		assert.throws(
			() => appointedOfficer({ office: { ...marshalOffice, establishedByLaw: false } }),
			/must exist by authenticated law/,
		);
	},
);

wardenTest(
	'an office established under another root cannot receive current authority',
	[ARTICLE_II.rules.appointments, ARTICLE_II.engineering.boundedCapabilities],
	() => {
		assert.throws(
			() =>
				appointedOfficer({
					office: { ...marshalOffice, establishmentRootDigest: 'sha256:other-root' },
				}),
			/another normative root/,
		);
	},
);

wardenTest(
	'candidate requires an eligibility determination',
	[ARTICLE_II.rules.appointments],
	() => {
		assert.throws(
			() => appointedOfficer({ candidate: { ...marshalCandidate, eligibilityVerified: false } }),
			/lacks an eligibility determination/,
		);
	},
);

wardenTest(
	'principal appointment requires a matching nomination',
	[ARTICLE_II.rules.appointments],
	() => {
		assert.throws(
			() => appointedOfficer({ nomination: { ...nomination, candidateId: 'candidate:other' } }),
			/nomination is absent or mismatched/,
		);
	},
);

wardenTest(
	'a self-nominating stranger cannot use the President field',
	[ARTICLE_II.engineering.mandateNotSelfAsserted],
	() => {
		assert.throws(
			() =>
				appointedOfficer({ nomination: { ...nomination, nominatedBy: 'president:self-declared' } }),
			/active presidential authority holder/,
		);
	},
);

wardenTest(
	'principal appointment requires authenticated Senate consent',
	[ARTICLE_II.rules.appointments, ARTICLE_II.engineering.safeSharedPower],
	() => {
		assert.throws(
			() => appointedOfficer({ senateConsent: { ...appointmentConsent, approved: false } }),
			/lacks authenticated Senate advice and consent/,
		);
	},
);

wardenTest(
	'principal appointment cannot be completed by a department head',
	[ARTICLE_II.rules.appointments],
	() => {
		assert.throws(
			() =>
				appointedOfficer({
					appointment: {
						...appointment,
						actorKind: 'department-head',
						actorId: 'attorney-general',
					},
				}),
			/appointed by the active President/,
		);
	},
);

function inferiorOffice(overrides = {}) {
	return {
		id: 'office:inferior',
		name: 'Inferior Executive Officer',
		classification: 'inferior',
		establishedByLaw: true,
		establishmentDigest: 'sha256:inferior-office',
		establishmentRootDigest: normativeRoot.digest,
		appointmentVestedIn: 'president-alone',
		appointmentVestingAuthenticated: true,
		departmentId: 'justice',
		courtId: 'court:district-hamilton',
		executionEndpoint: 'article-ii:inferior-service',
		capabilities: ['execute-federal-law'],
		...overrides,
	};
}

function inferiorAppointment(options = {}) {
	const office = options.office ?? inferiorOffice();
	const candidate = options.candidate ?? {
		id: 'candidate:inferior',
		eligibilityVerified: true,
	};
	const actorKind = options.actorKind ?? office.appointmentVestedIn;
	const actorId =
		options.actorId ??
		(actorKind === 'president-alone'
			? president.id
			: actorKind === 'department-head'
				? 'officer:department-head'
				: 'court:district-hamilton');
	return appointOfficer({
		executive,
		office,
		candidate,
		appointment: {
			id: 'appointment:inferior',
			actorKind,
			actorId,
			actorAuthorityVerified: actorKind !== 'president-alone',
			actorDepartmentId: options.actorDepartmentId ?? office.departmentId,
			actorCourtId: options.actorCourtId ?? office.courtId,
			officeId: office.id,
			candidateId: candidate.id,
			appointedAt: '2025-03-01T12:00:00Z',
			authenticated: true,
		},
		commission: {
			id: 'commission:inferior',
			signedBy: president.id,
			officeId: office.id,
			candidateId: candidate.id,
			issuedAt: '2025-03-01T12:05:00Z',
			authenticated: true,
		},
	});
}

for (const actorKind of ['president-alone', 'department-head', 'court-of-law']) {
	wardenTest(
		`Congress may vest an inferior appointment in ${actorKind}`,
		[ARTICLE_II.rules.appointments, ARTICLE_II.doctrine.appointmentClasses],
		() => {
			const officer = inferiorAppointment({
				office: inferiorOffice({ appointmentVestedIn: actorKind }),
				actorKind,
			});
			assert.equal(officer.appointmentPath, `inferior:${actorKind}`);
		},
	);
}

wardenTest(
	'inferior office may retain the default President-and-Senate appointment route',
	[ARTICLE_II.rules.appointments, ARTICLE_II.doctrine.appointmentClasses],
	() => {
		const office = inferiorOffice({ appointmentVestedIn: 'president-with-senate-consent' });
		const candidate = { id: 'candidate:inferior-default', eligibilityVerified: true };
		const officer = appointOfficer({
			executive,
			office,
			candidate,
			nomination: {
				authenticated: true,
				officeId: office.id,
				candidateId: candidate.id,
				nominatedBy: president.id,
			},
			senateConsent: {
				authenticated: true,
				approved: true,
				quorumVerified: true,
				officeId: office.id,
				candidateId: candidate.id,
			},
			appointment: {
				id: 'appointment:inferior-default',
				actorKind: 'president',
				actorId: president.id,
				officeId: office.id,
				candidateId: candidate.id,
				appointedAt: '2025-03-02T12:00:00Z',
				authenticated: true,
			},
			commission: {
				id: 'commission:inferior-default',
				signedBy: president.id,
				officeId: office.id,
				candidateId: candidate.id,
				issuedAt: '2025-03-02T12:05:00Z',
				authenticated: true,
			},
		});
		assert.equal(officer.appointmentPath, 'inferior:president-with-senate-consent');
	},
);

wardenTest(
	'inferior officer cannot be appointed by an actor outside the statutory vesting',
	[ARTICLE_II.rules.appointments],
	() => {
		assert.throws(
			() =>
				inferiorAppointment({
					office: inferiorOffice({ appointmentVestedIn: 'department-head' }),
					actorKind: 'court-of-law',
				}),
			/outside the statutory vesting/,
		);
	},
);

wardenTest(
	'department head cannot appoint into another department',
	[ARTICLE_II.rules.appointments],
	() => {
		assert.throws(
			() =>
				inferiorAppointment({
					office: inferiorOffice({ appointmentVestedIn: 'department-head' }),
					actorKind: 'department-head',
					actorDepartmentId: 'treasury',
				}),
			/another department/,
		);
	},
);

wardenTest(
	'court appointment remains inside the authenticated court vesting',
	[ARTICLE_II.rules.appointments],
	() => {
		assert.throws(
			() =>
				inferiorAppointment({
					office: inferiorOffice({ appointmentVestedIn: 'court-of-law' }),
					actorKind: 'court-of-law',
					actorCourtId: 'court:other',
				}),
			/outside the authenticated vesting/,
		);
	},
);

wardenTest(
	'commission must match the appointed candidate and office',
	[ARTICLE_II.rules.commissions],
	() => {
		assert.throws(
			() => appointedOfficer({ commission: { ...commission, candidateId: 'candidate:other' } }),
			/does not match/,
		);
	},
);

wardenTest(
	'commission must be signed by the active presidential authority holder',
	[ARTICLE_II.rules.commissions],
	() => {
		assert.throws(
			() => appointedOfficer({ commission: { ...commission, signedBy: 'former-president' } }),
			/active presidential authority holder/,
		);
	},
);

function recessInputs(overrides = {}) {
	const office = overrides.office ?? marshalOffice;
	const candidate = overrides.candidate ?? marshalCandidate;
	return {
		executive,
		office,
		candidate,
		senateState: {
			authenticated: true,
			senateSelfReportsInSession: false,
			canTransactBusiness: false,
			recessStartedAt: '2026-08-01T00:00:00Z',
			recessScheduledEndAt: '2026-08-20T00:00:00Z',
			recessDurationDays: 19,
			nextSessionEndsAt: '2027-12-20T00:00:00Z',
			...overrides.senateState,
		},
		appointment: {
			id: 'appointment:recess',
			actorId: president.id,
			officeId: office.id,
			candidateId: candidate.id,
			appointedAt: '2026-08-05T00:00:00Z',
			authenticated: true,
			...overrides.appointment,
		},
		commission: {
			...commission,
			id: 'commission:recess',
			issuedAt: '2026-08-05T00:05:00Z',
			...overrides.commission,
		},
	};
}

wardenTest(
	"a valid recess commission expires at the end of the Senate's next session",
	[ARTICLE_II.rules.recessAppointments],
	() => {
		const officer = makeRecessAppointment(recessInputs());
		assert.equal(officer.temporary, true);
		assert.equal(officer.expiresAt, '2027-12-20T00:00:00Z');
	},
);

wardenTest(
	"the Senate's authenticated in-session state blocks a recess appointment",
	[ARTICLE_II.doctrine.senateSession],
	() => {
		assert.throws(
			() =>
				makeRecessAppointment(recessInputs({ senateState: { senateSelfReportsInSession: true } })),
			/constitutionally in session/,
		);
	},
);

wardenTest(
	'the conservative model rejects a recess shorter than ten days',
	[ARTICLE_II.rules.recessAppointments, ARTICLE_II.doctrine.senateSession],
	() => {
		assert.throws(
			() => makeRecessAppointment(recessInputs({ senateState: { recessDurationDays: 5 } })),
			/shorter than ten days/,
		);
	},
);

function treatyInstrument(overrides = {}) {
	return {
		id: 'treaty:shared-infrastructure',
		textDigest: 'sha256:treaty-text',
		rootDigest: normativeRoot.digest,
		negotiatedBy: president.id,
		authenticated: true,
		underAuthorityVerified: true,
		constitutionalCompatibilityDetermined: true,
		domesticEffect: 'self-executing',
		...overrides,
	};
}

function treatyConsent(overrides = {}) {
	return {
		authenticated: true,
		instrumentId: 'treaty:shared-infrastructure',
		quorumVerified: true,
		senatorsPresent: 90,
		yeas: 60,
		nays: 30,
		recordDigest: 'sha256:treaty-consent',
		...overrides,
	};
}

wardenTest(
	'exactly two thirds of Senators present can consent to a treaty',
	[ARTICLE_II.rules.treaties],
	() => {
		const result = makeTreaty({
			executive,
			instrument: treatyInstrument(),
			senateConsent: treatyConsent(),
		});
		assert.equal(result.status, 'treaty-made');
		assert.equal(result.requiredYeas, 60);
	},
);

wardenTest(
	'one vote below two thirds leaves the treaty unmade',
	[ARTICLE_II.rules.treaties, ARTICLE_II.engineering.safeSharedPower],
	() => {
		const result = makeTreaty({
			executive,
			instrument: treatyInstrument(),
			senateConsent: treatyConsent({ yeas: 59 }),
		});
		assert.equal(result.status, 'treaty-not-made');
	},
);

wardenTest(
	'treaty instrument must be attributed to the active President',
	[ARTICLE_II.rules.treaties],
	() => {
		assert.throws(
			() =>
				makeTreaty({
					executive,
					instrument: treatyInstrument({ negotiatedBy: 'private-negotiator' }),
					senateConsent: treatyConsent(),
				}),
			/presidential attribution/,
		);
	},
);

wardenTest(
	'treaty instrument from another root cannot enter the current treaty route',
	[ARTICLE_II.rules.treaties],
	() => {
		assert.throws(
			() =>
				makeTreaty({
					executive,
					instrument: treatyInstrument({ rootDigest: 'sha256:other-root' }),
					senateConsent: treatyConsent(),
				}),
			/Treaty instrument belongs to another normative root/,
		);
	},
);

wardenTest(
	'Senate consent must refer to the same treaty instrument',
	[ARTICLE_II.engineering.safeSharedPower],
	() => {
		assert.throws(
			() =>
				makeTreaty({
					executive,
					instrument: treatyInstrument(),
					senateConsent: treatyConsent({ instrumentId: 'treaty:other' }),
				}),
			/lacks authenticated Senate advice and consent/,
		);
	},
);

wardenTest(
	'self-executing treaty returns to the Article VI registry',
	[ARTICLE_II.rules.treaties, ARTICLE_II.doctrine.treatyEffect],
	() => {
		const result = makeTreaty({
			executive,
			instrument: treatyInstrument(),
			senateConsent: treatyConsent(),
		});
		assert.equal(result.handoff, 'article-vi:register-treaty');
	},
);

wardenTest(
	'non-self-executing treaty requests implementing legislation',
	[ARTICLE_II.doctrine.treatyEffect],
	() => {
		const result = makeTreaty({
			executive,
			instrument: treatyInstrument({ domesticEffect: 'requires-implementing-legislation' }),
			senateConsent: treatyConsent(),
		});
		assert.equal(result.handoff, 'article-i:implementing-legislation');
	},
);

function clemencyRequest(overrides = {}) {
	return {
		id: 'request:clemency:1',
		kind: 'pardon',
		recipientId: 'person:one',
		offenseId: 'federal-offense:1',
		offenseSovereign: 'united-states',
		proceedingKind: 'criminal',
		criminalEffect: 'forgive-federal-criminal-consequence',
		authenticated: true,
		selfDirected: false,
		...overrides,
	};
}

for (const kind of ['pardon', 'reprieve', 'commutation']) {
	wardenTest(
		`${kind} may issue for an authenticated federal offense`,
		[ARTICLE_II.rules.clemency],
		() => {
			const result = grantClemency({ executive, request: clemencyRequest({ kind }) });
			assert.equal(result.status, 'clemency-issued');
			assert.equal(result.kind, kind);
		},
	);
}

wardenTest(
	'federal clemency does not silently erase independent civil effects',
	[ARTICLE_II.doctrine.pardonBoundary],
	() => {
		const result = grantClemency({ executive, request: clemencyRequest() });
		assert.equal(result.civilEffect, 'unchanged-unless-independently-authorized');
	},
);

wardenTest(
	'state offense lies outside presidential clemency power',
	[ARTICLE_II.rules.clemency],
	() => {
		const result = grantClemency({
			executive,
			request: clemencyRequest({ offenseSovereign: 'Hamilton' }),
		});
		assert.equal(result.reason, 'outside-federal-offense-power');
	},
);

wardenTest(
	'impeachment cannot be pardoned',
	[ARTICLE_II.rules.clemency, ARTICLE_II.rules.impeachmentRemoval],
	() => {
		const result = grantClemency({
			executive,
			request: clemencyRequest({ proceedingKind: 'impeachment' }),
		});
		assert.equal(result.reason, 'impeachment-exception');
	},
);

wardenTest(
	'self-directed clemency is routed to constitutional determination',
	[ARTICLE_II.doctrine.pardonBoundary, ARTICLE_II.engineering.wardenBoundary],
	() => {
		const result = grantClemency({
			executive,
			request: clemencyRequest({ recipientId: president.id, selfDirected: true }),
		});
		assert.equal(result.status, 'requires-constitutional-determination');
		assert.equal(result.handoff, 'article-iii:resolve');
	},
);

wardenTest(
	'written opinion request reaches a principal department officer',
	[ARTICLE_II.rules.writtenOpinions],
	() => {
		const result = requestWrittenOpinion({
			executive,
			principalOfficer: {
				officerId: 'secretary:state',
				departmentId: 'state',
				classification: 'principal',
				active: true,
				authorityVerified: true,
			},
			subject: {
				id: 'subject:treaty',
				departmentId: 'state',
				question: 'What obligations are presently due?',
				relatesToDepartmentDuties: true,
			},
		});
		assert.equal(result.status, 'written-opinion-requested');
		assert.equal(result.opinion, 'not-manufactured-by-request');
	},
);

wardenTest(
	'an inferior officer is not the Article II written-opinion endpoint',
	[ARTICLE_II.rules.writtenOpinions],
	() => {
		assert.throws(
			() =>
				requestWrittenOpinion({
					executive,
					principalOfficer: {
						officerId: 'assistant:one',
						departmentId: 'state',
						classification: 'inferior',
						active: true,
						authorityVerified: true,
					},
					subject: {
						id: 'subject:one',
						departmentId: 'state',
						question: 'Question',
						relatesToDepartmentDuties: true,
					},
				}),
			/only from a verified principal/,
		);
	},
);

wardenTest(
	'written opinion request cannot escape departmental duties',
	[ARTICLE_II.rules.writtenOpinions, ARTICLE_II.engineering.boundedCapabilities],
	() => {
		assert.throws(
			() =>
				requestWrittenOpinion({
					executive,
					principalOfficer: {
						officerId: 'secretary:state',
						departmentId: 'state',
						classification: 'principal',
						active: true,
						authorityVerified: true,
					},
					subject: {
						id: 'subject:treasury',
						departmentId: 'treasury',
						question: 'Change the tax ledger',
						relatesToDepartmentDuties: false,
					},
				}),
			/outside the officer's departmental duties/,
		);
	},
);

function militaryOrder(overrides = {}) {
	return {
		id: 'order:defense:1',
		issuedBy: president.id,
		authenticated: true,
		force: 'army',
		operation: 'defend-federal-facility',
		scope: 'facility:one',
		lawOfArmedConflictReviewVerified: true,
		appropriationVerified: true,
		...overrides,
	};
}

function militaryAuthorization(overrides = {}) {
	return {
		kind: 'congress-authorized',
		authenticated: true,
		statuteStatus: 'in-force',
		scopeIncludesOrder: true,
		statuteDigest: 'sha256:authorization',
		rootDigest: normativeRoot.digest,
		...overrides,
	};
}

wardenTest(
	'congressionally authorized military order enters Youngstown category one',
	[ARTICLE_II.rules.commanderInChief, ARTICLE_II.doctrine.youngstown],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder(),
			authorization: militaryAuthorization(),
		});
		assert.equal(result.status, 'military-order-authorized');
		assert.equal(result.authorityCategory, 'youngstown-category-one');
	},
);

wardenTest(
	'military authorization from another root cannot support a current command',
	[ARTICLE_II.doctrine.youngstown],
	() => {
		assert.throws(
			() =>
				commandForces({
					executive,
					order: militaryOrder(),
					authorization: militaryAuthorization({ rootDigest: 'sha256:other-root' }),
				}),
			/Military authorization belongs to another normative root/,
		);
	},
);

wardenTest(
	'state militia requires actual federal service',
	[ARTICLE_II.rules.commanderInChief],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder({ force: 'state-militia' }),
			authorization: militaryAuthorization({ calledIntoActualService: false }),
		});
		assert.equal(result.reason, 'state-militia-not-called-into-actual-federal-service');
	},
);

wardenTest(
	'federalized militia may receive a bounded command',
	[ARTICLE_II.rules.commanderInChief],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder({ force: 'state-militia' }),
			authorization: militaryAuthorization({ calledIntoActualService: true }),
		});
		assert.equal(result.status, 'military-order-authorized');
	},
);

wardenTest(
	'a verified hostile attack supports a bounded defensive response',
	[ARTICLE_II.rules.commanderInChief],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder(),
			authorization: militaryAuthorization({
				kind: 'repel-verified-attack',
				hostileAttackVerified: true,
				responseScopeVerified: true,
			}),
		});
		assert.equal(result.authorityCategory, 'repel-verified-attack');
	},
);

wardenTest(
	'an unverified attack cannot be manufactured by WARDEN',
	[ARTICLE_II.engineering.wardenBoundary],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder(),
			authorization: militaryAuthorization({
				kind: 'repel-verified-attack',
				hostileAttackVerified: false,
				responseScopeVerified: true,
			}),
		});
		assert.equal(result.status, 'military-order-blocked');
	},
);

wardenTest(
	'congressional silence enters a constitutional determination instead of an invented grant',
	[ARTICLE_II.doctrine.youngstown, ARTICLE_II.engineering.wardenBoundary],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder(),
			authorization: militaryAuthorization({ kind: 'congress-silent' }),
		});
		assert.equal(result.status, 'requires-constitutional-determination');
	},
);

wardenTest(
	'an order contrary to Congress is blocked without an exclusive-power determination',
	[ARTICLE_II.doctrine.youngstown],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder(),
			authorization: militaryAuthorization({
				kind: 'contrary-to-congress',
				exclusivePresidentialPowerDetermination: false,
			}),
		});
		assert.equal(result.status, 'military-order-blocked');
	},
);

for (const [name, orderMutation, pattern] of [
	[
		'military order requires law-of-armed-conflict review',
		{ lawOfArmedConflictReviewVerified: false },
		/law-of-armed-conflict/,
	],
	[
		'military order requires an appropriation boundary',
		{ appropriationVerified: false },
		/appropriation boundary/,
	],
]) {
	wardenTest(name, [ARTICLE_II.engineering.boundedCapabilities], () => {
		assert.throws(
			() =>
				commandForces({
					executive,
					order: militaryOrder(orderMutation),
					authorization: militaryAuthorization(),
				}),
			pattern,
		);
	});
}

wardenTest(
	'executive military order does not manufacture a declaration of war',
	[ARTICLE_II.rules.commanderInChief, ARTICLE_II.doctrine.youngstown],
	() => {
		const result = commandForces({
			executive,
			order: militaryOrder(),
			authorization: militaryAuthorization(),
		});
		assert.equal(result.declarationOfWar, 'not-created-by-executive-order');
	},
);

wardenTest(
	'execute accepts the real Article IV to Article III judgment handoff',
	[
		ARTICLE_IV.engineering.safeDispute,
		ARTICLE_III.engineering.boundedRemedy,
		ARTICLE_II.rules.takeCare,
	],
	() => {
		const order = executionOrder();
		assert.equal(unresolvedArticleIV.status, 'requires-resolution');
		assert.equal(judgment.handoff, 'article-ii:execute');
		assert.equal(order.status, 'execution-ordered');
		assert.equal(order.judgmentDigest, judgment.judgmentDigest);
	},
);

wardenTest(
	'execute preserves the Article III source object byte for byte',
	[ARTICLE_II.engineering.sourcePreservingExecution],
	() => {
		const before = JSON.stringify(judgment);
		executionOrder();
		assert.equal(JSON.stringify(judgment), before);
	},
);

wardenTest(
	'tampering with the judicial remedy fails at the executive boundary',
	[ARTICLE_II.doctrine.finalJudgment],
	() => {
		assert.throws(
			() =>
				executionOrder({
					judgment: {
						...judgment,
						remedy: { ...judgment.remedy, scope: 'all-future-judgments' },
					},
				}),
			/Judgment integrity check failed/,
		);
	},
);

wardenTest(
	'a valid judgment without an Article II handoff remains outside execution',
	[ARTICLE_III.engineering.boundedRemedy, ARTICLE_II.engineering.boundedCapabilities],
	() => {
		assert.throws(
			() => executionOrder({ judgment: { ...judgment, handoff: 'case-closed' } }),
			/does not authorize an Article II execution handoff/,
		);
	},
);

wardenTest(
	'an Article III stay blocks material execution',
	[ARTICLE_II.doctrine.finalJudgment],
	() => {
		const result = executionOrder({ judgment: { ...judgment, execution: 'stayed' } });
		assert.equal(result.status, 'execution-stayed');
		assert.equal(result.handoff, 'article-iii:await-further-order');
	},
);

wardenTest(
	'a remand blocks the former remedy',
	[ARTICLE_III.engineering.immutableLineage, ARTICLE_II.doctrine.finalJudgment],
	() => {
		const result = executionOrder({
			judgment: {
				...judgment,
				execution: 'suspended-on-remand',
			},
		});
		assert.equal(result.status, 'execution-stayed');
	},
);

wardenTest(
	'executive rejects a validly re-digested judgment from another normative root',
	[ARTICLE_II.rules.takeCare],
	() => {
		const foreign = {
			...judgment,
			rootDigest: 'sha256:foreign-root',
		};
		const content = {
			judgmentId: foreign.judgmentId,
			judiciaryId: foreign.judiciaryId,
			rootDigest: foreign.rootDigest,
			caseDigest: foreign.caseDigest,
			recordDigest: foreign.recordDigest,
			courtId: foreign.courtId,
			courtTier: foreign.courtTier,
			jurisdictionHead: foreign.jurisdictionHead,
			decidedAt: foreign.decidedAt,
			disposition: foreign.disposition,
			holdings: foreign.holdings,
			remedy: foreign.remedy,
			sourceDigest: foreign.sourceDigest,
			parentJudgmentDigest: foreign.parentJudgmentDigest ?? null,
			appellateOutcome: foreign.appellateOutcome ?? null,
		};
		foreign.judgmentDigest = digest(content);
		assert.throws(() => executionOrder({ judgment: foreign }), /different normative roots/);
	},
);

function officerForOffice(office) {
	return appointOfficer({
		executive,
		office,
		candidate: marshalCandidate,
		nomination: { ...nomination, officeId: office.id },
		senateConsent: { ...appointmentConsent, officeId: office.id },
		appointment: { ...appointment, officeId: office.id },
		commission: { ...commission, officeId: office.id },
	});
}

wardenTest(
	'commissioned officer needs judgment-execution capability',
	[ARTICLE_II.engineering.boundedCapabilities],
	() => {
		const observer = officerForOffice({
			...marshalOffice,
			id: 'office:observer',
			capabilities: ['observe-federal-judgment'],
		});
		assert.throws(
			() => executionOrder({ officer: observer }),
			/lacks judgment-execution capability/,
		);
	},
);

wardenTest(
	'judicial remedy selects an exact executive endpoint',
	[ARTICLE_III.engineering.boundedRemedy, ARTICLE_II.engineering.boundedCapabilities],
	() => {
		const otherEndpoint = officerForOffice({
			...marshalOffice,
			id: 'office:other-endpoint',
			executionEndpoint: 'article-ii:other-service',
		});
		assert.throws(
			() => executionOrder({ officer: otherEndpoint }),
			/names another executive endpoint/,
		);
	},
);

const planBoundaryFailures = [
	[
		'execution plan must reference the exact judgment digest',
		{ sourceJudgmentDigest: 'sha256:other-judgment' },
		/references another judgment/,
	],
	[
		'executive cannot change the judicial target',
		{ target: 'Every Enforcement Office' },
		/changes the judicial target/,
	],
	[
		'executive cannot change the judicial operation',
		{ operation: 'imprison-debtor-anyway' },
		/changes the judicial operation/,
	],
	[
		'executive cannot enlarge the judicial scope',
		{ scope: 'all-money-judgments' },
		/enlarges or changes the judicial scope/,
	],
	[
		'executive cannot add a sanction to the judicial remedy',
		{ noAdditionalSanction: false },
		/may not add an executive sanction/,
	],
	[
		'execution plan requires a least-force determination',
		{ leastForceVerified: false },
		/least-force determination/,
	],
	[
		'execution plan requires an appropriation boundary',
		{ appropriationVerified: false },
		/appropriation boundary/,
	],
];

for (const [name, mutation, pattern] of planBoundaryFailures) {
	wardenTest(name, [ARTICLE_II.engineering.sourcePreservingExecution], () => {
		assert.throws(() => executionOrder({ plan: executionPlan(mutation) }), pattern);
	});
}

wardenTest(
	'every execution step remains inside target and scope',
	[ARTICLE_II.engineering.boundedCapabilities],
	() => {
		const unsafeStep = {
			...executionPlan().steps[0],
			scope: 'all-future-judgments',
		};
		assert.throws(
			() => executionOrder({ plan: executionPlan({ steps: [unsafeStep] }) }),
			/exceeds the judicial remedy/,
		);
	},
);

wardenTest(
	'nonfinal reversible remedy cannot be converted into an irreversible step',
	[ARTICLE_III.engineering.boundedRemedy, ARTICLE_II.doctrine.finalJudgment],
	() => {
		const irreversible = {
			...executionPlan().steps[0],
			reversible: false,
		};
		assert.throws(
			() => executionOrder({ plan: executionPlan({ steps: [irreversible] }) }),
			/must remain reversible/,
		);
	},
);

wardenTest(
	'execution order preserves separate digests for holding, remedy, and source judgment',
	[ARTICLE_II.engineering.sourcePreservingExecution],
	() => {
		const order = executionOrder();
		assert.equal(order.sourceSnapshot.judgmentDigest, judgment.judgmentDigest);
		assert.notEqual(order.sourceSnapshot.holdingsDigest, order.sourceSnapshot.remedyDigest);
	},
);

wardenTest('execution order is deeply immutable', [ARTICLE_II.engineering.executionReceipt], () => {
	const order = executionOrder();
	assert.equal(Object.isFrozen(order), true);
	assert.throws(() => order.steps.push(order.steps[0]));
});

wardenTest(
	'complete authenticated observations create an execution receipt',
	[ARTICLE_II.engineering.executionReceipt],
	() => {
		const order = executionOrder();
		const receipt = confirmExecution({
			executive,
			order,
			observations: successfulObservations(order),
			confirmedAt: '2026-08-12T10:00:00Z',
		});
		assert.equal(receipt.status, 'execution-confirmed');
		assert.equal(receipt.handoff, 'article-iii:execution-receipt');
		assert.equal(receipt.judgmentDigest, judgment.judgmentDigest);
	},
);

wardenTest(
	'missing observation leaves execution incomplete',
	[ARTICLE_II.engineering.executionReceipt],
	() => {
		const order = executionOrder();
		const receipt = confirmExecution({
			executive,
			order,
			observations: successfulObservations(order).slice(0, 1),
			confirmedAt: '2026-08-12T10:00:00Z',
		});
		assert.equal(receipt.status, 'execution-incomplete');
		assert.equal(receipt.handoff, 'article-ii:remediate-execution');
	},
);

wardenTest(
	'failed observed step leaves execution incomplete',
	[ARTICLE_II.engineering.executionReceipt],
	() => {
		const order = executionOrder();
		const observations = successfulObservations(order);
		observations[1] = { ...observations[1], completed: false };
		const receipt = confirmExecution({
			executive,
			order,
			observations,
			confirmedAt: '2026-08-12T10:00:00Z',
		});
		assert.equal(receipt.status, 'execution-incomplete');
	},
);

wardenTest(
	'observation cannot invent an unauthorized execution step',
	[ARTICLE_II.engineering.executionReceipt],
	() => {
		const order = executionOrder();
		assert.throws(
			() =>
				confirmExecution({
					executive,
					order,
					observations: [
						...successfulObservations(order),
						{
							stepId: 'step:invented-sanction',
							authenticated: true,
							completed: true,
							observedEffect: 'extra punishment',
						},
					],
					confirmedAt: '2026-08-12T10:00:00Z',
				}),
			/unauthorized step/,
		);
	},
);

wardenTest(
	'unauthenticated observation cannot support a receipt',
	[ARTICLE_II.engineering.executionReceipt],
	() => {
		const order = executionOrder();
		const observations = successfulObservations(order);
		observations[0] = { ...observations[0], authenticated: false };
		assert.throws(
			() =>
				confirmExecution({
					executive,
					order,
					observations,
					confirmedAt: '2026-08-12T10:00:00Z',
				}),
			/not authenticated/,
		);
	},
);

wardenTest(
	'execution receipt is deeply immutable',
	[ARTICLE_II.engineering.executionReceipt],
	() => {
		const order = executionOrder();
		const receipt = confirmExecution({
			executive,
			order,
			observations: successfulObservations(order),
			confirmedAt: '2026-08-12T10:00:00Z',
		});
		assert.equal(Object.isFrozen(receipt), true);
		assert.throws(() => receipt.stepResults.push(receipt.stepResults[0]));
	},
);

for (const kind of ['state-of-union', 'recommend-measure']) {
	wardenTest(
		`${kind} communication remains a message rather than legislation`,
		[ARTICLE_II.rules.congressionalCommunication],
		() => {
			const result = communicateWithCongress({
				executive,
				message: {
					id: `message:${kind}`,
					kind,
					contentDigest: `sha256:${kind}`,
					issuedAt: '2026-08-12T12:00:00Z',
					authenticated: true,
				},
			});
			assert.equal(result.status, 'congressional-communication-issued');
			assert.equal(result.legislation, 'not-created-by-recommendation');
		},
	);
}

wardenTest(
	'extraordinary session requires an attributed extraordinary occasion',
	[ARTICLE_II.rules.congressionalCommunication],
	() => {
		assert.throws(
			() =>
				communicateWithCongress({
					executive,
					message: {
						id: 'message:convene',
						kind: 'convene-extraordinary-session',
						contentDigest: 'sha256:convene',
						issuedAt: '2026-08-12T12:00:00Z',
						authenticated: true,
						extraordinaryOccasionVerified: false,
					},
				}),
			/attributed occasion/,
		);
	},
);

wardenTest(
	'presidential adjournment requires authenticated disagreement between Houses',
	[ARTICLE_II.rules.congressionalCommunication],
	() => {
		assert.throws(
			() =>
				communicateWithCongress({
					executive,
					message: {
						id: 'message:adjourn',
						kind: 'adjourn-after-house-disagreement',
						contentDigest: 'sha256:adjourn',
						issuedAt: '2026-08-12T12:00:00Z',
						authenticated: true,
						houseDisagreementOnAdjournmentAuthenticated: false,
					},
				}),
			/requires authenticated House disagreement/,
		);
	},
);

wardenTest(
	'authenticated diplomatic credentials create a reception record',
	[ARTICLE_II.rules.diplomaticReception],
	() => {
		const result = receiveDiplomat({
			executive,
			diplomat: {
				id: 'ambassador:one',
				sendingState: 'Polity One',
				credentialDigest: 'sha256:credentials',
				credentialsAuthenticated: true,
				receivedAt: '2026-08-12T12:00:00Z',
			},
		});
		assert.equal(result.status, 'diplomat-received');
	},
);

wardenTest(
	'unverified diplomatic credentials cannot be received as authenticated',
	[ARTICLE_II.rules.diplomaticReception],
	() => {
		assert.throws(
			() =>
				receiveDiplomat({
					executive,
					diplomat: {
						id: 'ambassador:one',
						sendingState: 'Polity One',
						credentialDigest: 'sha256:credentials',
						credentialsAuthenticated: false,
						receivedAt: '2026-08-12T12:00:00Z',
					},
				}),
			/must be authenticated/,
		);
	},
);

wardenTest(
	'authenticated House impeachment and Senate conviction revoke civil authority',
	[ARTICLE_II.rules.impeachmentRemoval],
	() => {
		const result = applyImpeachmentRemoval({
			executive,
			subject: { id: president.id, officeKind: 'president' },
			record: {
				id: 'impeachment:one',
				subjectId: president.id,
				authenticated: true,
				houseImpeached: true,
				senateConvicted: true,
				convictionGround: 'bribery',
				effectiveAt: '2026-08-12T12:00:00Z',
				rootDigest: normativeRoot.digest,
			},
		});
		assert.equal(result.status, 'authority-revoked');
		assert.equal(result.handoff, 'amendment-xxv:presidential-succession');
		assert.equal(result.pardonAvailable, false);
	},
);

wardenTest(
	'impeachment record from another root cannot revoke current authority',
	[ARTICLE_II.rules.impeachmentRemoval],
	() => {
		assert.throws(
			() =>
				applyImpeachmentRemoval({
					executive,
					subject: { id: president.id, officeKind: 'president' },
					record: {
						id: 'impeachment:foreign-root',
						subjectId: president.id,
						authenticated: true,
						houseImpeached: true,
						senateConvicted: true,
						convictionGround: 'bribery',
						effectiveAt: '2026-08-12T12:00:00Z',
						rootDigest: 'sha256:other-root',
					},
				}),
			/Impeachment record belongs to another normative root/,
		);
	},
);

for (const [name, mutation] of [
	['House impeachment cannot be omitted from removal', { houseImpeached: false }],
	['Senate conviction cannot be omitted from removal', { senateConvicted: false }],
]) {
	wardenTest(name, [ARTICLE_II.rules.impeachmentRemoval], () => {
		assert.throws(
			() =>
				applyImpeachmentRemoval({
					executive,
					subject: { id: president.id, officeKind: 'president' },
					record: {
						id: 'impeachment:one',
						subjectId: president.id,
						authenticated: true,
						houseImpeached: true,
						senateConvicted: true,
						convictionGround: 'bribery',
						effectiveAt: '2026-08-12T12:00:00Z',
						rootDigest: normativeRoot.digest,
						...mutation,
					},
				}),
			/requires authenticated impeachment and Senate conviction/,
		);
	});
}

Команди запуску:

node --test work/article-ii.test.mjs
node --test work/article-iv.test.mjs work/article-iii.test.mjs work/article-ii.test.mjs

Результати окремої та накопичувальної перевірок:

Article II: tests 124 · pass 124 · fail 0
Articles IV–II: tests 236 · pass 236 · fail 0
flowchart TD
    A["124 сценарії статті II"] --> B["Мандат і безперервність"]
    A --> C["Посади і спільні повноваження"]
    A --> D["Наказ і квитанція"]
    B --> E["Безпечна відмова"]
    C --> E
    D --> E
    E --> F["236 накопичувальних перевірок"]
wardenWARDEN виконавчого контуру

WARDEN перевіряє походження повноваження, межі наказу та доказ виконання у 124 сценаріях

  • source: Походження повноваження
  • source: Межі наказу
  • source: Доказ виконання
  • process: WARDEN · 124 сценарії
  • artifact: Небезпечні mutation tests
  • state: Чинний маршрут підтверджено
  • human-decision: Людське рішення
  • authority references suite
  • scope references suite
  • evidence references suite
  • mutations validates suite
  • suite validates pass
  • suite returns review
WARDEN виконавчого контуруIRON CREED semantic-core · asset.constitution-runtime-06-article-ii.g07 · authorial brief

Що стаття II дає програмній архітектурі

Шостий експеримент додає прототипу сім переносних властивостей.

Перше — authority snapshot. Активний носій повноваження існує в конкретній версії root, строку, мандата й lineage. Зміна виконавця створює нову версію стану та зберігає батьківський об’єкт.

Друге — capability-bearing office. Посада має джерело, класифікацію та операції до появи конкретного посадовця. Призначення пов’язує суб’єкта із заздалегідь обмеженим інтерфейсом.

Третє — незалежне підтвердження shared operation. Договір і principal appointment потребують другого конституційного суб’єкта. Код зберігає окремий consent artifact і обчислює встановлений поріг.

Четверте — source-preserving execution. Виконавець створює похідний наказ і зберігає digest закону або рішення. Локальний план може уточнювати кроки, зберігаючи ціль та область джерела.

П’яте — двофазна зміна. Authorization передує матеріальній дії. Observation передує підтвердженню. Помилка на другій фазі створює incomplete state замість фіктивного успіху.

Шосте — reversible execution. Неостаточне судове рішення допускає виконання без stay, однак план зберігає зворотність. Апеляційний контур може зупинити або змінити подальший ефект без прихованого знищення історії.

Сьоме — revocable authority. Повноваження має процедуру припинення. Revocation пов’язується з доведеною зовнішньою подією й негайно змінює допустимі операції.

Ці властивості добре переносяться до software governance. Deployment controller може приймати підписаний release artifact, перевіряти origin, компілювати bounded plan, застосовувати його через обмежений service account, збирати observations і випускати receipt. Ротація оператора зберігає lineage. Високоризикова операція потребує незалежного approval. Відкат залишається окремою дією, а не стиранням історії.

Де закінчується шостий експеримент

Програмна модель упевнено перевіряє ідентифікатори, digests, строки, пороги, routes, capability та відповідність області. Вона слабше виражає сам зміст faithful execution. Закон може містити невизначеність. Два законні пріоритети можуть конкурувати за обмежений ресурс. Військова необхідність залежить від неповного record. Помилування виражає політичне й моральне судження. Призначення потребує оцінки характеру та компетентності. Дипломатичний прийом може змінити відносини держав самим фактом.

Булеве значення eligibilityVerified також не доводить громадянство, вік або відсутність дискваліфікації. Воно повідомляє, що відповідальна процедура створила атрибутоване визначення. Така архітектура покращує trace і перешкоджає самопризначенню, зберігаючи людське рішення на попередньому рівні.

confirmExecution() не виконує судовий наказ у фізичному світі. Вона перевіряє отримані спостереження. Автентичність сенсора, опір адресата, непередбачена шкода й неправдивий рапорт потребуватимуть нових механізмів доказування та контролю. Бюрократія вміла видавати зелену квитанцію на червону реальність задовго до появи JavaScript; цифровізація лише робить шрифт охайнішим.

Конституційне виконання також охоплює законний примус. Software exception завершує стек викликів. Державний наказ може завершити свободу, власність, кар’єру або життя людини. Тому provenance і bounded capability тут є мінімальною дисципліною, а не доказом справедливості системи.

Нарешті, стаття II залежить від ще не зібраного виробника загальних норм. Тестові fixtures уже передають statutory office, appropriation, military authorization, succession plan, Senate consent та impeachment record. Їхнє походження поки засвідчене ззовні. Стаття I має побудувати legislate(), розподілити палати, кворуми, голосування, veto, override, бюджети, заснування посад та імпічмент. Після неї модель уперше зможе пройти повне коло від загального правила до виконання й зворотної перевірки.

Висновок

Стаття II перетворює конституційний порядок на діяльну систему через атрибутованого носія повноваження, розподілені посади та перевірювані похідні артефакти. Президентський мандат установлює верхній виконавчий центр. Призначення створюють обмежених виконавців. Спільні повноваження потребують незалежного підтвердження. execute() зберігає джерело, обмежує наказ і передає дію матеріальному runtime. confirmExecution() повертає доказ результату. Наступництво та імпічмент змінюють носія, зберігаючи lineage системи.

Шоста збірка підтверджує практичну цінність програмної інтерпретації. Вона здатна моделювати походження, повноваження, область, перехід стану й аудит. Вона залишає людським інституціям зміст норми, факти, необхідність і відповідальність. Саме такий розподіл робить прототип корисним для software governance: код дисциплінує шлях рішення й перестає вдавати із себе джерело легітимності.

На карті UCA тепер рухається не лише сигнал. Судовий пакет отримав виконавця, наказ, спостережуваний ефект і зворотну квитанцію. Америка нашого прототипу вміє діяти. Залишилося з’ясувати, чи вміє вона створювати правило, гідне виконання.

Продовжити дослідження з ШІ

Сайт формує цей розділ із незалежного набору питань constitution-runtime.article-ii.execute, збереженого в супровідному каталозі constitution-runtime-06-article-ii-questions.yaml. Кожен prompt самостійно визначає свій предмет статті II, конституційне або доктринальне джерело, об’єкт прототипу та межу повноваження, тому може працювати поза лінійною послідовністю статті без втрати контексту.

Рекомендований маршрут: мандат → розподілена виконавча влада → безперервність → faithful execution → handoff судового рішення → призначення → договори → помилування → військове командування → WARDEN → межі. Двомовний каталог містить контракт відповіді ШІ, шістдесят шість самостійних prompts, умови відкриття гілок, посилання на код і візуальні матеріали та навігацію повернення.

Відомості про публікацію

Автори: Sam Starling, Oksana Dubinetska
Контекст проєкту: Zhovten Games / IRONCREED
Повне дослідницьке джерело: «Конституція коду» — DOI 10.5281/zenodo.21894242
Репозиторій дослідження: FOP-Oksana-Dubinetska/code-constitution
Історичні, юридичні та технічні матеріали: текст Конституції США; поправки XI–XXVII; огляд статті II; Executive Vesting Clause; президентська присяга; Take Care Clause; рамка Youngstown; Appointments Clause; principal та inferior officers; Recess Appointments Clause; treaty-making power; self-executing та non-self-executing treaties; Pardon Clause; Commander in Chief Clause; Impeachment Clause; 3 U.S.C. § 19
Пов’язані публікації: «Підключити Америку: як стаття VII запускає республіку»; «Чому довіряє Америка: як стаття VI збирає верховний порядок»; «Оновити Америку: як стаття V змінює конституційне ядро»; «Зв’язати Америку: як стаття IV перетворює штати на федеративну мережу»; «Розсудити Америку: як стаття III перетворює конфлікт на виконуване рішення»
Наступна публікація: стаття I — legislate() та підсумковий висновок серії
Редакція публікації: 0.2 · 13 серпня 2026 року