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

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

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

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

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

  • source: Компетенція
  • actor: Палата представників
  • actor: Сенат
  • artifact: Одна точна редакція
  • decision: Представлення
  • artifact: Закон
  • boundary: Обмежені повноваження
  • process: Оскарження
  • competence requires house
  • competence requires senate
  • house validates text
  • senate validates text
  • text requires presentment
  • presentment produces law
  • law executes powers
  • powers returns challenge
головне зображенняIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g01 · authorial brief

Остання станція стоїть на початку маршруту

У Death Stranding підключення станції до UCA виглядає як завершення роботи. Карта спалахує, мережа приймає новий вузол, інтерфейс повідомляє про розширення Америки, а гравець отримує доступ до спільних даних та інфраструктури. Потім починається менш урочиста частина державного будівництва: хтось має дозволити витрачання матеріалів, визначити правила дороги, призначити відповідального, установити межу доступу й вирішити, що станеться, коли нова лінія пройде через чуже укриття. Зв’язок створює можливість спільної дії. Загальна норма визначає, яка дія отримала право стати спільною.

Шість попередніх публікацій рухалися у зворотному напрямку. Стаття VII запустила порядок після ратифікації. Стаття VI визначила довірену редакцію та ієрархію чинних джерел. Стаття V навчила ядро змінюватися. Стаття IV з’єднала автономні юрисдикції. Стаття III прийняла конкретний спір і сформувала обмежений засіб поновлення. Стаття II перетворила закон або судове рішення на дію та повернула квитанцію виконання. На кожному рівні існували посилання на закон, установлену законом посаду, асигнування, військове уповноваження, процедуру імпічменту або організацію суду. Джерело цих об’єктів залишалося поза кадром.

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

legislate() → execute()
legislate() → constituteJudiciary() → resolve()
legislate() → authorizeAppropriation() → execute()
legislate() → establishOffice() → appointOfficer()
legislate() → impeach() → tryImpeachment() → applyImpeachmentRemoval()

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

Сьома збірка

Повна модель складається із семи конституційних функцій:

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

Стаття I містить десять секцій і є найширшим первинним текстом Конституції. Для програмної моделі вони утворюють чотири блоки:

БлокСекціїПрограмне питання
Носій і відтворення влади1–4Хто може брати участь у нормотворенні та звідки походить його мандат?
Внутрішня чинність і закон5–7Як кворум, журнал, дві палати, одна редакція та представлення створюють закон?
Позитивна компетенція8Який предмет доступний Конгресу та які засоби виводяться з наданої влади?
Межі9–10Які рішення заборонені Союзу й штатам або потребують спеціальної згоди?

Виконуваний модуль розгортає ці блоки в сімнадцять публічних операцій. Центральна legislate() проводить звичайний закон через увесь маршрут. Решта функцій показує самостійні переходи й дає змогу тестувати їх окремо:

ОпераціяПризначення
constituteCongress()Пов’язує дві палати, їхній склад, представництво, строки й поточний root
recordChamberVote()Перевіряє кворум, поріг, точний предмет голосування та запис у журналі
introduceBill()Перевіряє походження, компетенцію, прямі заборони та revenue origination
createBillVersion()Створює точну редакцію з digest і батьківською lineage
passChamber()Пов’язує незалежну згоду палати з конкретною редакцією
enrollBill()Допускає до представлення лише один текст, схвалений обома палатами
presentBill()Моделює підпис, звичайне вето, десятиденний маршрут і pocket veto
overrideVeto()Перевіряє повторне голосування двома третинами в кожній палаті
legislate()Збирає повний звичайний pipeline від проєкту до закону
authorizeAppropriation()Створює обмежене право розпоряджатися спільним грошовим ресурсом
establishOffice()Видає контракт посади, сумісний зі статтею II
authorizeMilitaryAction()Видає доведену конгресову основу військового наказу
createSuccessionPlan()Створює встановлений законом маршрут подвійної вакансії
organizeInferiorCourts()Установлює нижчі суди для статті III
impeach() / tryImpeachment()Розділяє обвинувачення Палати та судову функцію Сенату
screenStateAct()Перевіряє абсолютні заборони й дії штату, що потребують згоди Конгресу

Модуль зберігає історичну статтю I як предмет експерименту. Висновки для software governance з’являються після запуску через інверсію функції. Репозиторію проєкту не потрібні дві палати розробників, Президент гілки main і Сенат pull request. Йому потрібна ясна відповідь на ті самі питання: хто приймає загальнообов’язкову норму, у якому предметі та сфері, за якою процедурою, з якими незалежними згодами, щодо якої точної редакції, у який спосіб фіксується заперечення та де закінчується влада нормотворця.

Одна законодавча влада, розділена всередині себе

Перше речення статті I передає надані федеральні законодавчі повноваження Конгресу, що складається з Палати представників і Сенату. Constitution Annotated розглядає двопалатність як структурну умову федерального законодавства. Одна функція отримує дві незалежні інституційні підстави.

Палата представників побудована навколо населення, регулярного переобрання та пропорційного розподілу місць. Сенат — навколо рівного представництва штатів, шестирічного строку й поетапного оновлення. XVII поправка замінила обрання сенаторів законодавчими органами штатів прямими виборами, зберігши рівність штатів і класи строків. XIV поправка замінила первинну формулу представництва, XX установила сучасний початок строків Конгресу, а XXVII відокремила зміну винагороди членів від негайної вигоди чинного складу. Тому поточний normativeRoot представляє статтю I разом із чинними поправками, а первинні правила зберігає в історичній lineage.

Прототип виражає відмінність палат полями representation: "population-apportioned" і representation: "equal-state". Він вимагає окремих доказів виборів, кваліфікацій і чинної редакції правил. Для Сенату додатково перевіряються пряме обрання та поетапна безперервність. Один об’єкт congress містить обидві палати, однак жодна палата не отримує права заповнити результат іншої.

Такий дизайн дає програмній архітектурі важливий критерій незалежної згоди. Два підтвердження представляють дві підстави рішення лише тоді, коли кожне належить окремому суб’єктові, пов’язане з окремою відповідальністю та зберігає реальну можливість відмови. Дві кнопки в одному інтерфейсі, послідовно натиснуті одним носієм повноваження, утворюють дві події й одну підставу волі. Тому «Конституція коду» переносить функцію двопалатності через незалежність згод, а конкретну кількість сторін схвалення Установчий профіль визначає відповідно до ризику.

flowchart TB
    A["Проєкт загальної норми"] --> B["Палата представників"]
    A --> C["Сенат"]
    B --> D["Схвалена редакція Палати"]
    C --> E["Схвалена редакція Сенату"]
    D --> F{"Однаковий текст?"}
    E --> F
    F -- "Так" --> G["Зареєстрований законопроєкт"]
    F -- "Ні" --> H["Узгодження та повторне голосування"]
gateДві незалежні палати й одна редакція

Палата представників і Сенат окремо голосують за точні редакції; до представлення допускається лише однаковий текст

  • artifact: Законопроєкт
  • artifact: Редакція Палати
  • artifact: Редакція Сенату
  • decision: Digest збігається?
  • artifact: Одна редакція
  • state: Представлення
  • state: Повернення на узгодження
  • proposal produces house
  • proposal produces senate
  • house validates digest
  • senate validates digest
  • digest validates enrolled: Так
  • digest rejects revision: Ні
  • enrolled produces presentment
Дві незалежні палати й одна редакціяIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g02 · authorial brief

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

Секції 2–6 визначають вибори, кваліфікації, вакансії, строки, посадових осіб палат, кворум, правила, дисципліну, журнал, перерви, винагороду, привілеї та несумісність посад. Ці положення захищають безперервність законодавчої функції й відокремлюють повноваження органу від випадкової присутності людей у кімнаті.

У прототипі constituteCongress() не зберігає біографій 535 членів. Він приймає сертифіковані результати зовнішніх процесів і створює перевірюваний snapshot: кількість місць, кількість чинних членів, спосіб представництва, проходження кваліфікаційної перевірки, строк і поточний нормативний root. Така редукція зберігає архітектурну функцію й відкрито залишає вибори, спори про мандат і фактичне представництво зовнішнім системам.

recordChamberVote() далі перевіряє вужчу сферу. Більшість чинних членів палати утворює кворум. Звичайне питання приймається більшістю тих, хто голосує, за наявності кворуму, якщо Конституція не встановила іншого порога. Для подолання вето й засудження за імпічментом потрібні дві третини присутніх. Кожен голос пов’язаний із questionDigest, тому запис «230 за» залишається беззмістовним без відповіді на питання «за яку редакцію?»

Journal Clause надає процесу публічну пам’ять. Прототип вимагає засвідченого й оприлюдненого запису, а для кваліфікованого порога — поіменних yeas and nays. Подекуди ця вимога посилює буквальний мінімум тексту єдиним інженерним правилом доказовості. Журнал підтверджує подію, склад, предмет і результат. Він не створює відсутньої компетенції та не усуває змістового конституційного дефекту.

Тут виникає перше загальне правило серії:

Доказ процедури підтверджує процедуру. Повноваження, матеріальна допустимість і фактичне виконання потребують власних доказів.

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

Закон має редакцію раніше, ніж отримує номер

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

Прототип робить редакцію самостійним об’єктом. createBillVersion() зберігає текст, textDigest, палату, батьківський digest, amendments і час створення. passChamber() пов’язує голосування з versionDigest. enrollBill() порівнює зміст схвалених редакцій і за розбіжності повертає bicameral-disagreement.

Порівнюються саме тексти, а не локальні ідентифікатори дій. Палата й Сенат можуть створити два самостійні об’єкти в різний час і з різною процедурною lineage, що містять одну редакцію закону. Їхні versionDigest відрізняються; їхні textDigest збігаються. Enrolled bill отримує новий digest, який зберігає обидві дії та спільний текст.

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

Revenue Origination Clause додає спеціальне правило. Законопроєкт про збирання доходів виникає в Палаті представників; Сенат зберігає право пропонувати й приймати поправки. Constitution Annotated пов’язує цю вимогу з первинно прямим народним представництвом Палати й допускає змістові сенатські amendments. Тому модель блокує Senate-originated revenue bill і водночас дозволяє Сенату змінити вже ухвалений Палатою текст. Змінена редакція повертається до звичайної умови: обидві палати мають знову підтвердити однаковий зміст.

Представлення створює чотири маршрути закону

Після згоди палат enrolled bill надходить Президентові. Стаття I, секція 7, створює кілька результатів:

  1. Президент підписує законопроєкт, і він стає законом.
  2. Президент повертає його палаті походження із запереченнями; Конгрес може подолати вето двома третинами кожної палати.
  3. Президент не повертає проєкт протягом десяти днів, крім неділь; якщо можливість повернення зберігається, проєкт стає законом без підпису.
  4. Перерва Конгресу унеможливлює повернення, і бездіяльність Президента спричиняє pocket veto.

Прототип виражає ці маршрути функціями presentBill() і overrideVeto(). Звичайне вето зберігає enrolled bill незмінним, додає objections і повертає керування палаті походження. Override створює новий presentment digest із двох кваліфікованих голосувань. Pocket veto завершує поточний маршрут і вимагає нового законодавчого процесу.

stateDiagram-v2
    state "Одна редакція схвалена двома палатами" as Enrolled
    state "Підписано Президентом" as Signed
    state "Повернуто із запереченнями" as Vetoed
    state "Дві третини обох палат" as Override
    state "Десять днів без підпису" as TenDays
    state "Повернення неможливе через перерву" as Pocket
    state "Закон набрав чинності" as Law

    [*] --> Enrolled
    Enrolled --> Signed
    Enrolled --> Vetoed
    Enrolled --> TenDays
    Enrolled --> Pocket
    Signed --> Law
    TenDays --> Law
    Vetoed --> Override
    Override --> Law
    Pocket --> [*]
gateЧотири маршрути представлення

Узгоджений законопроєкт стає законом через підпис, сплив десяти днів або подолання звичайного вето; pocket veto завершує маршрут без закону

  • artifact: Узгоджений законопроєкт
  • decision: Президентське представлення
  • process: Підпис
  • process: Сплив 10 днів
  • process: Повернення із запереченнями
  • process: Подолання вето
  • state: Pocket veto
  • state: Закон
  • state: Маршрут завершено без закону
  • bill requires presentment
  • presentment produces signature
  • presentment produces ten-days
  • presentment produces veto
  • presentment produces pocket
  • signature produces law
  • ten-days produces law
  • veto requires override
  • override produces law
  • pocket rejects no-law
Чотири маршрути представленняIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g03 · authorial brief

Календарний розрахунок у коді має лабораторний характер. Він рахує дні за UTC, починає з наступного календарного дня й виключає неділі. Реальна оцінка pocket veto залежить від характеру перерви, можливості повернення та конституційної практики. Прототип перевіряє стан, переданий йому як congressAdjournedPreventsReturn, і не вдає автоматичного тлумача кожного парламентського календаря.

Компетенція передує голосуванню

Секція 8 перелічує повноваження Конгресу: податки й видатки, запозичення, торгівлю, натуралізацію та банкрутство, гроші й стандарти, пошту, виключні права авторів і винахідників, нижчі суди, міжнародні злочини, війну, збройні сили, ополчення, федеральний округ і федеральне майно. Necessary and Proper Clause завершує перелік правом ухвалювати закони, необхідні й належні для здійснення наданих повноважень. Огляд перелічених повноважень і огляд Necessary and Proper Clause пов’язують вибір засобу з легітимною конституційною метою.

Термінологічна примітка. Англійське militia у статті I означає конституційно організоване ополчення. Український відповідник тут — «ополчення»; слово «міліція» мало б пострадянське значення поліцейського органу й спотворювало б предмет норми. Ідентифікатори коду на кшталт militia збережено без перекладу як частину API.

introduceBill() вимагає powerClaim. Звичайна підстава обирається з перелічених повноважень або повноважень із забезпечення виконання пізніших поправок. necessary-and-proper допускається разом із linkedPower і чотирма перевірками: легітимна мета, пристосованість засобу, відсутність заборони та сумісність із Конституцією. Поле necessaryAndProper: true саме собою не видає Конгресу універсальної адміністративної викрутки.

flowchart TB
    A["Мета законопроєкту"] --> B{"Є надане повноваження?"}
    B -- "Ні" --> C["Проєкт заблоковано"]
    B -- "Так" --> D{"Засіб необхідний і належний?"}
    D -- "Ні" --> C
    D -- "Так" --> E{"Є пряма заборона?"}
    E -- "Так" --> C
    E -- "Ні" --> F["Проєкт допускається до процедури"]
gateКомпетенція та похідний засіб

Законодавча мета проходить через надане повноваження, перевірку необхідного й належного засобу та прямі конституційні заборони до голосування

  • artifact: Законодавча мета
  • decision: Надане повноваження?
  • decision: Необхідний і належний засіб?
  • decision: Пряма заборона?
  • state: Допуск до голосування
  • state: Safe rejection
  • purpose requires grant
  • grant validates means: Так
  • grant rejects reject: Ні
  • means validates prohibition: Так
  • means rejects reject: Ні
  • prohibition rejects reject: Так
  • prohibition validates vote: Ні
Компетенція та похідний засібIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g04 · authorial brief

Програмна аналогія тут особливо сильна. Архітектурний нормотворець отримує визначений предмет і сферу. Він може приймати обов’язкові правила всередині них і делегувати спосіб виконання. Делегований компонент зберігає зв’язок із джерелом і не розширює мету завдяки технічній ефективності. Лінтер може перевіряти прийняту норму. Здатність лінтера блокувати збірку не перетворює його на джерело норми. LLM може підготувати проєкт, класифікувати наслідки й показати конфлікт. Успішне генерування тексту не створює мандата на його прийняття.

Пряма заборона переживає кваліфіковану більшість

Секція 9 встановлює межі федеральної влади. Прототип перевіряє вісім класів: bill of attainder, ретроактивну кримінальну заборону, необґрунтоване зупинення habeas corpus, дефектний прямий податок поза чинною XVI поправкою, податок на експорт штату, перевагу портів, витрачання коштів Казначейства без асигнування та титул шляхетності.

Bill of Attainder Clause особливо важлива для розмежування законодавчої та судової функцій. Загальна норма описує дії, умови й наслідки. Законодавче рішення, яке обирає конкретну людину або закриту групу й призначає покарання без суду, привласнює чуже повноваження. Constitution Annotated визначає доктрину через законодавче покарання конкретних осіб або груп. Ex Post Facto Clause забороняє ретроактивне кримінальне погіршення; цивільна ретроактивність потребує інших підстав аналізу й до цієї вузької автоматичної перевірки не входить.

Процедура здатна пройти без жодної помилки й створити заборонений результат. Саме тому introduceBill() перевіряє компетенцію та прямі заборони до голосування. WARDEN не дозволяє двом палатам і Президентові легалізувати titleOfNobility: true спільним ентузіазмом. Реальний спір про кваліфікацію конкретного закону залишається судовим питанням статті III; тестова модель уміє розпізнати заздалегідь формалізовану ознаку й зберігає межу власної класифікації.

Історичний текст статті I водночас показує глибшу проблему. Three-Fifths Clause перетворювала поневолених людей на коефіцієнт представництва, а секція 9 захищала ввіз поневолених людей від федеральної заборони до 1808 року. Ці положення були частиною первинної конституційної основи й обслуговувалися чинними процедурами. XIII і XIV поправки змінили root, а стаття V надала формальний маршрут зміни. Програмна коректність первинного порядку не повідомляла йому матеріальної прийнятності. Вона лише робила експлуатацію людей відтворюваною, пропорційно розподіленою й акуратно записаною — той рідкісний випадок, коли quality assurance чесно підтверджував якість інституційного злочину.

З цього досвіду «Конституція коду» отримала негативний результат інверсії. Чинність норми всередині порядку, її відповідність зовнішньому праву, представництво зачеплених сторін і допустимість предмета утворюють різні рівні. Проєктний нормотворець здатен прийняти обов’язковий архітектурний акт і водночас створити акт, який підлягає оскарженню або припиненню. Нормативна система зберігає процедуру зміни власної основи й право учасників поставити під сумнів сам root.

Асигнування перетворює доступ на обмежене право витрачання

Appropriations Clause забороняє вилучати гроші з Казначейства без асигнування, установленого законом, і вимагає регулярного оприлюднення звіту про надходження та видатки. Constitution Annotated розглядає цю норму як основу контролю Конгресу над публічними коштами.

authorizeAppropriation() вимагає enacted law із явно заявленим output appropriation. Артефакт називає мету, граничну суму, одиницю, період доступності, відповідального та публічний ledger. Технічний доступ до рахунку не замінює цей об’єкт. Президентський наказ також не створює його. Виконавець отримує можливість перевірити appropriationDigest, мету й залишок до матеріальної дії.

У software governance спільними ресурсами є канонічний репозиторій, історія Git, секрети, production-середовище, реєстр ідентифікаторів, домен, ключі підпису, бюджет і реліз. Фактична наявність credentials повідомляє про здатність учинити дію. Нормативне право розпорядження виникає з визначеного джерела, предмета й згоди. Ця функція статті I переноситься майже без втрат.

flowchart TB
    A["Закон"] --> B["Асигнування"]
    B --> C["Мета"]
    B --> D["Гранична сума і строк"]
    B --> E["Відповідальний"]
    B --> F["Публічний реєстр"]
    C --> G["Виконавча дія"]
    D --> G
    E --> G
    F --> G
    G --> H["Квитанція та залишок"]
flowПраво розпорядження спільним ресурсом

Ухвалений закон створює обмежене асигнування з метою, сумою, строком, відповідальним і публічним журналом; виконання повертає квитанцію

  • artifact: Ухвалений закон
  • state: Мета
  • state: Сума
  • state: Строк
  • actor: Відповідальний
  • artifact: Публічний журнал
  • process: Обмежене виконання
  • artifact: Квитанція
  • law produces purpose
  • purpose produces amount
  • amount produces period
  • period produces actor
  • actor produces journal
  • journal produces execution
  • execution produces receipt
Право розпорядження спільним ресурсомIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g05 · authorial brief

Закон видає capability, а не виконує її

Фінальна стаття пов’язує раніше розділені модулі. Enacted law містить outputs, кожен із яких дозволяє окремий похідний артефакт:

Output законуПохідний артефактНаступний споживач
appropriationBounded appropriationстаття II та виконавчий план
office-establishmentПосада, класифікація та спосіб призначенняappointOfficer() статті II
military-authorizationКонгресова підстава і сфераcommandForces() статті II
succession-planЗаконний порядок подвійної вакансіїconstituteExecutive() та XXV поправка
inferior-courtsНижчі суди, jurisdictional heads і територіїconstituteJudiciary() статті III
Імпічмент Палати + засудження СенатуРішення про відкликання повноваженняapplyImpeachmentRemoval() статті II

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

Імпічмент є особливим двопалатним процесом. Палата представників має виключне повноваження висувати обвинувачення. Сенат має виключне повноваження провести trial; для засудження потрібні дві третини присутніх, а під час процесу над Президентом головує Головний суддя. Матеріали Сенату окремо описують засудження, обов’язкове усунення з посади й можливу дискваліфікацію. Кримінальна відповідальність залишається у звичайному процесі.

Прототип створює House impeachment як окремий об’єкт, а потім пов’язує Senate vote з його точним digest. Успішне рішення отримує handoff: "article-ii:revoke-authority". Стаття II приймає запис без адаптера, відкликає capability і запускає президентське наступництво. Президентське помилування залишається недоступним для імпічменту.

Штати зберігають власну владу всередині спільних заборон

Секція 10 завершує статтю I заборонами для штатів. Частина дій заборонена абсолютно: договори й союзи, видавання каперських свідоцтв, карбування грошей, bills of credit, неприпустимий законний платіжний засіб, bill of attainder, ex post facto law, порушення зобов’язання за договорами й титули шляхетності. Інші дії потребують згоди Конгресу: окремі мита, тоннаж, війська й військові кораблі в мирний час, agreements or compacts і вступ у війну. Текст зберігає винятки для необхідних inspection laws і негайного захисту в разі вторгнення або небезпеки, що не допускає зволікання.

screenStateAct() повертає три основні класи: абсолютна заборона, потреба у згоді та дозволена дія з доведеним consent. Згода пов’язана з точним actId і поточним root, тому її не можна повторно використати для іншого compact. Надзвичайний виняток перевіряється окремо й не перетворюється на постійну військову capability.

Це продовжує модель статті IV. Федерація визнає автономність вузлів, а стаття I визначає частину спільних меж їхнього нормотворення. Програмний проєкт так само може включати самостійні пакети, сервіси, репозиторії та команди з локальною компетенцією. Спільний порядок називає дії, що зачіпають shared state, security boundary, публічний контракт або зовнішнє зобов’язання, і вимагає окремої згоди. Локальна автономія отримує формальну сферу замість обіцянки «робіть що хочете, доки CI не почав диміти».

Виконуваний законодавчий шар

Нижче наведено повний ESM-модуль фінальної збірки. Він використовує спільну функцію digest() зі статті IV, зберігає незмінні snapshots і видає артефакти у форматах статей II та III.

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

export const ARTICLE_I = deepFreeze({
	id: 'U.S.Const.art.I',
	rules: {
		vesting:
			'I.1: all federal legislative powers granted by the Constitution are vested in a bicameral Congress consisting of a House and a Senate',
		house:
			'I.2: the House is population-apportioned, regularly elected, and possesses the sole power of impeachment',
		senate:
			'I.3: the Senate gives each state equal representation, preserves staggered continuity, and possesses the sole power to try impeachments',
		elections:
			"I.4: state law initially regulates congressional elections subject to Congress's constitutional power to alter specified regulations",
		quorumAndJournal:
			'I.5: a majority constitutes a quorum; each chamber controls its proceedings and keeps a journal with recorded yeas and nays when constitutionally required',
		independence:
			'I.6: compensation, legislative privilege, the Ineligibility Clause, and the Incompatibility Clause protect the legislative function and separate offices',
		revenueOrigination:
			'I.7.1: bills for raising revenue originate in the House, while the Senate may propose or concur with amendments',
		bicameralismAndPresentment:
			'I.7.2-3: legislation requires passage of one text by both chambers and constitutionally valid presentment to the President',
		enumeratedPowers:
			'I.8: Congress legislates within enumerated powers and may select necessary and proper means for carrying granted powers into execution',
		appropriations:
			'I.9.7: money is drawn from the Treasury only under appropriations made by law, with a regular public statement and account',
		federalProhibitions:
			'I.9: federal power remains subject to direct prohibitions including bills of attainder, ex post facto penal laws, export taxes, port preferences, and titles of nobility',
		stateProhibitions:
			'I.10: states are subject to absolute prohibitions and to specified actions requiring congressional consent',
		impeachment:
			'I.2.5 and I.3.6-7: the House impeaches, the Senate tries, conviction requires two thirds of Senators present, and judgment is limited to removal and possible disqualification',
	},
	amendments: {
		thirteenth:
			'Amendment XIII supersedes constitutional protection of slavery and authorizes congressional enforcement of abolition',
		fourteenth:
			'Amendment XIV replaces the original apportionment rule, adds qualification limits, and supplies congressional enforcement power',
		sixteenth:
			'Amendment XVI permits federal income taxes without apportionment among the states or regard to a census',
		seventeenth:
			'Amendment XVII establishes direct election of Senators while preserving equal state representation and six-year staggered terms',
		twentieth:
			'Amendment XX fixes the modern start and end of congressional terms and requires Congress to assemble at least annually',
		twentySeventh:
			'Amendment XXVII delays laws varying congressional compensation until an intervening House election',
	},
	doctrine: {
		defaultMajority:
			'When the Constitution specifies no different threshold, a quorum-enabled chamber acts by a majority of members voting',
		exactText:
			'Bicameralism requires House and Senate approval of the same legislative text before presentment',
		necessaryAndProper:
			'A necessary-and-proper measure must carry a granted power into execution through a fitting means and cannot supply an independent legislative end',
		antiCommandeeringOfJudgment:
			'A legislature creates general law and cannot replace adjudication with a named punishment imposed without judicial trial',
		presentment:
			'Signature, regular veto, enactment after ten days excluding Sundays, pocket veto, and bicameral override are distinct constitutional routes',
	},
	engineering: {
		competenceBeforeProcedure:
			'Constitution of Code I.1: an authenticated procedure cannot cure the absence of authority over subject and scope',
		independentConsents:
			'Constitution of Code I.2: independent approvals remain separately attributable and must bind the same exact revision',
		journalEvidence:
			'Constitution of Code I.2 and I.5: a journal proves recorded procedural events but does not manufacture competence or material validity',
		derivativeMeans:
			'Constitution of Code I.3: implementation mechanisms derive authority from an identified norm and cannot silently redefine its end, scope, or consequences',
		protectedResources:
			'Constitution of Code I.4: access to a common resource does not itself authorize disposition; a bounded act and auditable ledger are required',
		sourcePreservingLaw:
			'Constitution of Code I.2: an enacted law preserves root, bill, exact text, chamber records, presentment route, effective time, and amendment lineage',
		wardenBoundary:
			'WARDEN verifies legislative invariants but cannot supply political consent, invent competence, decide disputed material justice, or convert a blocked bill into law',
	},
});

export const CHAMBERS = Object.freeze(['house', 'senate']);

export const ENUMERATED_POWERS = Object.freeze([
	'tax-spend-general-welfare',
	'borrow',
	'commerce-foreign-interstate-tribal',
	'naturalization-bankruptcy',
	'coin-money-standards',
	'counterfeiting',
	'post-offices-roads',
	'copyright-patent',
	'inferior-tribunals',
	'piracy-law-of-nations',
	'declare-war',
	'raise-support-armies',
	'provide-maintain-navy',
	'armed-forces-rules',
	'militia-call',
	'militia-organization',
	'district-federal-property',
]);

export const AMENDMENT_ENFORCEMENT_POWERS = Object.freeze([
	'amendment-xiii-enforcement',
	'amendment-xiv-enforcement',
	'amendment-xv-enforcement',
	'amendment-xix-enforcement',
	'amendment-xxiii-enforcement',
	'amendment-xxiv-enforcement',
	'amendment-xxvi-enforcement',
]);

export const FEDERAL_PROHIBITIONS = Object.freeze([
	'bill-of-attainder',
	'ex-post-facto-penal-law',
	'unjustified-habeas-suspension',
	'unapportioned-direct-tax-outside-amendment-xvi',
	'tax-on-exports',
	'port-preference',
	'treasury-withdrawal-without-appropriation',
	'title-of-nobility',
]);

export const STATE_ABSOLUTE_PROHIBITIONS = Object.freeze([
	'treaty-alliance-confederation',
	'letters-of-marque-or-reprisal',
	'coin-money',
	'emit-bills-of-credit',
	'non-gold-silver-legal-tender',
	'bill-of-attainder',
	'ex-post-facto-law',
	'impair-contract-obligation',
	'title-of-nobility',
]);

export const STATE_CONSENT_ACTIONS = Object.freeze([
	'import-export-duty-beyond-inspection',
	'duty-of-tonnage',
	'keep-troops-or-warships-in-peace',
	'agreement-or-compact',
	'engage-in-war',
]);

const BILL_KINDS = Object.freeze([
	'ordinary',
	'revenue',
	'appropriation',
	'office-establishment',
	'military-authorization',
	'succession',
	'judiciary-organization',
	'omnibus',
]);

const LEGISLATIVE_OUTPUTS = Object.freeze([
	'general-rule',
	'revenue',
	'appropriation',
	'office-establishment',
	'military-authorization',
	'succession-plan',
	'inferior-courts',
]);

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 requirePositiveInteger(value, label) {
	if (!Number.isInteger(value) || value <= 0) {
		throw new TypeError(`${label} must be a positive integer`);
	}
}

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

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) {
	requireObject(root, 'normativeRoot');
	requireNonEmptyString(root.constitutionId, 'normativeRoot.constitutionId');
	requireNonEmptyString(root.digest, 'normativeRoot.digest');
	requireNonEmptyString(root.status, 'normativeRoot.status');

	if (root.status !== 'in-force') {
		throw new TypeError('Legislation requires a normative root in force');
	}
}

function snapshotRoot(root) {
	return {
		constitutionId: root.constitutionId,
		digest: root.digest,
		status: root.status,
		lineage: Array.isArray(root.lineage) ? [...root.lineage] : [],
	};
}

function normalizeChamber(chamber, expectedKind) {
	requireObject(chamber, expectedKind);
	requireNonEmptyString(chamber.id, `${expectedKind}.id`);
	requirePositiveInteger(chamber.totalSeats, `${expectedKind}.totalSeats`);
	requirePositiveInteger(chamber.seatedMembers, `${expectedKind}.seatedMembers`);

	if (chamber.seatedMembers > chamber.totalSeats) {
		throw new TypeError(`${expectedKind}.seatedMembers cannot exceed total seats`);
	}

	if (chamber.electionsAuthenticated !== true) {
		throw new TypeError(`${expectedKind} lacks authenticated elections or appointments`);
	}

	if (chamber.qualificationsVerified !== true) {
		throw new TypeError(`${expectedKind} lacks verified constitutional qualifications`);
	}

	if (chamber.fourteenthAmendmentScreened !== true) {
		throw new TypeError(`${expectedKind} lacks an Amendment XIV qualification screen`);
	}

	if (expectedKind === 'house') {
		if (
			chamber.representation !== 'population-apportioned' ||
			chamber.censusApportionmentVerified !== true
		) {
			throw new TypeError(
				'House representation must be population-apportioned under a verified census rule',
			);
		}
	} else if (
		chamber.representation !== 'equal-state' ||
		chamber.equalStateRepresentationVerified !== true ||
		chamber.seventeenthAmendmentElectionVerified !== true ||
		chamber.classesContinuityVerified !== true
	) {
		throw new TypeError(
			'Senate requires equal state representation, direct election, and staggered continuity',
		);
	}

	return {
		id: chamber.id,
		kind: expectedKind,
		totalSeats: chamber.totalSeats,
		seatedMembers: chamber.seatedMembers,
		representation: chamber.representation,
		electionsAuthenticated: true,
		qualificationsVerified: true,
		fourteenthAmendmentScreened: true,
		censusApportionmentVerified: expectedKind === 'house' ? true : null,
		equalStateRepresentationVerified: expectedKind === 'senate' ? true : null,
		seventeenthAmendmentElectionVerified: expectedKind === 'senate' ? true : null,
		classesContinuityVerified: expectedKind === 'senate' ? true : null,
		presidingOfficerId: chamber.presidingOfficerId ?? null,
	};
}

function congressContent(congress) {
	return {
		congressId: congress.congressId,
		normativeRoot: congress.normativeRoot,
		term: congress.term,
		house: congress.house,
		senate: congress.senate,
	};
}

export function constituteCongress({ normativeRoot, congressId, term, house, senate }) {
	assertNormativeRoot(normativeRoot);
	requireNonEmptyString(congressId, 'congressId');
	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('Congressional term must end after it begins');
	}

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

	const normalized = {
		congressId,
		normativeRoot: snapshotRoot(normativeRoot),
		term: {
			startsAt: term.startsAt,
			endsAt: term.endsAt,
			twentiethAmendmentScheduleVerified: true,
			annualAssemblyProvided: term.annualAssemblyProvided === true,
		},
		house: normalizeChamber(house, 'house'),
		senate: normalizeChamber(senate, 'senate'),
	};

	if (!normalized.term.annualAssemblyProvided) {
		throw new TypeError('Congress must provide for constitutionally required annual assembly');
	}

	return deepFreeze({
		status: 'congress-constituted',
		...normalized,
		congressDigest: digest(normalized),
		trace: [
			ARTICLE_I.rules.vesting,
			ARTICLE_I.rules.house,
			ARTICLE_I.rules.senate,
			ARTICLE_I.amendments.fourteenth,
			ARTICLE_I.amendments.seventeenth,
			ARTICLE_I.amendments.twentieth,
		],
	});
}

function assertCongress(congress) {
	requireObject(congress, 'congress');

	if (congress.status !== 'congress-constituted') {
		throw new TypeError('Congress is not constituted');
	}

	assertNormativeRoot(congress.normativeRoot);

	if (digest(congressContent(congress)) !== congress.congressDigest) {
		throw new TypeError('Congressional snapshot integrity check failed');
	}
}

function getChamber(congress, chamberKind) {
	if (!CHAMBERS.includes(chamberKind)) {
		throw new TypeError(`Unsupported chamber: ${chamberKind}`);
	}

	return congress[chamberKind];
}

function requiredYeasFor(threshold, membersPresent) {
	if (threshold === 'simple-majority') {
		return Math.floor(membersPresent / 2) + 1;
	}

	if (threshold === 'two-thirds-present') {
		return Math.ceil((membersPresent * 2) / 3);
	}

	throw new TypeError(`Unsupported vote threshold: ${threshold}`);
}

function normalizeVote({ congress, chamberKind, questionDigest, vote, threshold }) {
	const chamber = getChamber(congress, chamberKind);
	requireObject(vote, 'vote');
	requireNonEmptyString(questionDigest, 'questionDigest');
	requireNonEmptyString(vote.id, 'vote.id');
	requireNonEmptyString(vote.sessionId, 'vote.sessionId');
	requireIsoDate(vote.recordedAt, 'vote.recordedAt');
	requireNonNegativeInteger(vote.membersPresent, 'vote.membersPresent');
	requireNonNegativeInteger(vote.yeas, 'vote.yeas');
	requireNonNegativeInteger(vote.nays, 'vote.nays');
	requireNonNegativeInteger(vote.abstentions, 'vote.abstentions');

	if (vote.authenticated !== true || vote.journalPublished !== true) {
		throw new TypeError('Chamber vote requires authentication and a published journal entry');
	}

	if (vote.chamber !== chamberKind || vote.questionDigest !== questionDigest) {
		throw new TypeError('Chamber vote addresses another chamber or question revision');
	}

	if (vote.membersPresent > chamber.seatedMembers) {
		throw new TypeError('Vote reports more members present than are seated');
	}

	if (vote.yeas + vote.nays + vote.abstentions !== vote.membersPresent) {
		throw new TypeError('Vote totals do not equal the number of members present');
	}

	const quorum = Math.floor(chamber.seatedMembers / 2) + 1;

	if (vote.membersPresent < quorum || vote.quorumVerified !== true) {
		throw new TypeError(`${chamberKind} vote lacks a constitutional quorum`);
	}

	if (threshold === 'two-thirds-present' && vote.yeasAndNaysRecorded !== true) {
		throw new TypeError('A two-thirds vote requires recorded yeas and nays');
	}

	const requiredYeas = requiredYeasFor(threshold, vote.membersPresent);

	return {
		id: vote.id,
		chamber: chamberKind,
		sessionId: vote.sessionId,
		questionDigest,
		membersPresent: vote.membersPresent,
		quorum,
		quorumVerified: true,
		yeas: vote.yeas,
		nays: vote.nays,
		abstentions: vote.abstentions,
		threshold,
		requiredYeas,
		passed: vote.yeas >= requiredYeas,
		journalEntryId: vote.journalEntryId ?? vote.id,
		journalPublished: true,
		yeasAndNaysRecorded: vote.yeasAndNaysRecorded === true,
		recordedAt: vote.recordedAt,
		authenticated: true,
	};
}

export function recordChamberVote({
	congress,
	chamber,
	questionDigest,
	vote,
	threshold = 'simple-majority',
}) {
	assertCongress(congress);
	const normalized = normalizeVote({
		congress,
		chamberKind: chamber,
		questionDigest,
		vote,
		threshold,
	});

	return deepFreeze({
		status: normalized.passed ? 'question-passed' : 'question-rejected',
		congressDigest: congress.congressDigest,
		...normalized,
		voteDigest: digest(normalized),
		trace: [ARTICLE_I.rules.quorumAndJournal, ARTICLE_I.engineering.journalEvidence],
	});
}

function normalizePowerClaim(powerClaim) {
	requireObject(powerClaim, 'bill.powerClaim');
	requireUniqueStrings(powerClaim.bases, 'bill.powerClaim.bases');

	if (powerClaim.bases.length === 0) {
		throw new TypeError('Bill must identify at least one legislative power');
	}

	const granted = new Set([...ENUMERATED_POWERS, ...AMENDMENT_ENFORCEMENT_POWERS]);
	const unsupported = powerClaim.bases.filter(
		(basis) => basis !== 'necessary-and-proper' && !granted.has(basis),
	);
	const issues = unsupported.map((basis) => `unsupported-power:${basis}`);

	let necessaryAndProper = null;

	if (powerClaim.bases.includes('necessary-and-proper')) {
		requireObject(powerClaim.necessaryAndProper, 'bill.powerClaim.necessaryAndProper');
		const claim = powerClaim.necessaryAndProper;
		requireNonEmptyString(claim.linkedPower, 'necessaryAndProper.linkedPower');

		if (!granted.has(claim.linkedPower)) {
			issues.push(`necessary-and-proper-without-granted-end:${claim.linkedPower}`);
		}

		for (const field of [
			'legitimateEndVerified',
			'plainlyAdapted',
			'notProhibited',
			'consistentWithConstitution',
		]) {
			requireBoolean(claim[field], `necessaryAndProper.${field}`);

			if (!claim[field]) {
				issues.push(`necessary-and-proper-failed:${field}`);
			}
		}

		necessaryAndProper = {
			linkedPower: claim.linkedPower,
			legitimateEndVerified: claim.legitimateEndVerified,
			plainlyAdapted: claim.plainlyAdapted,
			notProhibited: claim.notProhibited,
			consistentWithConstitution: claim.consistentWithConstitution,
		};
	}

	return {
		normalized: {
			bases: [...powerClaim.bases],
			necessaryAndProper,
		},
		issues,
	};
}

function federalRestrictionIssues(restrictions = {}) {
	requireObject(restrictions, 'bill.restrictions');
	const issues = [];

	if (
		restrictions.namedPersonOrClosedGroup === true &&
		restrictions.punishmentWithoutTrial === true
	) {
		issues.push('bill-of-attainder');
	}

	if (restrictions.retroactive === true && restrictions.penal === true) {
		issues.push('ex-post-facto-penal-law');
	}

	if (
		restrictions.suspendsHabeas === true &&
		!(
			restrictions.rebellionOrInvasionVerified === true &&
			restrictions.publicSafetyRequiresSuspension === true
		)
	) {
		issues.push('unjustified-habeas-suspension');
	}

	if (
		restrictions.directTax === true &&
		restrictions.incomeTaxUnderAmendmentXVI !== true &&
		restrictions.apportionedByCensus !== true
	) {
		issues.push('unapportioned-direct-tax-outside-amendment-xvi');
	}

	if (restrictions.taxOnStateExports === true) {
		issues.push('tax-on-exports');
	}

	if (restrictions.portPreference === true) {
		issues.push('port-preference');
	}

	if (restrictions.treasuryWithdrawalWithoutAppropriation === true) {
		issues.push('treasury-withdrawal-without-appropriation');
	}

	if (restrictions.titleOfNobility === true) {
		issues.push('title-of-nobility');
	}

	return [...new Set(issues)];
}

function initialVersionContent({ billId, rootDigest, text, createdAt }) {
	return {
		versionId: `${billId}:introduced`,
		billId,
		rootDigest,
		text,
		textDigest: digest({ text }),
		createdByChamber: null,
		parentVersionDigest: null,
		amendments: [],
		createdAt,
	};
}

function introducedBillContent(bill) {
	return {
		billId: bill.billId,
		congressDigest: bill.congressDigest,
		rootDigest: bill.rootDigest,
		title: bill.title,
		kind: bill.kind,
		originatingChamber: bill.originatingChamber,
		introducedBy: bill.introducedBy,
		introducedAt: bill.introducedAt,
		effectiveAt: bill.effectiveAt,
		scope: bill.scope,
		outputs: bill.outputs,
		powerClaim: bill.powerClaim,
		restrictions: bill.restrictions,
		initialVersion: bill.initialVersion,
	};
}

export function introduceBill({ congress, bill }) {
	assertCongress(congress);
	requireObject(bill, 'bill');
	requireNonEmptyString(bill.id, 'bill.id');
	requireNonEmptyString(bill.title, 'bill.title');
	requireNonEmptyString(bill.kind, 'bill.kind');
	requireNonEmptyString(bill.originatingChamber, 'bill.originatingChamber');
	requireNonEmptyString(bill.introducedBy, 'bill.introducedBy');
	requireIsoDate(bill.introducedAt, 'bill.introducedAt');
	requireIsoDate(bill.effectiveAt, 'bill.effectiveAt');
	requireNonEmptyString(bill.scope, 'bill.scope');
	requireNonEmptyString(bill.text, 'bill.text');
	requireUniqueStrings(bill.outputs, 'bill.outputs');

	if (!BILL_KINDS.includes(bill.kind)) {
		throw new TypeError(`Unsupported bill kind: ${bill.kind}`);
	}

	if (!CHAMBERS.includes(bill.originatingChamber)) {
		throw new TypeError(`Unsupported originating chamber: ${bill.originatingChamber}`);
	}

	for (const output of bill.outputs) {
		if (!LEGISLATIVE_OUTPUTS.includes(output)) {
			throw new TypeError(`Unsupported legislative output: ${output}`);
		}
	}

	if (bill.rootDigest !== congress.normativeRoot.digest) {
		throw new TypeError('Bill belongs to another normative root');
	}

	const { normalized: powerClaim, issues: powerIssues } = normalizePowerClaim(bill.powerClaim);
	const restrictions = { ...(bill.restrictions ?? {}) };
	const issues = [...powerIssues, ...federalRestrictionIssues(restrictions)];

	if (
		(bill.kind === 'revenue' || bill.outputs.includes('revenue')) &&
		bill.originatingChamber !== 'house'
	) {
		issues.push('revenue-bill-did-not-originate-in-house');
	}

	const initialVersion = initialVersionContent({
		billId: bill.id,
		rootDigest: bill.rootDigest,
		text: bill.text,
		createdAt: bill.introducedAt,
	});
	const normalized = {
		billId: bill.id,
		congressDigest: congress.congressDigest,
		rootDigest: bill.rootDigest,
		title: bill.title,
		kind: bill.kind,
		originatingChamber: bill.originatingChamber,
		introducedBy: bill.introducedBy,
		introducedAt: bill.introducedAt,
		effectiveAt: bill.effectiveAt,
		scope: bill.scope,
		outputs: [...bill.outputs],
		powerClaim,
		restrictions,
		initialVersion: {
			...initialVersion,
			versionDigest: digest(initialVersion),
		},
	};
	const billDigest = digest(normalized);

	if (issues.length > 0) {
		return deepFreeze({
			status: 'bill-blocked',
			...normalized,
			billDigest,
			issues: [...new Set(issues)],
			handoff: 'article-i:revise-or-article-iii:resolve-if-case-or-controversy',
			trace: [
				ARTICLE_I.rules.enumeratedPowers,
				ARTICLE_I.rules.federalProhibitions,
				ARTICLE_I.engineering.competenceBeforeProcedure,
				ARTICLE_I.engineering.wardenBoundary,
			],
		});
	}

	return deepFreeze({
		status: 'bill-introduced',
		...normalized,
		billDigest,
		issues: [],
		trace: [
			ARTICLE_I.rules.vesting,
			ARTICLE_I.rules.revenueOrigination,
			ARTICLE_I.rules.enumeratedPowers,
			ARTICLE_I.engineering.competenceBeforeProcedure,
		],
	});
}

function assertIntroducedBill(congress, bill) {
	requireObject(bill, 'bill');

	if (bill.status !== 'bill-introduced') {
		throw new TypeError('Only a constitutionally screenable introduced bill may proceed');
	}

	if (
		bill.congressDigest !== congress.congressDigest ||
		bill.rootDigest !== congress.normativeRoot.digest
	) {
		throw new TypeError('Bill and Congress do not share one authority snapshot');
	}

	if (digest(introducedBillContent(bill)) !== bill.billDigest) {
		throw new TypeError('Introduced bill integrity check failed');
	}
}

function versionContent(version) {
	return {
		versionId: version.versionId,
		billId: version.billId,
		rootDigest: version.rootDigest,
		text: version.text,
		textDigest: version.textDigest,
		createdByChamber: version.createdByChamber,
		parentVersionDigest: version.parentVersionDigest,
		amendments: version.amendments,
		createdAt: version.createdAt,
	};
}

function assertVersion(bill, version) {
	requireObject(version, 'version');

	if (version.billId !== bill.billId || version.rootDigest !== bill.rootDigest) {
		throw new TypeError('Bill version belongs to another bill or normative root');
	}

	if (digest({ text: version.text }) !== version.textDigest) {
		throw new TypeError('Bill version text digest does not match its text');
	}

	if (digest(versionContent(version)) !== version.versionDigest) {
		throw new TypeError('Bill version integrity check failed');
	}
}

export function createBillVersion({ bill, chamber, text, amendments = [], createdAt }) {
	requireObject(bill, 'bill');

	if (bill.status !== 'bill-introduced') {
		throw new TypeError('A bill version requires an introduced bill');
	}

	if (!CHAMBERS.includes(chamber)) {
		throw new TypeError(`Unsupported chamber: ${chamber}`);
	}

	requireNonEmptyString(text, 'text');
	requireArray(amendments, 'amendments');
	requireIsoDate(createdAt, 'createdAt');

	const normalizedAmendments = amendments.map((amendment, index) => {
		requireObject(amendment, `amendments[${index}]`);
		requireNonEmptyString(amendment.id, `amendments[${index}].id`);
		requireNonEmptyString(amendment.description, `amendments[${index}].description`);
		return { id: amendment.id, description: amendment.description };
	});
	const parent = bill.initialVersion;
	const content = {
		versionId: `${bill.billId}:${chamber}:${digest({ text }).slice(7, 19)}`,
		billId: bill.billId,
		rootDigest: bill.rootDigest,
		text,
		textDigest: digest({ text }),
		createdByChamber: chamber,
		parentVersionDigest: parent.versionDigest,
		amendments: normalizedAmendments,
		createdAt,
	};

	return deepFreeze({ ...content, versionDigest: digest(content) });
}

function chamberActionContent(action) {
	return {
		billId: action.billId,
		billDigest: action.billDigest,
		congressDigest: action.congressDigest,
		rootDigest: action.rootDigest,
		chamber: action.chamber,
		version: action.version,
		vote: action.vote,
	};
}

export function passChamber({ congress, bill, chamber, version, vote, priorHouseAction = null }) {
	assertCongress(congress);
	assertIntroducedBill(congress, bill);
	assertVersion(bill, version);

	if (version.createdByChamber !== chamber) {
		throw new TypeError('Bill version is attributed to another chamber');
	}

	if (chamber === 'senate' && (bill.kind === 'revenue' || bill.outputs.includes('revenue'))) {
		if (
			!priorHouseAction ||
			priorHouseAction.status !== 'chamber-passed' ||
			priorHouseAction.chamber !== 'house' ||
			priorHouseAction.billDigest !== bill.billDigest
		) {
			throw new TypeError('Senate consideration of a revenue bill requires prior House passage');
		}
	}

	const voteRecord = recordChamberVote({
		congress,
		chamber,
		questionDigest: version.versionDigest,
		vote,
		threshold: 'simple-majority',
	});
	const content = {
		billId: bill.billId,
		billDigest: bill.billDigest,
		congressDigest: congress.congressDigest,
		rootDigest: bill.rootDigest,
		chamber,
		version,
		vote: voteRecord,
	};

	return deepFreeze({
		status: voteRecord.passed ? 'chamber-passed' : 'chamber-rejected',
		...content,
		actionDigest: digest(content),
		trace: [
			ARTICLE_I.rules.quorumAndJournal,
			ARTICLE_I.rules.bicameralismAndPresentment,
			ARTICLE_I.engineering.independentConsents,
		],
	});
}

function assertChamberAction(congress, bill, action, expectedChamber) {
	requireObject(action, `${expectedChamber}Action`);

	if (
		action.status !== 'chamber-passed' ||
		action.chamber !== expectedChamber ||
		action.billDigest !== bill.billDigest ||
		action.congressDigest !== congress.congressDigest ||
		action.rootDigest !== bill.rootDigest
	) {
		throw new TypeError(`${expectedChamber} action is absent, rejected, or mismatched`);
	}

	if (digest(chamberActionContent(action)) !== action.actionDigest) {
		throw new TypeError(`${expectedChamber} action integrity check failed`);
	}
}

function enrolledContent(enrolled) {
	return {
		enrollmentId: enrolled.enrollmentId,
		billId: enrolled.billId,
		billDigest: enrolled.billDigest,
		congressDigest: enrolled.congressDigest,
		rootDigest: enrolled.rootDigest,
		originatingChamber: enrolled.originatingChamber,
		title: enrolled.title,
		kind: enrolled.kind,
		text: enrolled.text,
		textDigest: enrolled.textDigest,
		versionDigest: enrolled.versionDigest,
		houseActionDigest: enrolled.houseActionDigest,
		senateActionDigest: enrolled.senateActionDigest,
		effectiveAt: enrolled.effectiveAt,
		scope: enrolled.scope,
		outputs: enrolled.outputs,
		powerClaim: enrolled.powerClaim,
		enrolledAt: enrolled.enrolledAt,
	};
}

export function enrollBill({ congress, bill, houseAction, senateAction, enrolledAt }) {
	assertCongress(congress);
	assertIntroducedBill(congress, bill);
	assertChamberAction(congress, bill, houseAction, 'house');
	assertChamberAction(congress, bill, senateAction, 'senate');
	requireIsoDate(enrolledAt, 'enrolledAt');

	if (houseAction.version.textDigest !== senateAction.version.textDigest) {
		return deepFreeze({
			status: 'bicameral-disagreement',
			billId: bill.billId,
			billDigest: bill.billDigest,
			houseVersionDigest: houseAction.version.versionDigest,
			senateVersionDigest: senateAction.version.versionDigest,
			handoff: 'congress:reconcile-and-repass-one-text',
			trace: [ARTICLE_I.doctrine.exactText, ARTICLE_I.engineering.independentConsents],
		});
	}

	const content = {
		enrollmentId: `enrollment:${bill.billId}`,
		billId: bill.billId,
		billDigest: bill.billDigest,
		congressDigest: congress.congressDigest,
		rootDigest: bill.rootDigest,
		originatingChamber: bill.originatingChamber,
		title: bill.title,
		kind: bill.kind,
		text: houseAction.version.text,
		textDigest: houseAction.version.textDigest,
		versionDigest: digest({
			billId: bill.billId,
			rootDigest: bill.rootDigest,
			textDigest: houseAction.version.textDigest,
		}),
		houseActionDigest: houseAction.actionDigest,
		senateActionDigest: senateAction.actionDigest,
		effectiveAt: bill.effectiveAt,
		scope: bill.scope,
		outputs: [...bill.outputs],
		powerClaim: bill.powerClaim,
		enrolledAt,
	};

	return deepFreeze({
		status: 'bill-enrolled',
		...content,
		enrolledDigest: digest(content),
		trace: [
			ARTICLE_I.rules.bicameralismAndPresentment,
			ARTICLE_I.doctrine.exactText,
			ARTICLE_I.engineering.sourcePreservingLaw,
		],
	});
}

function assertEnrolledBill(congress, enrolled) {
	requireObject(enrolled, 'enrolled');

	if (enrolled.status !== 'bill-enrolled') {
		throw new TypeError('Presentment requires an enrolled bill');
	}

	if (
		enrolled.congressDigest !== congress.congressDigest ||
		enrolled.rootDigest !== congress.normativeRoot.digest
	) {
		throw new TypeError('Enrolled bill belongs to another Congress or normative root');
	}

	if (digest(enrolledContent(enrolled)) !== enrolled.enrolledDigest) {
		throw new TypeError('Enrolled bill integrity check failed');
	}
}

function countConstitutionalDays(presentedAt, evaluatedAt) {
	const start = new Date(presentedAt);
	const end = new Date(evaluatedAt);

	if (end.getTime() < start.getTime()) {
		throw new TypeError('Presentment evaluation cannot precede presentment');
	}

	const cursor = new Date(
		Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate() + 1),
	);
	const finalDay = Date.UTC(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate());
	let days = 0;

	while (cursor.getTime() <= finalDay) {
		if (cursor.getUTCDay() !== 0) {
			days += 1;
		}

		cursor.setUTCDate(cursor.getUTCDate() + 1);
	}

	return days;
}

function lawContent(law) {
	return {
		lawId: law.lawId,
		congressDigest: law.congressDigest,
		rootDigest: law.rootDigest,
		billId: law.billId,
		billDigest: law.billDigest,
		enrolledDigest: law.enrolledDigest,
		title: law.title,
		kind: law.kind,
		text: law.text,
		textDigest: law.textDigest,
		versionDigest: law.versionDigest,
		originatingChamber: law.originatingChamber,
		houseActionDigest: law.houseActionDigest,
		senateActionDigest: law.senateActionDigest,
		presentmentDigest: law.presentmentDigest,
		enactmentRoute: law.enactmentRoute,
		enactedAt: law.enactedAt,
		effectiveAt: law.effectiveAt,
		scope: law.scope,
		outputs: law.outputs,
		powerClaim: law.powerClaim,
		statuteStatus: law.statuteStatus,
	};
}

function createLaw({ enrolled, presentmentDigest, enactmentRoute, enactedAt }) {
	const content = {
		lawId: `law:${enrolled.billId}`,
		congressDigest: enrolled.congressDigest,
		rootDigest: enrolled.rootDigest,
		billId: enrolled.billId,
		billDigest: enrolled.billDigest,
		enrolledDigest: enrolled.enrolledDigest,
		title: enrolled.title,
		kind: enrolled.kind,
		text: enrolled.text,
		textDigest: enrolled.textDigest,
		versionDigest: enrolled.versionDigest,
		originatingChamber: enrolled.originatingChamber,
		houseActionDigest: enrolled.houseActionDigest,
		senateActionDigest: enrolled.senateActionDigest,
		presentmentDigest,
		enactmentRoute,
		enactedAt,
		effectiveAt: enrolled.effectiveAt,
		scope: enrolled.scope,
		outputs: [...enrolled.outputs],
		powerClaim: enrolled.powerClaim,
		statuteStatus: 'in-force',
	};

	return deepFreeze({
		status: 'law-enacted',
		...content,
		lawDigest: digest(content),
		handoff: 'article-ii:faithful-execution',
		trace: [ARTICLE_I.rules.bicameralismAndPresentment, ARTICLE_I.engineering.sourcePreservingLaw],
	});
}

function presentmentContent(record) {
	return {
		presentmentId: record.presentmentId,
		enrolledDigest: record.enrolledDigest,
		presentedAt: record.presentedAt,
		action: record.action,
	};
}

export function presentBill({ congress, enrolled, presentedAt, presidentAction }) {
	assertCongress(congress);
	assertEnrolledBill(congress, enrolled);
	requireIsoDate(presentedAt, 'presentedAt');
	requireObject(presidentAction, 'presidentAction');
	requireNonEmptyString(presidentAction.kind, 'presidentAction.kind');

	if (!['sign', 'veto', 'no-action'].includes(presidentAction.kind)) {
		throw new TypeError(`Unsupported presidential action: ${presidentAction.kind}`);
	}

	if (Date.parse(presentedAt) < Date.parse(enrolled.enrolledAt)) {
		throw new TypeError('Presentment cannot precede enrollment');
	}

	let action;

	if (presidentAction.kind === 'sign') {
		requireNonEmptyString(presidentAction.actorId, 'presidentAction.actorId');
		requireIsoDate(presidentAction.actedAt, 'presidentAction.actedAt');

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

		action = {
			kind: 'sign',
			actorId: presidentAction.actorId,
			actedAt: presidentAction.actedAt,
			authenticated: true,
		};
		const record = {
			presentmentId: `presentment:${enrolled.billId}`,
			enrolledDigest: enrolled.enrolledDigest,
			presentedAt,
			action,
		};
		const presentmentDigest = digest(presentmentContent(record));

		return createLaw({
			enrolled,
			presentmentDigest,
			enactmentRoute: 'presidential-signature',
			enactedAt: presidentAction.actedAt,
		});
	}

	if (presidentAction.kind === 'veto') {
		requireNonEmptyString(presidentAction.actorId, 'presidentAction.actorId');
		requireIsoDate(presidentAction.actedAt, 'presidentAction.actedAt');
		requireNonEmptyString(presidentAction.returnedToChamber, 'presidentAction.returnedToChamber');
		requireNonEmptyString(presidentAction.objections, 'presidentAction.objections');

		if (
			presidentAction.authenticated !== true ||
			presidentAction.returnedDuringSession !== true ||
			presidentAction.returnedToChamber !== enrolled.originatingChamber
		) {
			throw new TypeError(
				'Regular veto must be authenticated and returned with objections to the originating chamber',
			);
		}

		action = {
			kind: 'veto',
			actorId: presidentAction.actorId,
			actedAt: presidentAction.actedAt,
			returnedToChamber: presidentAction.returnedToChamber,
			returnedDuringSession: true,
			objections: presidentAction.objections,
			authenticated: true,
		};
		const record = {
			presentmentId: `presentment:${enrolled.billId}`,
			enrolledDigest: enrolled.enrolledDigest,
			presentedAt,
			action,
		};
		const presentmentDigest = digest(presentmentContent(record));

		return deepFreeze({
			status: 'bill-vetoed',
			...record,
			presentmentDigest,
			enrolled,
			handoff: `article-i:${enrolled.originatingChamber}:reconsider`,
			trace: [ARTICLE_I.rules.bicameralismAndPresentment, ARTICLE_I.doctrine.presentment],
		});
	}

	requireIsoDate(presidentAction.evaluatedAt, 'presidentAction.evaluatedAt');
	requireBoolean(
		presidentAction.congressAdjournedPreventsReturn,
		'presidentAction.congressAdjournedPreventsReturn',
	);
	const constitutionalDays = countConstitutionalDays(presentedAt, presidentAction.evaluatedAt);
	action = {
		kind: 'no-action',
		evaluatedAt: presidentAction.evaluatedAt,
		constitutionalDays,
		congressAdjournedPreventsReturn: presidentAction.congressAdjournedPreventsReturn,
	};
	const record = {
		presentmentId: `presentment:${enrolled.billId}`,
		enrolledDigest: enrolled.enrolledDigest,
		presentedAt,
		action,
	};
	const presentmentDigest = digest(presentmentContent(record));

	if (constitutionalDays < 10) {
		return deepFreeze({
			status: 'presentment-pending',
			...record,
			presentmentDigest,
			remainingConstitutionalDays: 10 - constitutionalDays,
			trace: [ARTICLE_I.doctrine.presentment],
		});
	}

	if (presidentAction.congressAdjournedPreventsReturn) {
		return deepFreeze({
			status: 'bill-pocket-vetoed',
			...record,
			presentmentDigest,
			enrolled,
			handoff: 'article-i:new-legislative-process',
			trace: [ARTICLE_I.rules.bicameralismAndPresentment, ARTICLE_I.doctrine.presentment],
		});
	}

	return createLaw({
		enrolled,
		presentmentDigest,
		enactmentRoute: 'ten-days-without-signature',
		enactedAt: presidentAction.evaluatedAt,
	});
}

export function overrideVeto({ congress, vetoed, originVote, otherVote, enactedAt }) {
	assertCongress(congress);
	requireObject(vetoed, 'vetoed');
	requireIsoDate(enactedAt, 'enactedAt');

	if (vetoed.status !== 'bill-vetoed') {
		throw new TypeError('Only a regular veto may be overridden');
	}

	assertEnrolledBill(congress, vetoed.enrolled);
	const origin = vetoed.enrolled.originatingChamber;
	const other = origin === 'house' ? 'senate' : 'house';
	const originRecord = recordChamberVote({
		congress,
		chamber: origin,
		questionDigest: vetoed.enrolled.enrolledDigest,
		vote: originVote,
		threshold: 'two-thirds-present',
	});

	if (!originRecord.passed) {
		return deepFreeze({
			status: 'veto-sustained',
			failedChamber: origin,
			presentmentDigest: vetoed.presentmentDigest,
			voteDigest: originRecord.voteDigest,
			trace: [ARTICLE_I.doctrine.presentment],
		});
	}

	const otherRecord = recordChamberVote({
		congress,
		chamber: other,
		questionDigest: vetoed.enrolled.enrolledDigest,
		vote: otherVote,
		threshold: 'two-thirds-present',
	});

	if (!otherRecord.passed) {
		return deepFreeze({
			status: 'veto-sustained',
			failedChamber: other,
			presentmentDigest: vetoed.presentmentDigest,
			originVoteDigest: originRecord.voteDigest,
			voteDigest: otherRecord.voteDigest,
			trace: [ARTICLE_I.doctrine.presentment],
		});
	}

	const overrideRecord = {
		priorPresentmentDigest: vetoed.presentmentDigest,
		originVoteDigest: originRecord.voteDigest,
		otherVoteDigest: otherRecord.voteDigest,
		enactedAt,
	};

	return createLaw({
		enrolled: vetoed.enrolled,
		presentmentDigest: digest(overrideRecord),
		enactmentRoute: 'bicameral-veto-override',
		enactedAt,
	});
}

export function legislate({
	congress,
	bill: billInput,
	houseText,
	senateText,
	houseAmendments = [],
	senateAmendments = [],
	houseVote,
	senateVote,
	houseVersionAt,
	senateVersionAt,
	enrolledAt,
	presentedAt,
	presidentAction,
}) {
	const bill = introduceBill({ congress, bill: billInput });

	if (bill.status !== 'bill-introduced') {
		return bill;
	}

	const houseVersion = createBillVersion({
		bill,
		chamber: 'house',
		text: houseText,
		amendments: houseAmendments,
		createdAt: houseVersionAt,
	});
	const houseAction = passChamber({
		congress,
		bill,
		chamber: 'house',
		version: houseVersion,
		vote: houseVote,
	});

	if (houseAction.status !== 'chamber-passed') {
		return houseAction;
	}

	const senateVersion = createBillVersion({
		bill,
		chamber: 'senate',
		text: senateText,
		amendments: senateAmendments,
		createdAt: senateVersionAt,
	});
	const senateAction = passChamber({
		congress,
		bill,
		chamber: 'senate',
		version: senateVersion,
		vote: senateVote,
		priorHouseAction: houseAction,
	});

	if (senateAction.status !== 'chamber-passed') {
		return senateAction;
	}

	const enrolled = enrollBill({
		congress,
		bill,
		houseAction,
		senateAction,
		enrolledAt,
	});

	if (enrolled.status !== 'bill-enrolled') {
		return enrolled;
	}

	return presentBill({ congress, enrolled, presentedAt, presidentAction });
}

function assertLaw(law) {
	requireObject(law, 'law');

	if (law.status !== 'law-enacted' || law.statuteStatus !== 'in-force') {
		throw new TypeError('Operation requires an enacted law in force');
	}

	if (digest(lawContent(law)) !== law.lawDigest) {
		throw new TypeError('Law integrity check failed');
	}
}

function requireLawOutput(law, output) {
	assertLaw(law);

	if (!law.outputs.includes(output)) {
		throw new TypeError(`Law does not authorize legislative output: ${output}`);
	}
}

export function authorizeAppropriation({ law, appropriation }) {
	requireLawOutput(law, 'appropriation');
	requireObject(appropriation, 'appropriation');
	requireNonEmptyString(appropriation.id, 'appropriation.id');
	requireNonEmptyString(appropriation.purpose, 'appropriation.purpose');
	requireNonEmptyString(appropriation.unit, 'appropriation.unit');
	requireIsoDate(appropriation.availableFrom, 'appropriation.availableFrom');
	requireIsoDate(appropriation.availableThrough, 'appropriation.availableThrough');
	requireNonEmptyString(appropriation.accountableOfficer, 'appropriation.accountableOfficer');
	requireNonEmptyString(appropriation.publicLedgerId, 'appropriation.publicLedgerId');

	if (typeof appropriation.maximumAmount !== 'number' || appropriation.maximumAmount <= 0) {
		throw new TypeError('appropriation.maximumAmount must be a positive number');
	}

	if (Date.parse(appropriation.availableThrough) < Date.parse(appropriation.availableFrom)) {
		throw new TypeError('Appropriation availability cannot end before it begins');
	}

	if (appropriation.publicStatementRequired !== true) {
		throw new TypeError('Appropriation must require a regular public statement and account');
	}

	const content = {
		appropriationId: appropriation.id,
		lawDigest: law.lawDigest,
		rootDigest: law.rootDigest,
		purpose: appropriation.purpose,
		maximumAmount: appropriation.maximumAmount,
		unit: appropriation.unit,
		availableFrom: appropriation.availableFrom,
		availableThrough: appropriation.availableThrough,
		accountableOfficer: appropriation.accountableOfficer,
		publicLedgerId: appropriation.publicLedgerId,
		publicStatementRequired: true,
	};

	return deepFreeze({
		status: 'appropriation-authorized',
		...content,
		appropriationDigest: digest(content),
		remainingAmount: appropriation.maximumAmount,
		trace: [ARTICLE_I.rules.appropriations, ARTICLE_I.engineering.protectedResources],
	});
}

export function establishOffice({ law, office }) {
	requireLawOutput(law, 'office-establishment');
	requireObject(office, 'office');
	requireNonEmptyString(office.id, 'office.id');
	requireNonEmptyString(office.name, 'office.name');
	requireNonEmptyString(office.classification, 'office.classification');
	requireUniqueStrings(office.capabilities, 'office.capabilities');

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

	if (
		office.classification === 'inferior' &&
		![
			'president-with-senate-consent',
			'president-alone',
			'court-of-law',
			'department-head',
		].includes(office.appointmentVestedIn)
	) {
		throw new TypeError('Inferior office requires a constitutionally permitted appointing actor');
	}

	const content = {
		id: office.id,
		name: office.name,
		classification: office.classification,
		establishedByLaw: true,
		establishmentDigest: law.lawDigest,
		establishmentRootDigest: law.rootDigest,
		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],
	};

	return deepFreeze(content);
}

export function authorizeMilitaryAction({ law, authorization }) {
	requireLawOutput(law, 'military-authorization');
	requireObject(authorization, 'authorization');
	requireNonEmptyString(authorization.id, 'authorization.id');
	requireNonEmptyString(authorization.scope, 'authorization.scope');
	requireIsoDate(authorization.authorizedAt, 'authorization.authorizedAt');

	if (authorization.scopeIncludesOrder !== true) {
		throw new TypeError(
			'Military authorization must verify that the contemplated order lies within scope',
		);
	}

	return deepFreeze({
		id: authorization.id,
		kind: 'congress-authorized',
		authenticated: true,
		statuteStatus: 'in-force',
		scope: authorization.scope,
		scopeIncludesOrder: true,
		calledIntoActualService: authorization.calledIntoActualService === true,
		statuteDigest: law.lawDigest,
		rootDigest: law.rootDigest,
		authorizedAt: authorization.authorizedAt,
	});
}

export function createSuccessionPlan({ law, entries }) {
	requireLawOutput(law, 'succession-plan');
	requireArray(entries, 'entries');

	if (entries.length === 0) {
		throw new TypeError('Succession plan requires at least one eligible office entry');
	}

	const normalizedEntries = entries.map((entry, index) => {
		requireObject(entry, `entries[${index}]`);
		requireNonEmptyString(entry.officerId, `entries[${index}].officerId`);
		requireNonEmptyString(entry.officeId, `entries[${index}].officeId`);
		requireBoolean(entry.eligibleToAct, `entries[${index}].eligibleToAct`);
		return {
			officerId: entry.officerId,
			officeId: entry.officeId,
			eligibleToAct: entry.eligibleToAct,
		};
	});

	if (new Set(normalizedEntries.map((entry) => entry.officeId)).size !== normalizedEntries.length) {
		throw new TypeError('Succession plan cannot repeat an office');
	}

	return deepFreeze({
		establishedByLaw: true,
		statuteDigest: law.lawDigest,
		rootDigest: law.rootDigest,
		entries: normalizedEntries,
	});
}

export function organizeInferiorCourts({ law, courts }) {
	requireLawOutput(law, 'inferior-courts');
	requireArray(courts, 'courts');

	if (courts.length === 0) {
		throw new TypeError('Judiciary organization law must establish at least one inferior court');
	}

	const normalized = courts.map((court, index) => {
		requireObject(court, `courts[${index}]`);
		requireNonEmptyString(court.id, `courts[${index}].id`);
		requireNonEmptyString(court.name, `courts[${index}].name`);
		requirePositiveInteger(court.tier, `courts[${index}].tier`);
		requireUniqueStrings(court.originalHeads, `courts[${index}].originalHeads`);
		requireUniqueStrings(court.appellateHeads, `courts[${index}].appellateHeads`);
		requireUniqueStrings(court.venueStates, `courts[${index}].venueStates`);
		return {
			id: court.id,
			name: court.name,
			kind: 'inferior',
			tier: court.tier,
			articleIII: true,
			establishedBy: 'federal-statute',
			establishmentAuthenticated: true,
			establishmentDigest: law.lawDigest,
			establishmentRootDigest: law.rootDigest,
			originalHeads: [...court.originalHeads],
			appellateHeads: [...court.appellateHeads],
			venueStates: [...court.venueStates],
		};
	});

	if (new Set(normalized.map((court) => court.id)).size !== normalized.length) {
		throw new TypeError('Judiciary organization law cannot repeat a court id');
	}

	return deepFreeze(normalized);
}

function impeachmentContent(impeachment) {
	return {
		impeachmentId: impeachment.impeachmentId,
		congressDigest: impeachment.congressDigest,
		rootDigest: impeachment.rootDigest,
		subject: impeachment.subject,
		articles: impeachment.articles,
		chargeDigest: impeachment.chargeDigest,
		houseVoteDigest: impeachment.houseVoteDigest,
		impeachedAt: impeachment.impeachedAt,
	};
}

export function impeach({ congress, subject, articles, houseVote, impeachedAt }) {
	assertCongress(congress);
	requireObject(subject, 'subject');
	requireNonEmptyString(subject.id, 'subject.id');
	requireNonEmptyString(subject.officeKind, 'subject.officeKind');
	requireArray(articles, 'articles');
	requireIsoDate(impeachedAt, 'impeachedAt');

	if (articles.length === 0) {
		throw new TypeError('Impeachment requires at least one article');
	}

	const normalizedArticles = articles.map((article, index) => {
		requireObject(article, `articles[${index}]`);
		requireNonEmptyString(article.id, `articles[${index}].id`);
		requireNonEmptyString(article.ground, `articles[${index}].ground`);
		requireNonEmptyString(article.particulars, `articles[${index}].particulars`);
		return {
			id: article.id,
			ground: article.ground,
			particulars: article.particulars,
		};
	});
	const chargeDigest = digest({ subject, articles: normalizedArticles });
	const vote = recordChamberVote({
		congress,
		chamber: 'house',
		questionDigest: chargeDigest,
		vote: houseVote,
		threshold: 'simple-majority',
	});

	if (!vote.passed) {
		return deepFreeze({
			status: 'impeachment-rejected',
			subjectId: subject.id,
			chargeDigest,
			houseVoteDigest: vote.voteDigest,
			trace: [ARTICLE_I.rules.house, ARTICLE_I.rules.impeachment],
		});
	}

	const content = {
		impeachmentId: `impeachment:${subject.id}:${chargeDigest.slice(7, 19)}`,
		congressDigest: congress.congressDigest,
		rootDigest: congress.normativeRoot.digest,
		subject: { id: subject.id, officeKind: subject.officeKind },
		articles: normalizedArticles,
		chargeDigest,
		houseVoteDigest: vote.voteDigest,
		impeachedAt,
	};

	return deepFreeze({
		status: 'house-impeached',
		...content,
		impeachmentDigest: digest(content),
		handoff: 'article-i:senate-trial',
		trace: [ARTICLE_I.rules.house, ARTICLE_I.rules.impeachment],
	});
}

export function tryImpeachment({
	congress,
	impeachment,
	senateVote,
	presidingOfficer,
	triedAt,
	effectiveAt,
	disqualified = false,
}) {
	assertCongress(congress);
	requireObject(impeachment, 'impeachment');
	requireObject(presidingOfficer, 'presidingOfficer');
	requireIsoDate(triedAt, 'triedAt');
	requireIsoDate(effectiveAt, 'effectiveAt');
	requireBoolean(disqualified, 'disqualified');

	if (impeachment.status !== 'house-impeached') {
		throw new TypeError('Senate trial requires House impeachment');
	}

	if (
		impeachment.congressDigest !== congress.congressDigest ||
		impeachment.rootDigest !== congress.normativeRoot.digest ||
		digest(impeachmentContent(impeachment)) !== impeachment.impeachmentDigest
	) {
		throw new TypeError('Impeachment record does not match the current Congress and root');
	}

	requireNonEmptyString(presidingOfficer.id, 'presidingOfficer.id');
	requireNonEmptyString(presidingOfficer.role, 'presidingOfficer.role');

	if (
		impeachment.subject.officeKind === 'president' &&
		(presidingOfficer.role !== 'chief-justice' || presidingOfficer.authenticated !== true)
	) {
		throw new TypeError('The Chief Justice must preside over a presidential impeachment trial');
	}

	if (presidingOfficer.authenticated !== true) {
		throw new TypeError('Impeachment presiding officer must be authenticated');
	}

	const vote = recordChamberVote({
		congress,
		chamber: 'senate',
		questionDigest: impeachment.impeachmentDigest,
		vote: senateVote,
		threshold: 'two-thirds-present',
	});

	if (!vote.passed) {
		return deepFreeze({
			status: 'senate-acquitted',
			impeachmentDigest: impeachment.impeachmentDigest,
			senateVoteDigest: vote.voteDigest,
			triedAt,
			trace: [ARTICLE_I.rules.senate, ARTICLE_I.rules.impeachment],
		});
	}

	const record = {
		id: `impeachment-judgment:${impeachment.impeachmentId}`,
		rootDigest: congress.normativeRoot.digest,
		authenticated: true,
		subjectId: impeachment.subject.id,
		houseImpeached: true,
		senateConvicted: true,
		convictionGround: impeachment.articles.map((article) => article.ground).join('; '),
		houseRecordDigest: impeachment.impeachmentDigest,
		senateRecordDigest: vote.voteDigest,
		presidingOfficerId: presidingOfficer.id,
		triedAt,
		effectiveAt,
		removalRequired: true,
		disqualified,
		criminalLiability: 'separate-ordinary-process',
	};

	return deepFreeze({
		status: 'senate-convicted',
		...record,
		judgmentDigest: digest(record),
		handoff: 'article-ii:revoke-authority',
		trace: [ARTICLE_I.rules.impeachment, ARTICLE_I.engineering.sourcePreservingLaw],
	});
}

export function screenStateAct({ normativeRoot, act, congressionalConsent = null }) {
	assertNormativeRoot(normativeRoot);
	requireObject(act, 'act');
	requireNonEmptyString(act.id, 'act.id');
	requireNonEmptyString(act.state, 'act.state');
	requireNonEmptyString(act.kind, 'act.kind');

	if (act.rootDigest !== normativeRoot.digest || act.authenticated !== true) {
		throw new TypeError('State act must be authenticated against the current normative root');
	}

	if (STATE_ABSOLUTE_PROHIBITIONS.includes(act.kind)) {
		return deepFreeze({
			status: 'state-act-prohibited',
			actId: act.id,
			state: act.state,
			kind: act.kind,
			reason: `article-i-section-10:${act.kind}`,
			actDigest: digest(act),
			trace: [ARTICLE_I.rules.stateProhibitions],
		});
	}

	if (!STATE_CONSENT_ACTIONS.includes(act.kind)) {
		return deepFreeze({
			status: 'state-act-outside-model',
			actId: act.id,
			kind: act.kind,
			handoff: 'article-iii:resolve-if-case-or-controversy',
			trace: [ARTICLE_I.engineering.wardenBoundary],
		});
	}

	if (
		act.kind === 'engage-in-war' &&
		act.actuallyInvaded === true &&
		act.imminentDangerAdmitsNoDelay === true
	) {
		return deepFreeze({
			status: 'state-emergency-action-allowed',
			actId: act.id,
			state: act.state,
			kind: act.kind,
			actDigest: digest(act),
			trace: [ARTICLE_I.rules.stateProhibitions],
		});
	}

	if (
		act.kind === 'import-export-duty-beyond-inspection' &&
		act.onlyNecessaryInspectionCharge === true &&
		act.netProduceForUnitedStatesTreasury === true &&
		act.subjectToCongressionalRevision === true
	) {
		return deepFreeze({
			status: 'state-inspection-duty-allowed',
			actId: act.id,
			state: act.state,
			kind: act.kind,
			actDigest: digest(act),
			trace: [ARTICLE_I.rules.stateProhibitions],
		});
	}

	if (
		!congressionalConsent ||
		congressionalConsent.authenticated !== true ||
		congressionalConsent.approved !== true ||
		congressionalConsent.actId !== act.id ||
		congressionalConsent.rootDigest !== normativeRoot.digest
	) {
		return deepFreeze({
			status: 'state-act-requires-congressional-consent',
			actId: act.id,
			state: act.state,
			kind: act.kind,
			actDigest: digest(act),
			handoff: 'article-i:congressional-consent',
			trace: [ARTICLE_I.rules.stateProhibitions],
		});
	}

	return deepFreeze({
		status: 'state-act-consented',
		actId: act.id,
		state: act.state,
		kind: act.kind,
		actDigest: digest(act),
		consentDigest: digest(congressionalConsent),
		trace: [ARTICLE_I.rules.stateProhibitions, ARTICLE_I.engineering.independentConsents],
	});
}

WARDEN: сто п’ятдесят один сценарій створення закону

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

ГрупаПеревірювані відносиниОсновне джерело
Установлення Конгресуroot, дві палати, представництво, вибори, кваліфікація та строксекції 1–4; поправки XIV, XVII і XX
Компетенціяперелічені й надані поправками повноваження, Necessary and Properсекція 8; повноваження з виконання пізніших поправок
Федеральні межіпрямі заборони, habeas exception і поправка XVIсекція 9; поправка XVI
Revenue originationвиникнення в Палаті та право Сенату на amendmentсекція 7, клаузула 1
Внутрішня процедуракворум, пороги, журнал і точний question digestсекція 5; default-majority doctrine
Двопалатністьокремі дії палат і один text digestсекції 1 і 7; exact-text invariant
Представленняsignature, veto, ten-day route, pocket veto й overrideсекція 7
Похідні артефактиасигнування, посада, суд, військове уповноваження й наступництвосекції 8–9; Appointments і Succession Clauses; стаття III
ІмпічментHouse charge, Senate trial, дві третини й bounded judgmentсекції 2–3; стаття II, секція 4
Обмеження штатівабсолютні заборони, consent і надзвичайні виняткисекція 10
Міжмодульна інтеграціяєдиний root і сумісні контракти статей I–IVнакопичувальна архітектура прототипу

Групи перетинаються: один інтеграційний сценарій водночас перевіряє законодавчий output, root-binding і вхід статті II або III, а цикли генерують окремі тести для повних реєстрів повноважень і заборон. Авторитетний результат повертає node --test: 151 tests, 151 pass, 0 fail. Це невеликий корисний захист від ритуалу, за якого красиво оформлена таблиця отримує більше довіри, ніж виконуваний набір, який вона нібито описує.

matrixматриця WARDEN
Текст статті IЧинні поправкиДоктринаІнженерний розвиток
СкладСтруктура Конгресу · trace:ARTICLE_I.rules.vestingВибори й строки · trace:ARTICLE_I.amendments.seventeenthСпір про кваліфікацію · human-reviewНевідповідний root · trace:ARTICLE_I.engineering.wardenBoundary
КомпетенціяПерелічене повноваження · trace:ARTICLE_I.rules.enumeratedPowersВиконавче повноваження · trace:AMENDMENT_ENFORCEMENT_POWERSНеобхідний і належний засіб · trace:ARTICLE_I.doctrine.necessaryAndProperВідсутня компетенція · trace:ARTICLE_I.engineering.competenceBeforeProcedure
РедакціяОдин текст законопроєкту · trace:ARTICLE_I.rules.bicameralismAndPresentmentКонфлікт поправок · human-reviewТотожний текст · trace:ARTICLE_I.doctrine.exactTextНевідповідний digest · trace:ARTICLE_I.engineering.independentConsents
ГолосуванняКворум і журнал · trace:ARTICLE_I.rules.quorumAndJournalЗмінений поріг · human-reviewБільшість за замовчуванням · trace:ARTICLE_I.doctrine.defaultMajorityЖурнал не створює чинності · trace:ARTICLE_I.engineering.journalEvidence
ПредставленняДві палати й представлення · trace:ARTICLE_I.rules.bicameralismAndPresentmentВзаємодія з поправкою · human-reviewП’ять маршрутів · trace:ARTICLE_I.doctrine.presentmentЗаблокований білль · trace:ARTICLE_I.engineering.wardenBoundary
РесурсАсигнування за законом · trace:ARTICLE_I.rules.appropriationsМежа поправки · human-reviewПохідний засіб · trace:ARTICLE_I.doctrine.necessaryAndProperНеобмежений ресурс · trace:ARTICLE_I.engineering.protectedResources
ІмпічментОбвинувачення й суд · trace:ARTICLE_I.rules.impeachmentНаслідок усунення · human-reviewОбмежене рішення · human-reviewНемає незалежної згоди · trace:ARTICLE_I.engineering.independentConsents
ШтатиЗаборони штатів · trace:ARTICLE_I.rules.stateProhibitionsПовноваження виконання · trace:ARTICLE_I.amendments.fourteenthСпір про згоду чи виняток · human-reviewЗгода не прив’язана до root · trace:ARTICLE_I.engineering.independentConsents
ІнтеграціяСпільний конституційний root · trace:ARTICLE_I.rules.vestingЧинний lineage поправок · trace:normativeRoot.lineageМіжмодульний спір · human-reviewНевідповідність lineage · trace:ARTICLE_I.engineering.sourcePreservingLaw

WARDEN зіставляє 151 сценарій статті I з буквальним текстом, поправками, доктриною та інженерними інваріантами

  • source: Текст статті I
  • source: Чинні поправки
  • source: Доктрина
  • source: Інженерний розвиток
  • state: Склад
  • state: Компетенція
  • state: Редакція
  • state: Голосування
  • state: Представлення
  • state: Ресурс
  • state: Імпічмент
  • state: Штати
  • state: Інтеграція
  • article-text validates composition: Структура Конгресу · trace:ARTICLE_I.rules.vesting
  • amendments validates composition: Вибори й строки · trace:ARTICLE_I.amendments.seventeenth
  • doctrine returns composition: Спір про кваліфікацію · human-review
  • engineering rejects composition: Невідповідний root · trace:ARTICLE_I.engineering.wardenBoundary
  • article-text validates competence: Перелічене повноваження · trace:ARTICLE_I.rules.enumeratedPowers
  • amendments validates competence: Виконавче повноваження · trace:AMENDMENT_ENFORCEMENT_POWERS
  • doctrine validates competence: Необхідний і належний засіб · trace:ARTICLE_I.doctrine.necessaryAndProper
  • engineering rejects competence: Відсутня компетенція · trace:ARTICLE_I.engineering.competenceBeforeProcedure
  • article-text validates revision: Один текст законопроєкту · trace:ARTICLE_I.rules.bicameralismAndPresentment
  • amendments returns revision: Конфлікт поправок · human-review
  • doctrine validates revision: Тотожний текст · trace:ARTICLE_I.doctrine.exactText
  • engineering rejects revision: Невідповідний digest · trace:ARTICLE_I.engineering.independentConsents
  • article-text validates voting: Кворум і журнал · trace:ARTICLE_I.rules.quorumAndJournal
  • amendments returns voting: Змінений поріг · human-review
  • doctrine validates voting: Більшість за замовчуванням · trace:ARTICLE_I.doctrine.defaultMajority
  • engineering rejects voting: Журнал не створює чинності · trace:ARTICLE_I.engineering.journalEvidence
  • article-text validates presentment: Дві палати й представлення · trace:ARTICLE_I.rules.bicameralismAndPresentment
  • amendments returns presentment: Взаємодія з поправкою · human-review
  • doctrine validates presentment: П’ять маршрутів · trace:ARTICLE_I.doctrine.presentment
  • engineering rejects presentment: Заблокований білль · trace:ARTICLE_I.engineering.wardenBoundary
  • article-text validates resource: Асигнування за законом · trace:ARTICLE_I.rules.appropriations
  • amendments returns resource: Межа поправки · human-review
  • doctrine returns resource: Похідний засіб · trace:ARTICLE_I.doctrine.necessaryAndProper
  • engineering rejects resource: Необмежений ресурс · trace:ARTICLE_I.engineering.protectedResources
  • article-text validates impeachment: Обвинувачення й суд · trace:ARTICLE_I.rules.impeachment
  • amendments returns impeachment: Наслідок усунення · human-review
  • doctrine returns impeachment: Обмежене рішення · human-review
  • engineering rejects impeachment: Немає незалежної згоди · trace:ARTICLE_I.engineering.independentConsents
  • article-text validates states: Заборони штатів · trace:ARTICLE_I.rules.stateProhibitions
  • amendments validates states: Повноваження виконання · trace:ARTICLE_I.amendments.fourteenth
  • doctrine returns states: Спір про згоду чи виняток · human-review
  • engineering rejects states: Згода не прив’язана до root · trace:ARTICLE_I.engineering.independentConsents
  • article-text validates integration: Спільний конституційний root · trace:ARTICLE_I.rules.vesting
  • amendments validates integration: Чинний lineage поправок · trace:normativeRoot.lineage
  • doctrine returns integration: Міжмодульний спір · human-review
  • engineering rejects integration: Невідповідність lineage · trace:ARTICLE_I.engineering.sourcePreservingLaw
матриця WARDENIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g06 · authorial brief

Повний тестовий корпус:

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

import {
	AMENDMENT_ENFORCEMENT_POWERS,
	ARTICLE_I,
	ENUMERATED_POWERS,
	FEDERAL_PROHIBITIONS,
	STATE_ABSOLUTE_PROHIBITIONS,
	STATE_CONSENT_ACTIONS,
	authorizeAppropriation,
	authorizeMilitaryAction,
	constituteCongress,
	createBillVersion,
	createSuccessionPlan,
	enrollBill,
	establishOffice,
	impeach,
	introduceBill,
	legislate,
	organizeInferiorCourts,
	overrideVeto,
	passChamber,
	presentBill,
	recordChamberVote,
	screenStateAct,
	tryImpeachment,
} from './article-i.mjs';

import { digest, federate } from './article-iv.mjs';
import { constituteJudiciary } from './article-iii.mjs';
import {
	applyImpeachmentRemoval,
	appointOfficer,
	commandForces,
	constituteExecutive,
} 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+xiii+xiv+xvi+xvii+xx+xxii+xxv+xxvii',
	digest: 'sha256:root-after-article-v',
	parentDigest: 'sha256:root-before-article-v',
	amendmentDigest: 'sha256:amendments-current',
	status: 'in-force',
	lineage: Object.freeze([
		'sha256:root-before-article-v',
		'sha256:amendment:xiii',
		'sha256:amendment:xiv',
		'sha256:amendment:xvi',
		'sha256:amendment:xvii',
		'sha256:amendment:xx',
		'sha256:amendment:xxvii',
		'sha256:root-after-article-v',
	]),
});

const house = Object.freeze({
	id: 'house:119',
	totalSeats: 435,
	seatedMembers: 435,
	representation: 'population-apportioned',
	electionsAuthenticated: true,
	qualificationsVerified: true,
	fourteenthAmendmentScreened: true,
	censusApportionmentVerified: true,
	presidingOfficerId: 'speaker:one',
});

const senate = Object.freeze({
	id: 'senate:119',
	totalSeats: 100,
	seatedMembers: 100,
	representation: 'equal-state',
	electionsAuthenticated: true,
	qualificationsVerified: true,
	fourteenthAmendmentScreened: true,
	equalStateRepresentationVerified: true,
	seventeenthAmendmentElectionVerified: true,
	classesContinuityVerified: true,
	presidingOfficerId: 'vice-president:grace',
});

const term = Object.freeze({
	startsAt: '2025-01-03T17:00:00Z',
	endsAt: '2027-01-03T17:00:00Z',
	twentiethAmendmentScheduleVerified: true,
	annualAssemblyProvided: true,
});

function congressFixture(overrides = {}) {
	return constituteCongress({
		normativeRoot: overrides.normativeRoot ?? normativeRoot,
		congressId: overrides.congressId ?? 'congress:119',
		term: overrides.term ?? term,
		house: overrides.house ?? house,
		senate: overrides.senate ?? senate,
	});
}

const congress = congressFixture();

function vote(chamber, questionDigest, overrides = {}) {
	const membersPresent = overrides.membersPresent ?? (chamber === 'house' ? 420 : 90);
	const yeas = overrides.yeas ?? (chamber === 'house' ? 230 : 55);
	const abstentions = overrides.abstentions ?? 0;
	const nays = overrides.nays ?? membersPresent - yeas - abstentions;

	return {
		id: overrides.id ?? `vote:${chamber}:${questionDigest.slice(-12)}`,
		chamber,
		questionDigest,
		sessionId: overrides.sessionId ?? 'session:119:1',
		membersPresent,
		yeas,
		nays,
		abstentions,
		quorumVerified: overrides.quorumVerified ?? true,
		journalEntryId: overrides.journalEntryId ?? `journal:${chamber}:${questionDigest.slice(-12)}`,
		journalPublished: overrides.journalPublished ?? true,
		yeasAndNaysRecorded: overrides.yeasAndNaysRecorded ?? true,
		recordedAt: overrides.recordedAt ?? '2026-08-10T12:00:00Z',
		authenticated: overrides.authenticated ?? true,
		...overrides,
	};
}

function billInput(overrides = {}) {
	return {
		id: 'hr:warden-infrastructure',
		title: 'WARDEN Infrastructure and Public Execution Act',
		kind: 'omnibus',
		originatingChamber: 'house',
		introducedBy: 'representative:ada',
		introducedAt: '2026-08-10T09:00:00Z',
		effectiveAt: '2026-09-01T00:00:00Z',
		rootDigest: normativeRoot.digest,
		scope: 'federal-warden-infrastructure',
		text: 'Section 1. Establish bounded WARDEN infrastructure and its public execution ledger.',
		outputs: [
			'general-rule',
			'appropriation',
			'office-establishment',
			'military-authorization',
			'succession-plan',
			'inferior-courts',
		],
		powerClaim: {
			bases: ['commerce-foreign-interstate-tribal', 'necessary-and-proper'],
			necessaryAndProper: {
				linkedPower: 'commerce-foreign-interstate-tribal',
				legitimateEndVerified: true,
				plainlyAdapted: true,
				notProhibited: true,
				consistentWithConstitution: true,
			},
		},
		restrictions: {
			namedPersonOrClosedGroup: false,
			punishmentWithoutTrial: false,
			retroactive: false,
			penal: false,
			suspendsHabeas: false,
			directTax: false,
			taxOnStateExports: false,
			portPreference: false,
			treasuryWithdrawalWithoutAppropriation: false,
			titleOfNobility: false,
		},
		...overrides,
	};
}

function introduced(overrides = {}) {
	return introduceBill({ congress, bill: billInput(overrides) });
}

function version(bill, chamber, text = bill.initialVersion.text, overrides = {}) {
	return createBillVersion({
		bill,
		chamber,
		text,
		amendments: overrides.amendments ?? [],
		createdAt:
			overrides.createdAt ??
			(chamber === 'house' ? '2026-08-10T10:00:00Z' : '2026-08-10T14:00:00Z'),
	});
}

function chamberActions(options = {}) {
	const bill = options.bill ?? introduced();
	const houseVersion = options.houseVersion ?? version(bill, 'house', options.houseText);
	const houseAction = passChamber({
		congress,
		bill,
		chamber: 'house',
		version: houseVersion,
		vote: options.houseVote ?? vote('house', houseVersion.versionDigest),
	});
	const senateVersion = options.senateVersion ?? version(bill, 'senate', options.senateText);
	const senateAction = passChamber({
		congress,
		bill,
		chamber: 'senate',
		version: senateVersion,
		vote: options.senateVote ?? vote('senate', senateVersion.versionDigest),
		priorHouseAction: houseAction,
	});

	return { bill, houseVersion, senateVersion, houseAction, senateAction };
}

function enrolledBill(options = {}) {
	const actions = chamberActions(options);
	return enrollBill({
		congress,
		bill: actions.bill,
		houseAction: actions.houseAction,
		senateAction: actions.senateAction,
		enrolledAt: options.enrolledAt ?? '2026-08-10T16:00:00Z',
	});
}

function signedLaw(options = {}) {
	const enrolled = options.enrolled ?? enrolledBill(options);
	return presentBill({
		congress,
		enrolled,
		presentedAt: options.presentedAt ?? '2026-08-10T17:00:00Z',
		presidentAction: options.presidentAction ?? {
			kind: 'sign',
			actorId: 'president:ada',
			actedAt: '2026-08-10T18:00:00Z',
			authenticated: true,
		},
	});
}

wardenTest(
	'constituteCongress binds two differently represented chambers to one root',
	[ARTICLE_I.rules.vesting, ARTICLE_I.rules.house, ARTICLE_I.rules.senate],
	() => {
		assert.equal(congress.status, 'congress-constituted');
		assert.equal(congress.normativeRoot.digest, normativeRoot.digest);
		assert.equal(congress.house.representation, 'population-apportioned');
		assert.equal(congress.senate.representation, 'equal-state');
	},
);

wardenTest(
	'constituted Congress is deeply immutable',
	[ARTICLE_I.engineering.journalEvidence],
	() => {
		assert.equal(Object.isFrozen(congress), true);
		assert.equal(Object.isFrozen(congress.house), true);
		assert.throws(() => (congress.house.totalSeats = 1));
	},
);

const congressFormationFailures = [
	[
		'Congress cannot bind to a superseded root',
		{ normativeRoot: { ...normativeRoot, status: 'superseded' } },
		/root in force/,
	],
	[
		'House requires authenticated elections',
		{ house: { ...house, electionsAuthenticated: false } },
		/authenticated elections/,
	],
	[
		'House requires census-based apportionment',
		{ house: { ...house, censusApportionmentVerified: false } },
		/population-apportioned/,
	],
	[
		'Senate requires equal representation',
		{ senate: { ...senate, equalStateRepresentationVerified: false } },
		/equal state representation/,
	],
	[
		'Senate requires direct election under Amendment XVII',
		{ senate: { ...senate, seventeenthAmendmentElectionVerified: false } },
		/direct election/,
	],
	[
		'Senate requires staggered institutional continuity',
		{ senate: { ...senate, classesContinuityVerified: false } },
		/staggered continuity/,
	],
	[
		'both chambers require an Amendment XIV qualification screen',
		{ house: { ...house, fourteenthAmendmentScreened: false } },
		/Amendment XIV/,
	],
	[
		'Congress must provide for annual assembly',
		{ term: { ...term, annualAssemblyProvided: false } },
		/annual assembly/,
	],
	[
		'congressional term cannot run backwards',
		{ term: { ...term, endsAt: '2024-01-03T17:00:00Z' } },
		/end after/,
	],
];

for (const [name, mutation, pattern] of congressFormationFailures) {
	wardenTest(name, [ARTICLE_I.rules.vesting, ARTICLE_I.amendments.twentieth], () => {
		assert.throws(() => congressFixture(mutation), pattern);
	});
}

for (const power of ENUMERATED_POWERS) {
	wardenTest(
		`Article I accepts an authenticated claim to enumerated power: ${power}`,
		[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.competenceBeforeProcedure],
		() => {
			const result = introduced({
				powerClaim: { bases: [power] },
			});
			assert.equal(result.status, 'bill-introduced');
			assert.deepEqual(result.powerClaim.bases, [power]);
		},
	);
}

for (const power of AMENDMENT_ENFORCEMENT_POWERS) {
	wardenTest(
		`current root accepts later amendment enforcement power: ${power}`,
		[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.amendments.fourteenth],
		() => {
			const result = introduced({ powerClaim: { bases: [power] } });
			assert.equal(result.status, 'bill-introduced');
		},
	);
}

wardenTest(
	'unsupported policy goal does not manufacture federal competence',
	[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.competenceBeforeProcedure],
	() => {
		const result = introduced({ powerClaim: { bases: ['make-everything-nice'] } });
		assert.equal(result.status, 'bill-blocked');
		assert.deepEqual(result.issues, ['unsupported-power:make-everything-nice']);
	},
);

wardenTest(
	'Necessary and Proper cannot operate as an independent end',
	[ARTICLE_I.doctrine.necessaryAndProper, ARTICLE_I.engineering.derivativeMeans],
	() => {
		const result = introduced({
			powerClaim: {
				bases: ['necessary-and-proper'],
				necessaryAndProper: {
					linkedPower: 'be-generally-efficient',
					legitimateEndVerified: true,
					plainlyAdapted: true,
					notProhibited: true,
					consistentWithConstitution: true,
				},
			},
		});
		assert.equal(result.status, 'bill-blocked');
		assert.ok(result.issues.some((issue) => issue.includes('without-granted-end')));
	},
);

const necessaryAndProperFailures = [
	['legitimateEndVerified', 'a legitimate granted end'],
	['plainlyAdapted', 'a means plainly adapted to the end'],
	['notProhibited', 'a means outside direct constitutional prohibition'],
	['consistentWithConstitution', 'consistency with the constitutional order'],
];

for (const [field, label] of necessaryAndProperFailures) {
	wardenTest(
		`Necessary and Proper requires ${label}`,
		[ARTICLE_I.doctrine.necessaryAndProper, ARTICLE_I.engineering.derivativeMeans],
		() => {
			const base = billInput().powerClaim;
			const result = introduced({
				powerClaim: {
					...base,
					necessaryAndProper: { ...base.necessaryAndProper, [field]: false },
				},
			});
			assert.equal(result.status, 'bill-blocked');
			assert.ok(result.issues.includes(`necessary-and-proper-failed:${field}`));
		},
	);
}

const federalRestrictionMutations = {
	'bill-of-attainder': {
		namedPersonOrClosedGroup: true,
		punishmentWithoutTrial: true,
	},
	'ex-post-facto-penal-law': { retroactive: true, penal: true },
	'unjustified-habeas-suspension': {
		suspendsHabeas: true,
		rebellionOrInvasionVerified: false,
		publicSafetyRequiresSuspension: false,
	},
	'unapportioned-direct-tax-outside-amendment-xvi': {
		directTax: true,
		incomeTaxUnderAmendmentXVI: false,
		apportionedByCensus: false,
	},
	'tax-on-exports': { taxOnStateExports: true },
	'port-preference': { portPreference: true },
	'treasury-withdrawal-without-appropriation': {
		treasuryWithdrawalWithoutAppropriation: true,
	},
	'title-of-nobility': { titleOfNobility: true },
};

for (const prohibition of FEDERAL_PROHIBITIONS) {
	wardenTest(
		`federal prohibition blocks legislation: ${prohibition}`,
		[ARTICLE_I.rules.federalProhibitions, ARTICLE_I.engineering.wardenBoundary],
		() => {
			const result = introduced({
				restrictions: {
					...billInput().restrictions,
					...federalRestrictionMutations[prohibition],
				},
			});
			assert.equal(result.status, 'bill-blocked');
			assert.ok(result.issues.includes(prohibition));
		},
	);
}

wardenTest(
	'a valid Amendment XVI income-tax claim is not treated as an unapportioned direct-tax defect',
	[ARTICLE_I.amendments.sixteenth, ARTICLE_I.rules.federalProhibitions],
	() => {
		const result = introduced({
			kind: 'revenue',
			outputs: ['revenue'],
			restrictions: {
				...billInput().restrictions,
				directTax: true,
				incomeTaxUnderAmendmentXVI: true,
				apportionedByCensus: false,
			},
			powerClaim: { bases: ['tax-spend-general-welfare'] },
		});
		assert.equal(result.status, 'bill-introduced');
	},
);

wardenTest(
	'habeas suspension passes only through the narrow rebellion-or-invasion gate',
	[ARTICLE_I.rules.federalProhibitions],
	() => {
		const result = introduced({
			restrictions: {
				...billInput().restrictions,
				suspendsHabeas: true,
				rebellionOrInvasionVerified: true,
				publicSafetyRequiresSuspension: true,
			},
		});
		assert.equal(result.status, 'bill-introduced');
	},
);

wardenTest(
	'a revenue bill originating in the Senate is blocked before voting',
	[ARTICLE_I.rules.revenueOrigination],
	() => {
		const result = introduced({
			kind: 'revenue',
			originatingChamber: 'senate',
			outputs: ['revenue'],
			powerClaim: { bases: ['tax-spend-general-welfare'] },
		});
		assert.equal(result.status, 'bill-blocked');
		assert.ok(result.issues.includes('revenue-bill-did-not-originate-in-house'));
	},
);

wardenTest(
	'the Senate may amend a revenue bill after House passage',
	[ARTICLE_I.rules.revenueOrigination, ARTICLE_I.doctrine.exactText],
	() => {
		const bill = introduced({
			kind: 'revenue',
			outputs: ['revenue'],
			powerClaim: { bases: ['tax-spend-general-welfare'] },
		});
		const houseVersion = version(bill, 'house');
		const houseAction = passChamber({
			congress,
			bill,
			chamber: 'house',
			version: houseVersion,
			vote: vote('house', houseVersion.versionDigest),
		});
		const senateVersion = version(bill, 'senate', `${bill.initialVersion.text} Senate amendment.`, {
			amendments: [{ id: 's-amdt:1', description: 'Adjust rate' }],
		});
		const senateAction = passChamber({
			congress,
			bill,
			chamber: 'senate',
			version: senateVersion,
			vote: vote('senate', senateVersion.versionDigest),
			priorHouseAction: houseAction,
		});
		assert.equal(senateAction.status, 'chamber-passed');
	},
);

wardenTest(
	'the Senate cannot take up a revenue bill before House passage',
	[ARTICLE_I.rules.revenueOrigination],
	() => {
		const bill = introduced({
			kind: 'revenue',
			outputs: ['revenue'],
			powerClaim: { bases: ['tax-spend-general-welfare'] },
		});
		const senateVersion = version(bill, 'senate');
		assert.throws(
			() =>
				passChamber({
					congress,
					bill,
					chamber: 'senate',
					version: senateVersion,
					vote: vote('senate', senateVersion.versionDigest),
				}),
			/prior House passage/,
		);
	},
);

wardenTest(
	'a majority of a quorum passes an ordinary question',
	[ARTICLE_I.rules.quorumAndJournal, ARTICLE_I.doctrine.defaultMajority],
	() => {
		const record = recordChamberVote({
			congress,
			chamber: 'senate',
			questionDigest: 'sha256:ordinary-question',
			vote: vote('senate', 'sha256:ordinary-question', {
				membersPresent: 60,
				yeas: 31,
				nays: 29,
			}),
		});
		assert.equal(record.status, 'question-passed');
		assert.equal(record.requiredYeas, 31);
	},
);

wardenTest(
	'one vote below the ordinary majority rejects the question',
	[ARTICLE_I.doctrine.defaultMajority],
	() => {
		const record = recordChamberVote({
			congress,
			chamber: 'senate',
			questionDigest: 'sha256:ordinary-question-2',
			vote: vote('senate', 'sha256:ordinary-question-2', {
				membersPresent: 60,
				yeas: 30,
				nays: 30,
			}),
		});
		assert.equal(record.status, 'question-rejected');
	},
);

const voteIntegrityFailures = [
	['a chamber cannot act below quorum', { membersPresent: 40, yeas: 30, nays: 10 }, /quorum/],
	['a false quorum attestation blocks the vote', { quorumVerified: false }, /quorum/],
	[
		'vote totals must equal members present',
		{ membersPresent: 90, yeas: 60, nays: 20, abstentions: 0 },
		/totals/,
	],
	[
		'a vote cannot report more members than are seated',
		{ membersPresent: 101, yeas: 70, nays: 31 },
		/more members/,
	],
	[
		'an unauthenticated vote cannot support legislative action',
		{ authenticated: false },
		/authentication/,
	],
	[
		'an unpublished journal entry cannot support legislative action',
		{ journalPublished: false },
		/published journal/,
	],
	[
		'a vote cannot be rebound to another question digest',
		{ questionDigest: 'sha256:other-question' },
		/another chamber or question/,
	],
	[
		'a Senate vote cannot impersonate the House',
		{ chamber: 'house' },
		/another chamber or question/,
	],
];

for (const [name, mutation, pattern] of voteIntegrityFailures) {
	wardenTest(
		name,
		[ARTICLE_I.rules.quorumAndJournal, ARTICLE_I.engineering.journalEvidence],
		() => {
			const questionDigest = 'sha256:vote-integrity';
			assert.throws(
				() =>
					recordChamberVote({
						congress,
						chamber: 'senate',
						questionDigest,
						vote: vote('senate', questionDigest, mutation),
					}),
				pattern,
			);
		},
	);
}

wardenTest(
	'a passed House version produces an immutable chamber action',
	[ARTICLE_I.rules.bicameralismAndPresentment, ARTICLE_I.engineering.independentConsents],
	() => {
		const bill = introduced();
		const houseVersion = version(bill, 'house');
		const action = passChamber({
			congress,
			bill,
			chamber: 'house',
			version: houseVersion,
			vote: vote('house', houseVersion.versionDigest),
		});
		assert.equal(action.status, 'chamber-passed');
		assert.equal(Object.isFrozen(action), true);
		assert.throws(() => (action.vote.yeas = 1));
	},
);

wardenTest(
	'a rejected chamber vote stops that chamber action',
	[ARTICLE_I.doctrine.defaultMajority],
	() => {
		const bill = introduced();
		const houseVersion = version(bill, 'house');
		const action = passChamber({
			congress,
			bill,
			chamber: 'house',
			version: houseVersion,
			vote: vote('house', houseVersion.versionDigest, {
				membersPresent: 420,
				yeas: 200,
				nays: 220,
			}),
		});
		assert.equal(action.status, 'chamber-rejected');
	},
);

wardenTest(
	'a chamber cannot vote on a version attributed to the other chamber',
	[ARTICLE_I.engineering.independentConsents],
	() => {
		const bill = introduced();
		const senateVersion = version(bill, 'senate');
		assert.throws(
			() =>
				passChamber({
					congress,
					bill,
					chamber: 'house',
					version: senateVersion,
					vote: vote('house', senateVersion.versionDigest),
				}),
			/another chamber/,
		);
	},
);

wardenTest(
	'House and Senate approval of identical text creates an enrolled bill',
	[ARTICLE_I.doctrine.exactText, ARTICLE_I.rules.bicameralismAndPresentment],
	() => {
		const enrolled = enrolledBill();
		assert.equal(enrolled.status, 'bill-enrolled');
		assert.equal(enrolled.textDigest, introduced().initialVersion.textDigest);
	},
);

wardenTest(
	'different chamber texts remain a disagreement even when both votes pass',
	[ARTICLE_I.doctrine.exactText, ARTICLE_I.engineering.independentConsents],
	() => {
		const enrolled = enrolledBill({
			houseText: billInput().text,
			senateText: `${billInput().text} Section 2. Unapproved Senate-only power.`,
		});
		assert.equal(enrolled.status, 'bicameral-disagreement');
		assert.equal(enrolled.handoff, 'congress:reconcile-and-repass-one-text');
	},
);

wardenTest(
	'presentment refuses a bicameral disagreement',
	[ARTICLE_I.rules.bicameralismAndPresentment],
	() => {
		const disagreement = enrolledBill({
			houseText: billInput().text,
			senateText: `${billInput().text} Different text.`,
		});
		assert.throws(
			() =>
				presentBill({
					congress,
					enrolled: disagreement,
					presentedAt: '2026-08-10T17:00:00Z',
					presidentAction: {
						kind: 'sign',
						actorId: 'president:ada',
						actedAt: '2026-08-10T18:00:00Z',
						authenticated: true,
					},
				}),
			/enrolled bill/,
		);
	},
);

wardenTest('the President cannot sign before enrollment', [ARTICLE_I.doctrine.presentment], () => {
	assert.throws(
		() =>
			presentBill({
				congress,
				enrolled: enrolledBill(),
				presentedAt: '2026-08-10T15:00:00Z',
				presidentAction: {
					kind: 'sign',
					actorId: 'president:ada',
					actedAt: '2026-08-10T18:00:00Z',
					authenticated: true,
				},
			}),
		/precede enrollment/,
	);
});

wardenTest(
	'authenticated presidential signature enacts the exact enrolled text',
	[ARTICLE_I.rules.bicameralismAndPresentment, ARTICLE_I.engineering.sourcePreservingLaw],
	() => {
		const law = signedLaw();
		assert.equal(law.status, 'law-enacted');
		assert.equal(law.enactmentRoute, 'presidential-signature');
		assert.equal(law.textDigest, enrolledBill().textDigest);
		assert.equal(law.rootDigest, normativeRoot.digest);
	},
);

wardenTest('enacted law is deeply immutable', [ARTICLE_I.engineering.sourcePreservingLaw], () => {
	const law = signedLaw();
	assert.equal(Object.isFrozen(law), true);
	assert.throws(() => law.outputs.push('dictatorship'));
});

wardenTest(
	'an unauthenticated presidential signature creates no law',
	[ARTICLE_I.doctrine.presentment, ARTICLE_I.engineering.wardenBoundary],
	() => {
		assert.throws(
			() =>
				signedLaw({
					presidentAction: {
						kind: 'sign',
						actorId: 'president:ada',
						actedAt: '2026-08-10T18:00:00Z',
						authenticated: false,
					},
				}),
			/authenticated/,
		);
	},
);

function regularVeto(enrolled = enrolledBill(), overrides = {}) {
	return presentBill({
		congress,
		enrolled,
		presentedAt: overrides.presentedAt ?? '2026-08-10T17:00:00Z',
		presidentAction: {
			kind: 'veto',
			actorId: 'president:ada',
			actedAt: '2026-08-11T12:00:00Z',
			authenticated: true,
			returnedToChamber: enrolled.originatingChamber,
			returnedDuringSession: true,
			objections: 'The measure exceeds the preferred implementation budget.',
			...(overrides.presidentAction ?? {}),
		},
	});
}

wardenTest(
	'a regular veto preserves the enrolled bill and returns objections to its origin',
	[ARTICLE_I.doctrine.presentment],
	() => {
		const vetoed = regularVeto();
		assert.equal(vetoed.status, 'bill-vetoed');
		assert.equal(vetoed.action.returnedToChamber, 'house');
		assert.equal(vetoed.enrolled.status, 'bill-enrolled');
	},
);

const vetoFailures = [
	[
		'regular veto must return to the originating chamber',
		{ returnedToChamber: 'senate' },
		/originating chamber/,
	],
	[
		'regular veto must occur while return remains possible',
		{ returnedDuringSession: false },
		/originating chamber/,
	],
	['regular veto must contain objections', { objections: '' }, /non-empty string/],
	['regular veto must be authenticated', { authenticated: false }, /originating chamber/],
];

for (const [name, mutation, pattern] of vetoFailures) {
	wardenTest(name, [ARTICLE_I.rules.bicameralismAndPresentment], () => {
		assert.throws(() => regularVeto(enrolledBill(), { presidentAction: mutation }), pattern);
	});
}

wardenTest(
	'nine constitutional days without action leave presentment pending',
	[ARTICLE_I.doctrine.presentment],
	() => {
		const result = presentBill({
			congress,
			enrolled: enrolledBill({ enrolledAt: '2026-08-03T10:00:00Z' }),
			presentedAt: '2026-08-03T12:00:00Z',
			presidentAction: {
				kind: 'no-action',
				evaluatedAt: '2026-08-13T12:00:00Z',
				congressAdjournedPreventsReturn: false,
			},
		});
		assert.equal(result.status, 'presentment-pending');
		assert.equal(result.action.constitutionalDays, 9);
	},
);

wardenTest(
	'ten days excluding Sundays enact a bill without signature when return remains possible',
	[ARTICLE_I.doctrine.presentment],
	() => {
		const result = presentBill({
			congress,
			enrolled: enrolledBill({ enrolledAt: '2026-08-03T10:00:00Z' }),
			presentedAt: '2026-08-03T12:00:00Z',
			presidentAction: {
				kind: 'no-action',
				evaluatedAt: '2026-08-14T12:00:00Z',
				congressAdjournedPreventsReturn: false,
			},
		});
		assert.equal(result.status, 'law-enacted');
		assert.equal(result.enactmentRoute, 'ten-days-without-signature');
	},
);

wardenTest(
	'adjournment preventing return converts the ten-day route into a pocket veto',
	[ARTICLE_I.doctrine.presentment],
	() => {
		const result = presentBill({
			congress,
			enrolled: enrolledBill({ enrolledAt: '2026-08-03T10:00:00Z' }),
			presentedAt: '2026-08-03T12:00:00Z',
			presidentAction: {
				kind: 'no-action',
				evaluatedAt: '2026-08-14T12:00:00Z',
				congressAdjournedPreventsReturn: true,
			},
		});
		assert.equal(result.status, 'bill-pocket-vetoed');
		assert.equal(result.handoff, 'article-i:new-legislative-process');
	},
);

wardenTest(
	'presentment evaluation cannot run backward in time',
	[ARTICLE_I.doctrine.presentment],
	() => {
		assert.throws(
			() =>
				presentBill({
					congress,
					enrolled: enrolledBill(),
					presentedAt: '2026-08-10T17:00:00Z',
					presidentAction: {
						kind: 'no-action',
						evaluatedAt: '2026-08-09T12:00:00Z',
						congressAdjournedPreventsReturn: false,
					},
				}),
			/cannot precede/,
		);
	},
);

wardenTest(
	'two thirds of each chamber override a regular veto',
	[ARTICLE_I.rules.bicameralismAndPresentment, ARTICLE_I.doctrine.presentment],
	() => {
		const vetoed = regularVeto();
		const law = overrideVeto({
			congress,
			vetoed,
			originVote: vote('house', vetoed.enrolled.enrolledDigest, {
				membersPresent: 420,
				yeas: 280,
				nays: 140,
			}),
			otherVote: vote('senate', vetoed.enrolled.enrolledDigest, {
				membersPresent: 90,
				yeas: 60,
				nays: 30,
			}),
			enactedAt: '2026-08-12T16:00:00Z',
		});
		assert.equal(law.status, 'law-enacted');
		assert.equal(law.enactmentRoute, 'bicameral-veto-override');
	},
);

wardenTest(
	'one House vote below two thirds sustains the veto',
	[ARTICLE_I.doctrine.presentment],
	() => {
		const vetoed = regularVeto();
		const result = overrideVeto({
			congress,
			vetoed,
			originVote: vote('house', vetoed.enrolled.enrolledDigest, {
				membersPresent: 420,
				yeas: 279,
				nays: 141,
			}),
			otherVote: vote('senate', vetoed.enrolled.enrolledDigest, {
				membersPresent: 90,
				yeas: 60,
				nays: 30,
			}),
			enactedAt: '2026-08-12T16:00:00Z',
		});
		assert.equal(result.status, 'veto-sustained');
		assert.equal(result.failedChamber, 'house');
	},
);

wardenTest(
	'one Senate vote below two thirds sustains the veto after House reconsideration',
	[ARTICLE_I.doctrine.presentment],
	() => {
		const vetoed = regularVeto();
		const result = overrideVeto({
			congress,
			vetoed,
			originVote: vote('house', vetoed.enrolled.enrolledDigest, {
				membersPresent: 420,
				yeas: 280,
				nays: 140,
			}),
			otherVote: vote('senate', vetoed.enrolled.enrolledDigest, {
				membersPresent: 90,
				yeas: 59,
				nays: 31,
			}),
			enactedAt: '2026-08-12T16:00:00Z',
		});
		assert.equal(result.status, 'veto-sustained');
		assert.equal(result.failedChamber, 'senate');
	},
);

wardenTest(
	'override requires yeas and nays in the journal',
	[ARTICLE_I.rules.quorumAndJournal, ARTICLE_I.doctrine.presentment],
	() => {
		const vetoed = regularVeto();
		assert.throws(
			() =>
				overrideVeto({
					congress,
					vetoed,
					originVote: vote('house', vetoed.enrolled.enrolledDigest, {
						membersPresent: 420,
						yeas: 280,
						nays: 140,
						yeasAndNaysRecorded: false,
					}),
					otherVote: vote('senate', vetoed.enrolled.enrolledDigest, {
						membersPresent: 90,
						yeas: 60,
						nays: 30,
					}),
					enactedAt: '2026-08-12T16:00:00Z',
				}),
			/recorded yeas and nays/,
		);
	},
);

wardenTest(
	'a pocket veto cannot be overridden as a returned bill',
	[ARTICLE_I.doctrine.presentment],
	() => {
		const pocket = presentBill({
			congress,
			enrolled: enrolledBill({ enrolledAt: '2026-08-03T10:00:00Z' }),
			presentedAt: '2026-08-03T12:00:00Z',
			presidentAction: {
				kind: 'no-action',
				evaluatedAt: '2026-08-14T12:00:00Z',
				congressAdjournedPreventsReturn: true,
			},
		});
		assert.throws(
			() =>
				overrideVeto({
					congress,
					vetoed: pocket,
					originVote: {},
					otherVote: {},
					enactedAt: '2026-08-15T00:00:00Z',
				}),
			/regular veto/,
		);
	},
);

wardenTest(
	'the central legislate pipeline reaches the same signed-law state',
	[ARTICLE_I.rules.bicameralismAndPresentment, ARTICLE_I.engineering.sourcePreservingLaw],
	() => {
		const draft = billInput();
		const preview = introduceBill({ congress, bill: draft });
		const hv = version(preview, 'house', draft.text);
		const sv = version(preview, 'senate', draft.text);
		const result = legislate({
			congress,
			bill: draft,
			houseText: draft.text,
			senateText: draft.text,
			houseVote: vote('house', hv.versionDigest),
			senateVote: vote('senate', sv.versionDigest),
			houseVersionAt: '2026-08-10T10:00:00Z',
			senateVersionAt: '2026-08-10T14:00:00Z',
			enrolledAt: '2026-08-10T16:00:00Z',
			presentedAt: '2026-08-10T17:00:00Z',
			presidentAction: {
				kind: 'sign',
				actorId: 'president:ada',
				actedAt: '2026-08-10T18:00:00Z',
				authenticated: true,
			},
		});
		assert.equal(result.status, 'law-enacted');
		assert.equal(result.lawDigest, signedLaw().lawDigest);
	},
);

wardenTest(
	'the central pipeline returns a blocked bill before any vote',
	[ARTICLE_I.engineering.competenceBeforeProcedure],
	() => {
		const draft = billInput({ powerClaim: { bases: ['unlimited-power'] } });
		const result = legislate({ congress, bill: draft });
		assert.equal(result.status, 'bill-blocked');
	},
);

const law = signedLaw();

function lawWithOutputs(outputs) {
	const bill = introduced({ outputs });
	return signedLaw({ enrolled: enrolledBill({ bill }) });
}

function appropriation(overrides = {}) {
	return {
		id: 'appropriation:warden:2027',
		purpose: 'Operate the bounded WARDEN verification service',
		maximumAmount: 5_000_000,
		unit: 'USD',
		availableFrom: '2026-10-01T00:00:00Z',
		availableThrough: '2027-09-30T23:59:59Z',
		accountableOfficer: 'officer:warden-administrator',
		publicLedgerId: 'ledger:warden:2027',
		publicStatementRequired: true,
		...overrides,
	};
}

wardenTest(
	'an enacted appropriation produces a bounded public spending authority',
	[ARTICLE_I.rules.appropriations, ARTICLE_I.engineering.protectedResources],
	() => {
		const result = authorizeAppropriation({ law, appropriation: appropriation() });
		assert.equal(result.status, 'appropriation-authorized');
		assert.equal(result.maximumAmount, 5_000_000);
		assert.equal(result.remainingAmount, 5_000_000);
		assert.equal(result.lawDigest, law.lawDigest);
	},
);

const appropriationFailures = [
	['appropriation requires a positive maximum amount', { maximumAmount: 0 }, /positive number/],
	[
		'appropriation availability cannot run backward',
		{ availableThrough: '2025-09-30T23:59:59Z' },
		/cannot end before/,
	],
	[
		'appropriation requires a public statement and account',
		{ publicStatementRequired: false },
		/public statement/,
	],
];

for (const [name, mutation, pattern] of appropriationFailures) {
	wardenTest(name, [ARTICLE_I.rules.appropriations], () => {
		assert.throws(
			() => authorizeAppropriation({ law, appropriation: appropriation(mutation) }),
			pattern,
		);
	});
}

wardenTest(
	'physical Treasury access cannot replace an appropriation output',
	[ARTICLE_I.rules.appropriations, ARTICLE_I.engineering.protectedResources],
	() => {
		const generalLaw = lawWithOutputs(['general-rule']);
		assert.throws(
			() => authorizeAppropriation({ law: generalLaw, appropriation: appropriation() }),
			/does not authorize.*appropriation/,
		);
	},
);

function office(overrides = {}) {
	return {
		id: 'office:warden-administrator',
		name: 'WARDEN Administrator',
		classification: 'principal',
		departmentId: 'justice',
		executionEndpoint: 'article-ii:warden-service',
		capabilities: ['execute-federal-law', 'administer-public-ledger'],
		...overrides,
	};
}

wardenTest(
	'office-establishment output creates the exact Article II office contract',
	[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.sourcePreservingLaw],
	() => {
		const result = establishOffice({ law, office: office() });
		assert.equal(result.establishedByLaw, true);
		assert.equal(result.establishmentDigest, law.lawDigest);
		assert.equal(result.establishmentRootDigest, normativeRoot.digest);
		assert.equal(result.classification, 'principal');
	},
);

for (const actor of [
	'president-with-senate-consent',
	'president-alone',
	'court-of-law',
	'department-head',
]) {
	wardenTest(
		`Congress may vest an inferior office appointment in ${actor}`,
		[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.derivativeMeans],
		() => {
			const result = establishOffice({
				law,
				office: office({ classification: 'inferior', appointmentVestedIn: actor }),
			});
			assert.equal(result.appointmentVestedIn, actor);
			assert.equal(result.appointmentVestingAuthenticated, true);
		},
	);
}

wardenTest(
	'an inferior office cannot invent an appointing actor',
	[ARTICLE_I.engineering.derivativeMeans],
	() => {
		assert.throws(
			() =>
				establishOffice({
					law,
					office: office({ classification: 'inferior', appointmentVestedIn: 'llm-autocomplete' }),
				}),
			/permitted appointing actor/,
		);
	},
);

wardenTest(
	'a law without office-establishment output cannot create an office',
	[ARTICLE_I.engineering.competenceBeforeProcedure],
	() => {
		assert.throws(
			() => establishOffice({ law: lawWithOutputs(['general-rule']), office: office() }),
			/does not authorize.*office-establishment/,
		);
	},
);

function militaryAuthorization(overrides = {}) {
	return {
		id: 'authorization:defend-warden-network',
		scope: 'defend federal WARDEN infrastructure against a verified armed attack',
		scopeIncludesOrder: true,
		calledIntoActualService: false,
		authorizedAt: '2026-09-01T00:00:00Z',
		...overrides,
	};
}

wardenTest(
	'military-authorization output creates the exact Article II authority class',
	[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.sourcePreservingLaw],
	() => {
		const result = authorizeMilitaryAction({
			law,
			authorization: militaryAuthorization(),
		});
		assert.equal(result.kind, 'congress-authorized');
		assert.equal(result.statuteStatus, 'in-force');
		assert.equal(result.statuteDigest, law.lawDigest);
		assert.equal(result.rootDigest, normativeRoot.digest);
	},
);

wardenTest(
	'military output must determine that the contemplated order remains within scope',
	[ARTICLE_I.engineering.derivativeMeans],
	() => {
		assert.throws(
			() =>
				authorizeMilitaryAction({
					law,
					authorization: militaryAuthorization({ scopeIncludesOrder: false }),
				}),
			/within scope/,
		);
	},
);

wardenTest(
	'a general law cannot be re-labelled as a military authorization',
	[ARTICLE_I.engineering.competenceBeforeProcedure],
	() => {
		assert.throws(
			() =>
				authorizeMilitaryAction({
					law: lawWithOutputs(['general-rule']),
					authorization: militaryAuthorization(),
				}),
			/does not authorize.*military-authorization/,
		);
	},
);

const successionEntries = 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 },
]);

wardenTest(
	'succession law creates an Article II dual-vacancy plan',
	[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.sourcePreservingLaw],
	() => {
		const result = createSuccessionPlan({ law, entries: successionEntries });
		assert.equal(result.establishedByLaw, true);
		assert.equal(result.statuteDigest, law.lawDigest);
		assert.equal(result.entries.length, 3);
	},
);

wardenTest(
	'succession plan requires at least one entry',
	[ARTICLE_I.engineering.derivativeMeans],
	() => {
		assert.throws(() => createSuccessionPlan({ law, entries: [] }), /at least one/);
	},
);

wardenTest(
	'succession plan cannot repeat an office',
	[ARTICLE_I.engineering.derivativeMeans],
	() => {
		assert.throws(
			() =>
				createSuccessionPlan({
					law,
					entries: [successionEntries[0], { ...successionEntries[0], officerId: 'speaker:two' }],
				}),
			/repeat an office/,
		);
	},
);

wardenTest(
	'a law without succession output cannot create a dual-vacancy order',
	[ARTICLE_I.engineering.competenceBeforeProcedure],
	() => {
		assert.throws(
			() =>
				createSuccessionPlan({ law: lawWithOutputs(['general-rule']), entries: successionEntries }),
			/does not authorize.*succession-plan/,
		);
	},
);

const inferiorCourt = Object.freeze({
	id: 'court:district-hamilton',
	name: 'District Court for Hamilton',
	tier: 1,
	originalHeads: ['federal-question'],
	appellateHeads: [],
	venueStates: ['Hamilton'],
});

wardenTest(
	'judiciary-organization law establishes inferior Article III courts',
	[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.derivativeMeans],
	() => {
		const courts = organizeInferiorCourts({ law, courts: [inferiorCourt] });
		assert.equal(courts[0].kind, 'inferior');
		assert.equal(courts[0].establishmentDigest, law.lawDigest);
		assert.equal(courts[0].articleIII, true);
	},
);

wardenTest(
	'judiciary-organization law cannot repeat a court id',
	[ARTICLE_I.engineering.journalEvidence],
	() => {
		assert.throws(
			() => organizeInferiorCourts({ law, courts: [inferiorCourt, inferiorCourt] }),
			/repeat a court id/,
		);
	},
);

wardenTest(
	'judiciary organization requires at least one inferior court',
	[ARTICLE_I.rules.enumeratedPowers],
	() => {
		assert.throws(() => organizeInferiorCourts({ law, courts: [] }), /at least one/);
	},
);

wardenTest(
	'a law without inferior-courts output cannot establish a tribunal',
	[ARTICLE_I.engineering.competenceBeforeProcedure],
	() => {
		assert.throws(
			() =>
				organizeInferiorCourts({ law: lawWithOutputs(['general-rule']), courts: [inferiorCourt] }),
			/does not authorize.*inferior-courts/,
		);
	},
);

const impeachmentSubject = Object.freeze({
	id: 'president:ada',
	officeKind: 'president',
});

const impeachmentArticles = Object.freeze([
	{
		id: 'article:1',
		ground: 'high-crime-or-misdemeanor:abuse-of-office',
		particulars: 'Used an executive capability to defeat an authenticated statutory boundary.',
	},
]);

const impeachmentChargeDigest = digest({
	subject: impeachmentSubject,
	articles: impeachmentArticles,
});

function houseImpeachment(overrides = {}) {
	return impeach({
		congress,
		subject: overrides.subject ?? impeachmentSubject,
		articles: overrides.articles ?? impeachmentArticles,
		houseVote:
			overrides.houseVote ??
			vote('house', impeachmentChargeDigest, {
				membersPresent: 420,
				yeas: 220,
				nays: 200,
			}),
		impeachedAt: overrides.impeachedAt ?? '2026-08-20T18:00:00Z',
	});
}

wardenTest(
	'a House majority creates articles of impeachment',
	[ARTICLE_I.rules.house, ARTICLE_I.rules.impeachment],
	() => {
		const result = houseImpeachment();
		assert.equal(result.status, 'house-impeached');
		assert.equal(result.subject.id, 'president:ada');
		assert.equal(result.handoff, 'article-i:senate-trial');
	},
);

wardenTest(
	'one House vote below the majority rejects impeachment',
	[ARTICLE_I.rules.house, ARTICLE_I.doctrine.defaultMajority],
	() => {
		const result = houseImpeachment({
			houseVote: vote('house', impeachmentChargeDigest, {
				membersPresent: 420,
				yeas: 210,
				nays: 210,
			}),
		});
		assert.equal(result.status, 'impeachment-rejected');
	},
);

wardenTest(
	'House impeachment vote must address the exact articles',
	[ARTICLE_I.engineering.independentConsents],
	() => {
		assert.throws(
			() =>
				houseImpeachment({
					houseVote: vote('house', 'sha256:different-articles', {
						membersPresent: 420,
						yeas: 220,
						nays: 200,
					}),
				}),
			/another chamber or question/,
		);
	},
);

function senateTrial(impeachment = houseImpeachment(), overrides = {}) {
	return tryImpeachment({
		congress,
		impeachment,
		senateVote:
			overrides.senateVote ??
			vote('senate', impeachment.impeachmentDigest, {
				membersPresent: 90,
				yeas: 60,
				nays: 30,
			}),
		presidingOfficer: overrides.presidingOfficer ?? {
			id: 'chief-justice:one',
			role: 'chief-justice',
			authenticated: true,
		},
		triedAt: overrides.triedAt ?? '2026-08-25T18:00:00Z',
		effectiveAt: overrides.effectiveAt ?? '2026-08-25T18:05:00Z',
		disqualified: overrides.disqualified ?? false,
	});
}

wardenTest(
	'exactly two thirds of Senators present convict after House impeachment',
	[ARTICLE_I.rules.senate, ARTICLE_I.rules.impeachment],
	() => {
		const result = senateTrial();
		assert.equal(result.status, 'senate-convicted');
		assert.equal(result.removalRequired, true);
		assert.equal(result.criminalLiability, 'separate-ordinary-process');
		assert.equal(result.handoff, 'article-ii:revoke-authority');
	},
);

wardenTest(
	'one Senate vote below two thirds acquits',
	[ARTICLE_I.rules.senate, ARTICLE_I.rules.impeachment],
	() => {
		const impeachment = houseImpeachment();
		const result = senateTrial(impeachment, {
			senateVote: vote('senate', impeachment.impeachmentDigest, {
				membersPresent: 90,
				yeas: 59,
				nays: 31,
			}),
		});
		assert.equal(result.status, 'senate-acquitted');
	},
);

wardenTest(
	'the Chief Justice presides when the President is tried',
	[ARTICLE_I.rules.impeachment],
	() => {
		assert.throws(
			() =>
				senateTrial(houseImpeachment(), {
					presidingOfficer: {
						id: 'vice-president:grace',
						role: 'president-of-senate',
						authenticated: true,
					},
				}),
			/Chief Justice/,
		);
	},
);

wardenTest(
	'an unauthenticated Chief Justice cannot satisfy the presidential-trial gate',
	[ARTICLE_I.rules.impeachment, ARTICLE_I.engineering.journalEvidence],
	() => {
		assert.throws(
			() =>
				senateTrial(houseImpeachment(), {
					presidingOfficer: {
						id: 'chief-justice:one',
						role: 'chief-justice',
						authenticated: false,
					},
				}),
			/Chief Justice/,
		);
	},
);

wardenTest(
	'Senate conviction requires recorded yeas and nays',
	[ARTICLE_I.rules.quorumAndJournal, ARTICLE_I.rules.impeachment],
	() => {
		const impeachment = houseImpeachment();
		assert.throws(
			() =>
				senateTrial(impeachment, {
					senateVote: vote('senate', impeachment.impeachmentDigest, {
						membersPresent: 90,
						yeas: 60,
						nays: 30,
						yeasAndNaysRecorded: false,
					}),
				}),
			/recorded yeas and nays/,
		);
	},
);

wardenTest(
	'disqualification remains a separately visible consequence',
	[ARTICLE_I.rules.impeachment],
	() => {
		const result = senateTrial(houseImpeachment(), { disqualified: true });
		assert.equal(result.disqualified, true);
		assert.equal(result.removalRequired, true);
	},
);

wardenTest('Senate cannot try a rejected House charge', [ARTICLE_I.rules.impeachment], () => {
	const rejected = houseImpeachment({
		houseVote: vote('house', impeachmentChargeDigest, {
			membersPresent: 420,
			yeas: 210,
			nays: 210,
		}),
	});
	assert.throws(
		() =>
			tryImpeachment({
				congress,
				impeachment: rejected,
				senateVote: {},
				presidingOfficer: {
					id: 'chief-justice:one',
					role: 'chief-justice',
					authenticated: true,
				},
				triedAt: '2026-08-25T18:00:00Z',
				effectiveAt: '2026-08-25T18:05:00Z',
			}),
		/requires House impeachment/,
	);
});

function stateAct(kind, overrides = {}) {
	return {
		id: `state-act:hamilton:${kind}`,
		state: 'Hamilton',
		kind,
		rootDigest: normativeRoot.digest,
		authenticated: true,
		...overrides,
	};
}

for (const kind of STATE_ABSOLUTE_PROHIBITIONS) {
	wardenTest(
		`Article I absolutely prohibits state action: ${kind}`,
		[ARTICLE_I.rules.stateProhibitions],
		() => {
			const result = screenStateAct({ normativeRoot, act: stateAct(kind) });
			assert.equal(result.status, 'state-act-prohibited');
			assert.equal(result.kind, kind);
		},
	);
}

for (const kind of STATE_CONSENT_ACTIONS) {
	wardenTest(
		`state action requires congressional consent: ${kind}`,
		[ARTICLE_I.rules.stateProhibitions, ARTICLE_I.engineering.independentConsents],
		() => {
			const act = stateAct(kind);
			const result = screenStateAct({ normativeRoot, act });
			assert.equal(result.status, 'state-act-requires-congressional-consent');
			assert.equal(result.handoff, 'article-i:congressional-consent');
		},
	);

	wardenTest(
		`authenticated congressional consent permits state action: ${kind}`,
		[ARTICLE_I.rules.stateProhibitions, ARTICLE_I.engineering.independentConsents],
		() => {
			const act = stateAct(kind);
			const result = screenStateAct({
				normativeRoot,
				act,
				congressionalConsent: {
					id: `consent:${act.id}`,
					actId: act.id,
					rootDigest: normativeRoot.digest,
					approved: true,
					authenticated: true,
				},
			});
			assert.equal(result.status, 'state-act-consented');
		},
	);
}

wardenTest(
	'a state may respond to actual invasion when imminent danger admits no delay',
	[ARTICLE_I.rules.stateProhibitions],
	() => {
		const result = screenStateAct({
			normativeRoot,
			act: stateAct('engage-in-war', {
				actuallyInvaded: true,
				imminentDangerAdmitsNoDelay: true,
			}),
		});
		assert.equal(result.status, 'state-emergency-action-allowed');
	},
);

wardenTest(
	'necessary inspection duties pass through the narrow Section 10 exception',
	[ARTICLE_I.rules.stateProhibitions],
	() => {
		const result = screenStateAct({
			normativeRoot,
			act: stateAct('import-export-duty-beyond-inspection', {
				onlyNecessaryInspectionCharge: true,
				netProduceForUnitedStatesTreasury: true,
				subjectToCongressionalRevision: true,
			}),
		});
		assert.equal(result.status, 'state-inspection-duty-allowed');
	},
);

wardenTest(
	'consent for another state act cannot be replayed',
	[ARTICLE_I.engineering.independentConsents],
	() => {
		const act = stateAct('agreement-or-compact');
		const result = screenStateAct({
			normativeRoot,
			act,
			congressionalConsent: {
				id: 'consent:other',
				actId: 'state-act:other',
				rootDigest: normativeRoot.digest,
				approved: true,
				authenticated: true,
			},
		});
		assert.equal(result.status, 'state-act-requires-congressional-consent');
	},
);

wardenTest(
	'a state act from another normative root is rejected before Section 10 analysis',
	[ARTICLE_I.engineering.competenceBeforeProcedure],
	() => {
		assert.throws(
			() =>
				screenStateAct({
					normativeRoot,
					act: stateAct('agreement-or-compact', { rootDigest: 'sha256:foreign-root' }),
				}),
			/current normative root/,
		);
	},
);

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 successionPlan = createSuccessionPlan({ law, entries: successionEntries });

const executive = constituteExecutive({
	normativeRoot,
	federation,
	mandate: {
		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,
	},
	president: {
		id: 'president:ada',
		name: 'Ada',
		naturalBornCitizenDetermination: true,
		ageAtTermStart: 48,
		yearsResident: 30,
		fourteenthAmendmentEligible: true,
		priorElectionsToPresidency: 0,
		actedMoreThanTwoYearsOfAnotherTerm: false,
	},
	vicePresident: {
		id: 'vice-president:grace',
		name: 'Grace',
		naturalBornCitizenDetermination: true,
		ageAtTermStart: 46,
		yearsResident: 28,
		fourteenthAmendmentEligible: true,
		priorElectionsToPresidency: 0,
		actedMoreThanTwoYearsOfAnotherTerm: false,
	},
	term: {
		startsAt: '2025-01-20T17:00:00Z',
		endsAt: '2029-01-20T17:00:00Z',
		constitutionalDurationYears: 4,
		twentiethAmendmentScheduleVerified: true,
	},
	oath: {
		officeholderId: 'president:ada',
		takenAt: '2025-01-20T17:00:00Z',
		authenticated: true,
		swornOrAffirmed: true,
		faithfullyExecute: true,
		preserveProtectDefend: true,
	},
	compensation: {
		compensationRecordDigest: 'sha256:compensation:2025-2029',
		fixedDuringTerm: true,
		otherFederalOrStateEmolumentAccepted: false,
	},
	successionPlan,
});

wardenTest(
	'Article I succession law constitutes the Article II executive without an adapter',
	[ARTICLE_I.engineering.sourcePreservingLaw, ARTICLE_I.engineering.derivativeMeans],
	() => {
		assert.equal(executive.status, 'executive-constituted');
		assert.equal(executive.successionPlan.statuteDigest, law.lawDigest);
		assert.equal(executive.normativeRoot.digest, law.rootDigest);
	},
);

const establishedOffice = establishOffice({ law, office: office() });
const officeCandidate = Object.freeze({
	id: 'officer:warden-administrator',
	name: 'Lin',
	eligibilityVerified: true,
	conflictReviewDigest: 'sha256:warden-admin-conflict-review',
});

const appointedAdministrator = appointOfficer({
	executive,
	office: establishedOffice,
	candidate: officeCandidate,
	nomination: {
		authenticated: true,
		officeId: establishedOffice.id,
		candidateId: officeCandidate.id,
		nominatedBy: 'president:ada',
	},
	senateConsent: {
		authenticated: true,
		approved: true,
		quorumVerified: true,
		officeId: establishedOffice.id,
		candidateId: officeCandidate.id,
		recordDigest: 'sha256:senate-consent-warden-admin',
	},
	appointment: {
		id: 'appointment:warden-administrator',
		actorKind: 'president',
		actorId: 'president:ada',
		officeId: establishedOffice.id,
		candidateId: officeCandidate.id,
		appointedAt: '2026-09-01T12:00:00Z',
		authenticated: true,
	},
	commission: {
		id: 'commission:warden-administrator',
		signedBy: 'president:ada',
		officeId: establishedOffice.id,
		candidateId: officeCandidate.id,
		issuedAt: '2026-09-01T12:05:00Z',
		authenticated: true,
	},
});

wardenTest(
	'Article I office artifact passes directly into Article II appointment',
	[ARTICLE_I.engineering.sourcePreservingLaw, ARTICLE_I.engineering.independentConsents],
	() => {
		assert.equal(appointedAdministrator.status, 'officer-commissioned');
		assert.equal(appointedAdministrator.office.establishmentDigest, law.lawDigest);
		assert.equal(appointedAdministrator.rootDigest, normativeRoot.digest);
	},
);

const militaryAuthority = authorizeMilitaryAction({
	law,
	authorization: militaryAuthorization(),
});

wardenTest(
	'Article I military authorization enters Article II Youngstown category one',
	[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.derivativeMeans],
	() => {
		const command = commandForces({
			executive,
			order: {
				id: 'order:defend-warden',
				issuedBy: 'president:ada',
				authenticated: true,
				force: 'army',
				operation: 'defend-federal-warden-infrastructure',
				scope: 'federal-warden-infrastructure',
				lawOfArmedConflictReviewVerified: true,
				appropriationVerified: true,
			},
			authorization: militaryAuthority,
		});
		assert.equal(command.status, 'military-order-authorized');
		assert.equal(command.authorityCategory, 'youngstown-category-one');
		assert.equal(command.authorizationDigest, digest(militaryAuthority));
	},
);

const inferiorCourts = organizeInferiorCourts({ law, courts: [inferiorCourt] });
const supremeCourt = Object.freeze({
	id: 'court:supreme',
	name: 'Supreme Court',
	kind: 'supreme',
	tier: 2,
	articleIII: true,
	establishedBy: 'constitution',
	establishmentAuthenticated: true,
	originalHeads: ['interstate'],
	appellateHeads: ['federal-question'],
	venueStates: [],
});

const judiciary = constituteJudiciary({
	normativeRoot,
	federation,
	courts: [...inferiorCourts, supremeCourt],
	judges: [
		{
			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',
		},
	],
});

wardenTest(
	'Article I inferior-court artifact constitutes the Article III judiciary',
	[ARTICLE_I.rules.enumeratedPowers, ARTICLE_I.engineering.derivativeMeans],
	() => {
		assert.match(judiciary.judiciaryId, /^judiciary:/);
		assert.equal(judiciary.courts[0].establishedBy, 'federal-statute');
		assert.equal(judiciary.normativeRoot.digest, normativeRoot.digest);
	},
);

const conviction = senateTrial();

wardenTest(
	'Article I impeachment judgment revokes Article II presidential authority',
	[ARTICLE_I.rules.impeachment, ARTICLE_I.engineering.sourcePreservingLaw],
	() => {
		const revocation = applyImpeachmentRemoval({
			executive,
			subject: impeachmentSubject,
			record: conviction,
		});
		assert.equal(revocation.status, 'authority-revoked');
		assert.equal(revocation.active, false);
		assert.equal(revocation.handoff, 'amendment-xxv:presidential-succession');
		assert.equal(revocation.pardonAvailable, false);
	},
);

Усі 151 сценарій проходять. Накопичувальний запуск статей IV, III, II та I проходить 387/387 тестів. Ранні автономні збірки статей VII, VI й V містять відповідно 4, 10 і 23 сценарії. Уся серія документує 424 успішні сценарії WARDEN; єдина поточна runtime-батарея охоплює останні чотири взаємопов’язані модулі, а перші три зберігають власні випробувальні контури bootstrap, root of trust і upgrade protocol.

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

Повний маршрут: від ратифікації до квитанції

Сьома функція дає змогу зібрати всю систему в один граф:

flowchart TB
    A["VII · bootstrap()"] --> B["VI · rootOfTrust()"]
    B --> C["V · upgradeKernel()"]
    C --> D["I · legislate()"]
    D --> E["II · execute()"]
    D --> F["III · resolve()"]
    C --> G["IV · federate()"]
    G --> F
    F --> E
    E --> H["Квитанція виконання"]
    H --> F
topologyНакопичувальна архітектура семи статей

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

  • artifact: Стаття VII · запуск
  • artifact: Стаття VI · root
  • artifact: Стаття V · зміна
  • artifact: Стаття IV · федерація
  • artifact: Стаття I · закон
  • artifact: Стаття III · рішення
  • artifact: Стаття II · виконання
  • artifact: Квитанція повертається до спору
  • vii produces vi
  • vi produces v
  • v produces iv
  • iv produces i
  • iv produces iii
  • i references iii
  • i produces ii
  • iii executes ii
  • ii returns receipt
  • receipt returns iii
Накопичувальна архітектура семи статейIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g07 · authorial brief

Лінійність цієї схеми умовна. Конституційний runtime є графом станів і зворотних зв’язків. Закон здатен організувати суд, після чого суд розглядає спір про закон. Виконавець повертає квитанцію суду. Поправка змінює root, під яким діють усі наступні артефакти. Федеративний конфлікт створює case or controversy. Імпічмент відкликає виконавче повноваження й запускає наступництво. Кожна стрілка зберігає source digest, сферу та handoff.

У коді досягнуто п’ять накопичувальних властивостей:

  1. Походження. Кожен чинний об’єкт пов’язаний із root і батьківськими рішеннями.
  2. Розділення станів. Проєкт, норма, рішення, наказ, матеріальна дія та квитанція представлені різними подіями.
  3. Обмежена capability. Компонент отримує визначену операцію, мету, сферу й спосіб перегляду.
  4. Безпечна відмова. Невизначеність або дефект створюють спостережуваний стан і маршрут вирішення замість мовчазного продовження.
  5. Незмінна lineage. Перегляд створює новий об’єкт, зберігаючи історію первинного рішення.

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

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

Історична форма статті I переноситься в software governance через такі функції:

Механізм статті IІнвертована функціяМожлива програмна форма
Legislative Vestingзаздалегідь визначений нормотворець і предметпрофіль ролей, ownership, реєстр повноважень
Дві палатинезалежні підстави згодиreview власника сфери + security/legal/data approval за ризиком
Кворум і журналчинний склад і доказ рішенняpolicy quorum, signed decision record, append-only log
Один текстзгода з точною редакцієюcommit SHA, artifact digest, immutable proposal
Presentment і vetoнезалежне заперечення та заміщенняblocking review, objection window, override threshold
Перелічені повноваженняпредметна компетенціяbounded authority за domain, repository, environment та effect
Necessary and Properвибір похідного засобуimplementation discretion, пов’язаний із прийнятою policy
Appropriationsокреме право на спільний ресурсуповноваження для budget, secret, production, signing key і release
Bill of Attainder / ex post factoрозмежування норми й особистої відповідальностізагальні правила, доведений incident record, окремий дисциплінарний процес
Обмеження штатівавтономія частин усередині спільних межlocal jurisdiction + consent для shared contracts і state

Найсильніша частина моделі пов’язана з походженням і переходами. Software уже складається з формальних артефактів, версій, залежностей, журналів, ролей і машинних перевірок. Зв’язок «точна норма → повноваження → реалізація → спостереження» природно виражається кодом. Конституційний спосіб постановки питань робить приховану владу видимою: хто має право змінити API, хто розпоряджається production, хто визначає security boundary, яка практика стала обов’язковою та як її скасувати.

Середня за силою частина пов’язана з інституційними аналогіями. Дві палати корисні як питання про незалежні згоди й часто надмірні як буквальна організаційна копія. Президентський підпис корисний як зовнішній objection gate і небезпечний як культ єдиного merge-authority. Федерація корисна для автономних юрисдикцій і потребує адаптації до реальної топології проєкту.

Найслабша частина моделі пов’язана з автоматичним визначенням змісту. Код здатен перевірити заявлену категорію, поріг, digest і сферу. Він обмежено здатен визначити, чи є конкретна норма bill of attainder, чи справді засіб necessary and proper, чи існує політичне питання та чи справедлива основна підстава. Ці рішення потребують тлумачення, фактів, представництва й відповідальності. Формалізація робить вхід видимим і не знищує людської природи рішення.

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

Модель має шість основних меж.

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

Другою межею є довіра до входів. Поля authenticated: true, authorityVerified: true і constitutionalCompatibilityDetermined: true означають результати зовнішньої перевірки. Виробнича система потребуватиме підписів, схем, довіреного часу, журналів, розділеної атестації та реального процесу оскарження. Булеве поле зручне для лабораторії й має приблизно ту саму доказову силу, що й табличка «усе перевірено» на дверях відділу внутрішнього контролю.

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

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

П’ятою межею є вартість. Повна модель виправдана для довготривалого проєкту з кількома юрисдикціями, чутливими даними, публічними зобов’язаннями, складною поставкою та високою ціною незворотного рішення. Локальна утиліта отримує користь із кількох елементів: ясного ownership, точної редакції, tests, журналу рішення та rollback. Решта державного апарату може спокійно залишитися у Вашингтоні.

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

Підсумкова оцінка придатності моделі

Експеримент дав позитивний результат на рівні нормативної архітектури. Усі сім статей надали переносні функції:

  • установлення та сфера порядку;
  • визначення довіреного корпусу;
  • зміна основної підстави;
  • відносини автономних юрисдикцій;
  • створення загальної норми;
  • виконання й спостереження результату;
  • вирішення конкретного спору.

Програмна система здатна виразити ці функції через типізовані артефакти, стани, digests, журнали, capabilities, тести й handoffs. Накопичувальний прототип показує сумісність інтерфейсів і безпечні відмови. Він також показує, що буквальне відтворення американських інституцій створює зайву церемонію та хибну політичну суб’єктність компонентів.

Практична адаптація використовує метод функціональної інверсії: історична норма спершу відновлюється як функція, а потім отримує нові предмет, суб’єкта, сферу, доказ і межу. Конгрес не перейменовується на maintainer team. Із двопалатності виділяється незалежність згод. З Appropriations Clause — різниця між доступом і правом розпорядження. Зі статті III — конкретний спір і доведений record. Зі статті V — різниця між нормативною зміною й технічною міграцією. Зі статті VII — зовнішній установчий bootstrap.

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

Висновок

У першій публікації карта UCA лише починала світитися. Дев’ять локальних рішень створювали сферу нового порядку, а WARDEN перевіряв чотири умови запуску. У фіналі ця карта отримала законодавче джерело, федеративні зв’язки, суд, виконання, оновлення ядра й спільний root of trust. Орел вийшов із завантажувача й виявив, що production оточений журналами, digests і кількома незалежними суб’єктами, кожен із яких уміє сказати «ні». Для республіканської архітектури це вважається ознакою здоров’я.

Стаття I завершує модель у точці походження звичайної норми. legislate() доводить компетенцію, зберігає один точний текст, збирає дві незалежні згоди, проводить представлення, видає обмежені capabilities і залишає результат доступним для суду та поправки. 151 тест підтверджує реалізацію цього контракту. 424 сценарії всієї серії показують, що сім конституційних функцій здатні утворити зв’язну виконувану лабораторію.

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

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

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

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

navigatorнавігатор питань

Маршрут розмови від походження закону до підсумкової оцінки програмної адаптації семи статей

  • artifact: Стаття I
  • state: Нормотворець
  • state: Дві згоди
  • state: Одна редакція
  • state: Представлення
  • state: Компетенція
  • state: Прямі заборони
  • state: Спільні ресурси
  • state: Імпічмент
  • state: Міжмодульний маршрут
  • state: WARDEN
  • state: Software governance
  • human-decision: Підсумок семи статей
  • root produces normmaker
  • normmaker produces consents
  • consents produces text
  • text produces presentment
  • presentment produces competence
  • competence produces prohibitions
  • prohibitions produces resources
  • resources produces impeachment
  • impeachment produces modules
  • modules produces warden
  • warden produces governance
  • governance produces conclusion
навігатор питаньIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g08 · authorial brief

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

Автори: Sam Starling, Oksana Dubinetska
Контекст проєкту: Zhovten Games / IRONCREED
Повне дослідницьке джерело: «Конституція коду» — DOI 10.5281/zenodo.21894242
Дослідницький репозиторій: FOP-Oksana-Dubinetska/code-constitution
Історичні, правові й технічні матеріали: текст Конституції США; поправки XI–XXVII; огляд статті I; двопалатність; Origination Clause; президентське схвалення та вето; перелічені повноваження; Necessary and Proper Clause; Appropriations Clause; матеріали Сенату про імпічмент; законодавчий процес Палати представників
Пов’язані публікації: «Підключити Америку: як стаття VII запускає республіку»; «Чому довіряє Америка: як стаття VI збирає верховний порядок»; «Оновити Америку: як стаття V змінює конституційне ядро»; «Зв’язати Америку: як стаття IV перетворює штати на федеративну мережу»; «Розсудити Америку: як стаття III перетворює конфлікт на виконуване рішення»; «Виконати Америку: як стаття II перетворює рішення на дію»
Статус циклу: завершено · публікація 7 із 7
Редакція публікації: 0.2 · 13 серпня 2026 року