Starting question

How can a system turn political intent into a generally binding rule, prove the normmaker’s competence, obtain independent consents to one exact text, survive an objection, issue bounded authority to other components, and preserve a route for challenging the result?

The complete research foundation for this public adaptation is available on Zenodo: Code Constitution.

herolead image

Article I turns a proposal into law through competence, two independent consents, one exact text, and a verifiable presentment route.

  • source: Competence
  • actor: House of Representatives
  • actor: Senate
  • artifact: One exact text
  • decision: Presentment
  • artifact: Law
  • boundary: Bounded powers
  • process: Challenge
  • competence requires house
  • competence requires senate
  • house validates text
  • senate validates text
  • text requires presentment
  • presentment produces law
  • law executes powers
  • powers returns challenge
lead imageIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g01 · authorial brief

The last station stands at the beginning of the route

In Death Stranding, connecting a station to the UCA looks like the end of the job. The map lights up, the network accepts a new node, the interface announces that America has expanded, and the player gains access to shared data and infrastructure. Then the less ceremonial part of state-building begins: somebody must authorize expenditure of materials, set the road’s rules, name the responsible actor, limit access, and decide what happens when the new line runs through somebody else’s shelter. Connectivity creates the possibility of common action. A general rule determines which action has acquired the right to become common.

The previous six publications moved in reverse. Article VII launched the order after ratification. Article VI identified the trusted revision and hierarchy of operative sources. Article V taught the kernel to change. Article IV connected autonomous jurisdictions. Article III accepted a concrete dispute and formed a bounded remedy. Article II turned a law or judgment into action and returned a receipt of execution. At every layer, there were references to law, a legally established office, an appropriation, military authorization, an impeachment process, or the organization of a court. The producer of those objects remained outside the frame.

Article I opens that frame. It shows where a general derivative rule comes from, why two groups may disagree about it independently, which exact revision actually received consent, how the President participates, which subjects are available to the federal legislature at all, and which decisions remain prohibited even after a flawless vote. In our software build, the final function sits at the beginning of most operational chains:

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

The reverse order of reading now reveals its purpose. We first saw a working system and then gradually returned to the place where it acquires authority to produce what it will later execute, interpret, recognize, and defend. The final publication concerns the origin of ordinary law and also concludes the entire experiment.

The seventh build

The full model contains seven constitutional functions:

PublicationConstitutional functionPrototype state
VIIbootstrap()Establishes the system after sufficient ratification
VIrootOfTrust()Identifies the trusted revision, continuity, and order of supremacy
VupgradeKernel()Changes the normative kernel and separates amendment force from runtime migration
IVfederate()Connects autonomous nodes and interjurisdictional protocols
IIIresolve()Accepts a concrete dispute, establishes the record, and forms a bounded remedy
IIexecute()Transforms an operative source into bounded action and a receipt
Ilegislate()Produces a general rule and issues authority to the other components

Article I contains ten sections and is the Constitution’s longest original article. For the software model, they form four blocks:

BlockSectionsSoftware question
Holder and reproduction of power1–4Who may participate in normmaking, and where does that mandate come from?
Internal validity and law5–7How do quorum, journal, two Houses, one revision, and presentment create law?
Positive competence8Which subjects are available to Congress, and which means derive from granted power?
Limits9–10Which decisions are prohibited to the Union and the states, or require special consent?

The executable module expands these blocks into seventeen public operations. The central legislate() conducts an ordinary law through the entire route. The other functions expose individual transitions and make them independently testable:

OperationPurpose
constituteCongress()Binds two Houses, their composition, representation, terms, and current root
recordChamberVote()Verifies quorum, threshold, exact subject of the vote, and journal record
introduceBill()Verifies origin, competence, direct prohibitions, and revenue origination
createBillVersion()Creates an exact text with digest and parent lineage
passChamber()Binds a House’s independent consent to a specific revision
enrollBill()Admits to presentment only one text approved by both Houses
presentBill()Models signature, return veto, the ten-day route, and pocket veto
overrideVeto()Verifies a repeated two-thirds vote in each House
legislate()Assembles the complete ordinary pipeline from proposal to law
authorizeAppropriation()Creates bounded authority to use a common monetary resource
establishOffice()Issues an office contract compatible with Article II
authorizeMilitaryAction()Issues a proved congressional basis for a military order
createSuccessionPlan()Creates a statutory route for dual vacancy
organizeInferiorCourts()Establishes lower courts for Article III
impeach() / tryImpeachment()Separates House accusation from the Senate’s trial function
screenStateAct()Checks absolute prohibitions and state acts requiring congressional consent

The module retains the historical Article I as the experiment’s subject. Conclusions for software governance emerge after execution through inversion of function. The project repository does not need two Houses of developers, a President of the main branch, and a Senate of pull requests. It needs clear answers to the same questions: who makes a generally binding rule, in which subject and scope, through which procedure, with which independent consents, to which exact revision, how an objection is recorded, and where the normmaker’s authority ends.

One legislative power, divided within itself

The first sentence of Article I vests the federal legislative powers granted by the Constitution in a Congress consisting of a House of Representatives and a Senate. Constitution Annotated treats bicameralism as a structural condition of federal legislation. One function receives two independent institutional foundations.

The House is organized around population, regular reelection, and apportionment. The Senate is organized around equal representation of states, six-year terms, and staggered renewal. The Seventeenth Amendment replaced selection of senators by state legislatures with direct election while preserving equality among states and the classes of terms. The Fourteenth Amendment replaced the original representation formula, the Twentieth set the modern beginning of congressional terms, and the Twenty-Seventh separated changes in member compensation from immediate benefit to the sitting Congress. The current normativeRoot therefore represents Article I together with operative amendments while preserving original rules in historical lineage.

The prototype expresses the distinction between Houses through representation: "population-apportioned" and representation: "equal-state". It requires separate proof of elections, qualifications, and the operative revision of the rules. The Senate additionally requires direct election and staggered continuity. One congress object contains both Houses, yet neither House may fill in the other’s result.

This design gives software architecture an important criterion of independent consent. Two approvals represent two grounds of decision only when each belongs to a separate actor, carries separate responsibility, and preserves a genuine power to refuse. Two buttons in one interface, pressed in sequence by one authority holder, create two events and one ground of will. Code Constitution therefore transfers the function of bicameralism through independence of consent, while the project’s Founding Profile sets the specific number of approving parties according to risk.

flowchart TB
    A["Draft general rule"] --> B["House of Representatives"]
    A --> C["Senate"]
    B --> D["House-approved revision"]
    C --> E["Senate-approved revision"]
    D --> F{"Same text?"}
    E --> F
    F -- "Yes" --> G["Enrolled bill"]
    F -- "No" --> H["Reconciliation and another vote"]
gateTwo independent Houses and one revision

The House and Senate vote separately on exact revisions; only identical text may proceed to presentment.

  • artifact: Bill
  • artifact: House revision
  • artifact: Senate revision
  • decision: Digests match?
  • artifact: One enrolled text
  • state: Presentment
  • state: Return for reconciliation
  • proposal produces house
  • proposal produces senate
  • house validates digest
  • senate validates digest
  • digest validates enrolled: Yes
  • digest rejects revision: No
  • enrolled produces presentment
Two independent Houses and one revisionIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g02 · authorial brief

Composition enables a decision; quorum creates an operative sitting

Sections 2–6 govern elections, qualifications, vacancies, terms, officers of the Houses, quorum, rules, discipline, journals, adjournments, compensation, privilege, and incompatibility of offices. These provisions protect continuity of the legislative function and distinguish institutional authority from the accidental presence of people in a room.

In the prototype, constituteCongress() does not store the biographies of 535 members. It accepts certified results of external processes and creates a verifiable snapshot: number of seats, number of sitting members, form of representation, completion of qualification review, term, and current normative root. This reduction preserves the architectural function and openly leaves elections, mandate disputes, and actual representation to external systems.

recordChamberVote() then checks a narrower domain. A majority of sitting members constitutes a quorum. With quorum present, an ordinary question passes by a majority of those voting unless the Constitution prescribes another threshold. Veto override and conviction on impeachment require two thirds of those present. Every vote binds to a questionDigest, because a record of “230 in favor” is empty without an answer to “in favor of which revision?”

The Journal Clause gives the process a public memory. The prototype requires an authenticated and published record and, for qualified thresholds, recorded yeas and nays. In places, this requirement strengthens the text’s literal minimum through a uniform engineering rule of provability. The journal proves the event, composition, subject, and result. It neither creates missing competence nor cures a substantive constitutional defect.

The first general rule of the series follows:

Proof of procedure proves procedure. Authority, substantive permissibility, and factual execution require evidence of their own.

A Git commit performs a similarly limited function. It can prove that a particular record entered history after a particular parent revision. It does not give that record the status of architectural law, the consent of affected parties, or conformity with a higher order. A normative journal adds precisely those relationships.

A law has a revision before it receives a number

The practical legislative process is much richer than three constitutional sentences: committees, hearings, calendars, amendments, conferences, rules of debate, and many kinds of parliamentary act. The House of Representatives describes the operational sequence from introduction to presidential consideration. Article I establishes the higher contract: both Houses must pass one text, after which it undergoes presentment.

The prototype makes a revision an independent object. createBillVersion() stores the text, textDigest, House, parent digest, amendments, and creation time. passChamber() binds a vote to versionDigest. enrollBill() compares the content of approved revisions and returns bicameral-disagreement when they differ.

The comparison concerns text, not local action identifiers. The House and Senate may create two separate objects at different times and through different procedural lineages while containing one revision of the bill. Their versionDigest values differ; their textDigest values match. The enrolled bill receives a new digest that preserves both actions and the common text.

This distinction exposed the first substantive defect in our own implementation. An early WARDEN version required matching versionDigest values. That condition made enactment impossible: the revision identifier included the House and time, so two independent consents could never produce byte-identical objects. The correction moved the comparison to textDigest while preserving both provenance lines separately. Formal rigor stopped blocking the very independence it was supposed to protect.

The Revenue Origination Clause adds a special rule. A bill for raising revenue originates in the House of Representatives; the Senate retains the power to propose and concur with amendments. Constitution Annotated connects this requirement with the House’s originally direct popular representation and permits substantive Senate amendments. The model therefore blocks a Senate-originated revenue bill while allowing the Senate to amend text already passed by the House. The amended revision returns to the ordinary condition: both Houses must again confirm the same content.

Presentment creates four routes to law

After the Houses agree, the enrolled bill goes to the President. Section 7 of Article I creates several outcomes:

  1. The President signs the bill, and it becomes law.
  2. The President returns it to the House of origin with objections; Congress may override the veto by two thirds of each House.
  3. The President does not return the bill within ten days, Sundays excepted; if return remains possible, it becomes law without signature.
  4. An adjournment of Congress prevents return, and presidential inaction produces a pocket veto.

The prototype expresses these routes through presentBill() and overrideVeto(). An ordinary veto preserves the enrolled bill unchanged, adds objections, and returns control to the originating House. Override creates a new presentment digest from two qualified votes. A pocket veto ends the current route and requires a new legislative process.

stateDiagram-v2
    state "One revision approved by both Houses" as Enrolled
    state "Signed by the President" as Signed
    state "Returned with objections" as Vetoed
    state "Two thirds of both Houses" as Override
    state "Ten days without signature" as TenDays
    state "Return prevented by adjournment" as Pocket
    state "Law took effect" as Law

    [*] --> Enrolled
    Enrolled --> Signed
    Enrolled --> Vetoed
    Enrolled --> TenDays
    Enrolled --> Pocket
    Signed --> Law
    TenDays --> Law
    Vetoed --> Override
    Override --> Law
    Pocket --> [*]
gateFour presentment routes

An enrolled bill becomes law by signature, expiration of ten days, or override of an ordinary veto; a pocket veto ends the route without law.

  • artifact: Enrolled bill
  • decision: Presentment to the President
  • process: Signature
  • process: Expiration of 10 days
  • process: Return with objections
  • process: Veto override
  • state: Pocket veto
  • state: Law
  • state: Route ends without law
  • 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
Four presentment routesIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g03 · authorial brief

The calendar calculation in the code is a laboratory model. It counts in UTC, begins with the next calendar day, and excludes Sundays. Actual pocket-veto analysis depends on the kind of adjournment, the possibility of return, and constitutional practice. The prototype checks the state supplied as congressAdjournedPreventsReturn and does not pretend to interpret every congressional calendar automatically.

Competence precedes the vote

Section 8 enumerates congressional powers: taxes and spending, borrowing, commerce, naturalization and bankruptcy, money and standards, postal services, exclusive rights for authors and inventors, lower courts, international offenses, war, armed forces, the militia, the federal district, and federal property. The Necessary and Proper Clause completes the list with authority to make laws necessary and proper for carrying granted powers into execution. The overview of enumerated powers and overview of the Necessary and Proper Clause connect the selection of means with a legitimate constitutional end.

introduceBill() requires a powerClaim. An ordinary basis is selected from enumerated powers or enforcement powers supplied by later amendments. necessary-and-proper is admitted together with linkedPower and four determinations: a legitimate end, means adapted to it, absence of prohibition, and compatibility with the Constitution. The field necessaryAndProper: true alone does not give Congress a universal administrative screwdriver.

flowchart TB
    A["Bill’s end"] --> B{"Granted power exists?"}
    B -- "No" --> C["Bill blocked"]
    B -- "Yes" --> D{"Means necessary and proper?"}
    D -- "No" --> C
    D -- "Yes" --> E{"Direct prohibition?"}
    E -- "Yes" --> C
    E -- "No" --> F["Bill admitted to procedure"]
gateCompetence and derivative means

A legislative end passes through granted power, review of necessary and proper means, and direct constitutional prohibitions before voting.

  • artifact: Legislative end
  • decision: Granted power?
  • decision: Necessary and proper means?
  • decision: Direct prohibition?
  • state: Eligible for voting
  • state: Safe rejection
  • purpose requires grant
  • grant validates means: Yes
  • grant rejects reject: No
  • means validates prohibition: Yes
  • means rejects reject: No
  • prohibition rejects reject: Yes
  • prohibition validates vote: No
Competence and derivative meansIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g04 · authorial brief

The software analogy is especially strong here. An architectural normmaker receives a defined subject and scope. It may adopt binding rules within them and delegate the manner of execution. The delegated component remains linked to its source and cannot expand the end merely because doing so is technically efficient. A linter can check an adopted rule. Its power to block a build does not turn it into the source of the rule. An LLM may draft text, classify consequences, and expose a conflict. Successful generation creates no mandate to enact the result.

A direct prohibition survives a qualified majority

Section 9 sets limits on federal power. The prototype checks eight classes: bills of attainder, retroactive penal prohibitions, unjustified suspension of habeas corpus, a defective direct tax outside the operative Sixteenth Amendment, a tax on a state’s exports, preference among ports, spending from the Treasury without appropriation, and titles of nobility.

The Bill of Attainder Clause is especially important to the boundary between legislative and judicial functions. A general rule describes conduct, conditions, and consequences. A legislative act that selects a named person or closed group and assigns punishment without trial appropriates another branch’s authority. Constitution Annotated defines the doctrine through legislative punishment of specified persons or groups. The Ex Post Facto Clause prohibits retroactive penal worsening; civil retroactivity requires other analysis and remains outside this narrow automated screen.

A procedure can run without one error and still produce a prohibited result. That is why introduceBill() checks competence and direct prohibitions before voting. WARDEN does not let both Houses and the President legalize titleOfNobility: true by shared enthusiasm. A real dispute over classification of a particular law remains an Article III judicial question; the test model recognizes a preformalized feature and preserves the limit of its classification.

The historical text of Article I also exposes a deeper problem. The Three-Fifths Clause turned enslaved people into a coefficient of representation, and Section 9 protected the importation of enslaved people from federal prohibition until 1808. These provisions belonged to the original constitutional foundation and were served by valid procedures. Amendments XIII and XIV changed the root, while Article V supplied the formal route for change. Software correctness of the original order did not make it materially acceptable. It merely made the exploitation of human beings reproducible, apportioned, and neatly recorded—the rare case in which quality assurance faithfully certified the quality of an institutional crime.

Code Constitution derived a negative result from this inversion. A rule’s validity within an order, its conformity with external law, representation of affected parties, and permissibility of its subject are different layers. A project normmaker may enact a binding architectural act and simultaneously create an act that remains challengeable or terminable. The normative system preserves both a procedure for changing its foundation and the participants’ right to question the root itself.

Appropriation turns access into bounded authority to spend

The Appropriations Clause prohibits drawing money from the Treasury without an appropriation made by law and requires regular publication of accounts of receipts and expenditures. Constitution Annotated treats the provision as a foundation of congressional control over public funds.

authorizeAppropriation() requires an enacted law with an explicit appropriation output. The artifact names a purpose, maximum amount, unit, period of availability, accountable actor, and public ledger. Technical access to an account does not replace it. A presidential order does not create it either. Before material action, the executive can verify appropriationDigest, purpose, and remaining balance.

In software governance, common resources include the canonical repository, Git history, secrets, production environment, identifier registry, domain, signing keys, budget, and release. Possession of credentials proves the ability to act. Normative authority to dispose of the resource arises from a defined source, subject, and consent. This function of Article I transfers with almost no loss.

flowchart TB
    A["Law"] --> B["Appropriation"]
    B --> C["Purpose"]
    B --> D["Maximum amount and period"]
    B --> E["Accountable actor"]
    B --> F["Public ledger"]
    C --> G["Executive action"]
    D --> G
    E --> G
    F --> G
    G --> H["Receipt and remaining balance"]
flowAuthority over a shared resource

An enacted law creates a bounded appropriation with purpose, amount, period, accountable actor, and public journal; execution returns a receipt.

  • artifact: Enacted law
  • state: Purpose
  • state: Amount
  • state: Period
  • actor: Accountable actor
  • artifact: Public journal
  • process: Bounded execution
  • artifact: Receipt
  • law produces purpose
  • purpose produces amount
  • amount produces period
  • period produces actor
  • actor produces journal
  • journal produces execution
  • execution produces receipt
Authority over a shared resourceIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g05 · authorial brief

Law issues a capability; it does not exercise one

The final article links the previously separate modules. An enacted law contains outputs, each authorizing a distinct derivative artifact:

Law outputDerivative artifactNext consumer
appropriationBounded appropriationArticle II and an executive plan
office-establishmentOffice, classification, and appointment routeArticle II’s appointOfficer()
military-authorizationCongressional basis and scopeArticle II’s commandForces()
succession-planStatutory dual-vacancy orderconstituteExecutive() and Amendment XXV
inferior-courtsLower courts, jurisdictional heads, and territoriesArticle III’s constituteJudiciary()
House impeachment + Senate convictionAuthority-revocation judgmentArticle II’s applyImpeachmentRemoval()

This design preserves the separation among rule, derivative authority, and action. A law establishing an office creates an office contract. It does not appoint a particular person when the Constitution requires a separate route. Military authorization defines scope and moves presidential action into the first category of the Youngstown framework. It does not select every tactical operation. A judiciary act creates a lower court. A judicial decision arises later, after a case, record, and independent hearing.

Impeachment is a special bicameral process. The House possesses the sole power of impeachment. The Senate possesses the sole power to try impeachments; conviction requires two thirds of members present, and the Chief Justice presides when the President is tried. Senate materials separately describe conviction, mandatory removal, and possible disqualification. Criminal liability remains within ordinary process.

The prototype creates House impeachment as a separate object and then binds the Senate vote to its exact digest. A successful judgment receives handoff: "article-ii:revoke-authority". Article II accepts the record without an adapter, revokes the capability, and starts presidential succession. Presidential clemency remains unavailable for impeachment.

States retain their own power within common prohibitions

Section 10 concludes Article I with prohibitions on the states. Some acts are prohibited absolutely: treaties and alliances, letters of marque, coining money, bills of credit, impermissible legal tender, bills of attainder, ex post facto laws, impairment of contractual obligation, and titles of nobility. Other acts require congressional consent: certain duties, tonnage, peacetime troops and warships, agreements or compacts, and entry into war. The text preserves exceptions for necessary inspection laws and immediate defense against invasion or danger that permits no delay.

screenStateAct() returns three main classes: absolute prohibition, consent required, and permitted action with proved consent. Consent binds to an exact actId and current root, so it cannot be reused for another compact. The emergency exception is checked separately and does not become a permanent military capability.

This continues the Article IV model. Federation recognizes the autonomy of nodes; Article I defines part of the common boundary around their normmaking. A software project may likewise contain autonomous packages, services, repositories, and teams with local competence. The common order names acts affecting shared state, a security boundary, public contract, or external obligation and requires separate consent. Local autonomy receives a formal scope instead of the promise “do whatever you want until CI starts smoking.”

The executable legislative layer

Below is the complete ESM module for the final build. It uses the shared digest() function from Article IV, preserves immutable snapshots, and issues artifacts in the formats consumed by Articles II and 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: 151 scenarios for producing law

Article I receives the largest individual test battery in the series. Its subject is broad: composition of Congress, competence, revisions, votes, the journal, four presentment routes, qualified thresholds, protected resources, derivative authority, impeachment, and state limits.

GroupRelationships under testPrincipal source
Constitution of Congressroot, two Houses, representation, elections, qualifications, and termSections 1–4; Amendments XIV, XVII, and XX
Competenceenumerated and amendment powers, Necessary and ProperSection 8; enforcement powers of later amendments
Federal limitsdirect prohibitions, habeas exception, and Amendment XVISection 9; Amendment XVI
Revenue originationorigin in the House and Senate power to amendSection 7, Clause 1
Internal procedurequorum, thresholds, journal, and exact question digestSection 5; default-majority doctrine
Bicameralismseparate House actions and one text digestSections 1 and 7; exact-text invariant
Presentmentsignature, veto, ten-day route, pocket veto, and overrideSection 7
Derivative artifactsappropriation, office, court, military authorization, and successionSections 8–9; Appointments and Succession Clauses; Article III
ImpeachmentHouse charge, Senate trial, two thirds, and bounded judgmentSections 2–3; Article II, Section 4
State limitsabsolute prohibitions, consent, and emergency exceptionsSection 10
Cross-module integrationone root and compatible contracts for Articles I–IVcumulative prototype architecture

The groups overlap: one integration scenario may simultaneously test a legislative output, root binding, and an Article II or III input, while loops generate separate tests for complete registries of powers and prohibitions. The authoritative node --test result is 151 tests, 151 pass, 0 fail. That is a small useful defense against the ritual in which a beautifully formatted table receives more trust than the executable suite it supposedly describes.

matrixWARDEN matrix
Article I textOperative amendmentsDoctrineEngineering extensions
CompositionCongress structure · trace:ARTICLE_I.rules.vestingElections and terms · trace:ARTICLE_I.amendments.seventeenthQualification dispute · human-reviewRoot mismatch · trace:ARTICLE_I.engineering.wardenBoundary
CompetenceEnumerated power · trace:ARTICLE_I.rules.enumeratedPowersEnforcement power · trace:AMENDMENT_ENFORCEMENT_POWERSNecessary and proper means · trace:ARTICLE_I.doctrine.necessaryAndProperAuthority absent · trace:ARTICLE_I.engineering.competenceBeforeProcedure
RevisionOne bill text · trace:ARTICLE_I.rules.bicameralismAndPresentmentAmendment conflict · human-reviewExact text · trace:ARTICLE_I.doctrine.exactTextDigest mismatch · trace:ARTICLE_I.engineering.independentConsents
VotingQuorum and journal · trace:ARTICLE_I.rules.quorumAndJournalAmended threshold · human-reviewDefault majority · trace:ARTICLE_I.doctrine.defaultMajorityJournal cannot create validity · trace:ARTICLE_I.engineering.journalEvidence
PresentmentTwo chambers and presentment · trace:ARTICLE_I.rules.bicameralismAndPresentmentAmendment interaction · human-reviewFive routes · trace:ARTICLE_I.doctrine.presentmentBlocked bill · trace:ARTICLE_I.engineering.wardenBoundary
ResourceAppropriation by law · trace:ARTICLE_I.rules.appropriationsAmendment boundary · human-reviewDerivative means · trace:ARTICLE_I.doctrine.necessaryAndProperUnbounded resource · trace:ARTICLE_I.engineering.protectedResources
ImpeachmentCharge and trial · trace:ARTICLE_I.rules.impeachmentRemoval consequence · human-reviewBounded judgment · human-reviewIndependent consent absent · trace:ARTICLE_I.engineering.independentConsents
StatesState prohibitions · trace:ARTICLE_I.rules.stateProhibitionsEnforcement power · trace:ARTICLE_I.amendments.fourteenthConsent or exception dispute · human-reviewConsent is not root-bound · trace:ARTICLE_I.engineering.independentConsents
IntegrationShared constitutional root · trace:ARTICLE_I.rules.vestingOperative amendment lineage · trace:normativeRoot.lineageCross-module dispute · human-reviewLineage mismatch · trace:ARTICLE_I.engineering.sourcePreservingLaw

WARDEN maps 151 Article I scenarios to the literal text, amendments, doctrine, and engineering invariants.

  • source: Article I text
  • source: Operative amendments
  • source: Doctrine
  • source: Engineering extensions
  • state: Composition
  • state: Competence
  • state: Revision
  • state: Voting
  • state: Presentment
  • state: Resource
  • state: Impeachment
  • state: States
  • state: Integration
  • article-text validates composition: Congress structure · trace:ARTICLE_I.rules.vesting
  • amendments validates composition: Elections and terms · trace:ARTICLE_I.amendments.seventeenth
  • doctrine returns composition: Qualification dispute · human-review
  • engineering rejects composition: Root mismatch · trace:ARTICLE_I.engineering.wardenBoundary
  • article-text validates competence: Enumerated power · trace:ARTICLE_I.rules.enumeratedPowers
  • amendments validates competence: Enforcement power · trace:AMENDMENT_ENFORCEMENT_POWERS
  • doctrine validates competence: Necessary and proper means · trace:ARTICLE_I.doctrine.necessaryAndProper
  • engineering rejects competence: Authority absent · trace:ARTICLE_I.engineering.competenceBeforeProcedure
  • article-text validates revision: One bill text · trace:ARTICLE_I.rules.bicameralismAndPresentment
  • amendments returns revision: Amendment conflict · human-review
  • doctrine validates revision: Exact text · trace:ARTICLE_I.doctrine.exactText
  • engineering rejects revision: Digest mismatch · trace:ARTICLE_I.engineering.independentConsents
  • article-text validates voting: Quorum and journal · trace:ARTICLE_I.rules.quorumAndJournal
  • amendments returns voting: Amended threshold · human-review
  • doctrine validates voting: Default majority · trace:ARTICLE_I.doctrine.defaultMajority
  • engineering rejects voting: Journal cannot create validity · trace:ARTICLE_I.engineering.journalEvidence
  • article-text validates presentment: Two chambers and presentment · trace:ARTICLE_I.rules.bicameralismAndPresentment
  • amendments returns presentment: Amendment interaction · human-review
  • doctrine validates presentment: Five routes · trace:ARTICLE_I.doctrine.presentment
  • engineering rejects presentment: Blocked bill · trace:ARTICLE_I.engineering.wardenBoundary
  • article-text validates resource: Appropriation by law · trace:ARTICLE_I.rules.appropriations
  • amendments returns resource: Amendment boundary · human-review
  • doctrine returns resource: Derivative means · trace:ARTICLE_I.doctrine.necessaryAndProper
  • engineering rejects resource: Unbounded resource · trace:ARTICLE_I.engineering.protectedResources
  • article-text validates impeachment: Charge and trial · trace:ARTICLE_I.rules.impeachment
  • amendments returns impeachment: Removal consequence · human-review
  • doctrine returns impeachment: Bounded judgment · human-review
  • engineering rejects impeachment: Independent consent absent · trace:ARTICLE_I.engineering.independentConsents
  • article-text validates states: State prohibitions · trace:ARTICLE_I.rules.stateProhibitions
  • amendments validates states: Enforcement power · trace:ARTICLE_I.amendments.fourteenth
  • doctrine returns states: Consent or exception dispute · human-review
  • engineering rejects states: Consent is not root-bound · trace:ARTICLE_I.engineering.independentConsents
  • article-text validates integration: Shared constitutional root · trace:ARTICLE_I.rules.vesting
  • amendments validates integration: Operative amendment lineage · trace:normativeRoot.lineage
  • doctrine returns integration: Cross-module dispute · human-review
  • engineering rejects integration: Lineage mismatch · trace:ARTICLE_I.engineering.sourcePreservingLaw
WARDEN matrixIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g06 · authorial brief

The complete test suite follows:

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);
	},
);

All 151 scenarios pass. A cumulative run of Articles IV, III, II, and I passes 387/387 tests. The earlier independent builds for Articles VII, VI, and V contain 4, 10, and 23 scenarios respectively. The series documents 424 successful WARDEN scenarios in total: the current unified runtime battery covers the last four interconnected modules, while the first three preserve their own bootstrap, root-of-trust, and upgrade-protocol test circuits.

The number of tests measures the implemented contract’s scale. It does not measure the Constitution’s justice, the completeness of American law, or the political quality of a particular statute. WARDEN checks program conformity with selected invariants. It can detect an unsupported competence claim, mismatched text, an insufficient threshold, or a foreign root. It receives factual and doctrinal classifications as input and preserves a dispute for a court or editorial audit.

The complete route: from ratification to receipt

The seventh function assembles the full system into one graph:

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["Receipt of execution"]
    H --> F
topologyCumulative architecture of seven articles

Ratification launches a trusted and amendable order; federation, legislation, and adjudication produce sources for bounded execution, and the receipt returns to the resolution circuit.

  • artifact: Article VII · bootstrap
  • artifact: Article VI · root
  • artifact: Article V · amendment
  • artifact: Article IV · federation
  • artifact: Article I · law
  • artifact: Article III · judgment
  • artifact: Article II · execution
  • artifact: Receipt returns to the dispute
  • 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
Cumulative architecture of seven articlesIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g07 · authorial brief

The diagram’s linearity is conventional. The constitutional runtime is a graph of states and feedback loops. A law may organize a court, after which the court hears a dispute about the law. The executive returns a receipt to the court. An amendment changes the root under which all later artifacts operate. A federal conflict creates a case or controversy. Impeachment revokes executive authority and starts succession. Every arrow preserves a source digest, scope, and handoff.

The code achieves five cumulative properties:

  1. Provenance. Every operative object binds to the root and its parent decisions.
  2. Separation of states. A proposal, rule, judgment, order, material act, and receipt are distinct events.
  3. Bounded capability. A component receives a defined operation, purpose, scope, and review route.
  4. Safe failure. Uncertainty or defect creates an observable state and a resolution path rather than silent continuation.
  5. Immutable lineage. Review creates a new object while preserving the history of the original decision.

These properties make the model technically useful. They also expose its cost: more types, digests, journals, intermediate states, checks, and explicit decision owners. A small project can drown in its own constitutional paperwork long before acquiring its first user. The scale of adoption must match the scale of risk.

What Article I gives software architecture

The historical form of Article I transfers into software governance through the following functions:

Article I mechanismInverted functionPossible software form
Legislative Vestingpredefined normmaker and subjectrole profile, ownership, authority register
Two Housesindependent grounds of consentdomain-owner review plus security/legal/data approval by risk
Quorum and journaloperative composition and proof of decisionpolicy quorum, signed decision record, append-only log
One textconsent to an exact revisioncommit SHA, artifact digest, immutable proposal
Presentment and vetoindependent objection and replacementblocking review, objection window, override threshold
Enumerated powerssubject-matter competencebounded authority by domain, repository, environment, and effect
Necessary and Properselection of derivative meansimplementation discretion linked to accepted policy
Appropriationsseparate right over a common resourceauthorization for budget, secrets, production, signing keys, and release
Bill of Attainder / ex post factoseparation of rule and personal responsibilitygeneral rules, proved incident record, separate disciplinary process
Limits on statesautonomy of parts inside common boundarieslocal jurisdiction plus consent for shared contracts and state

The model is strongest in provenance and transitions. Software already consists of formal artifacts, versions, dependencies, journals, roles, and machine checks. The link “exact rule → authority → implementation → observation” is natural to express in code. Constitutional questioning makes hidden power visible: who may change an API, dispose of production, define a security boundary, turn a practice into an obligation, and repeal it.

Institutional analogies are moderately strong. Two Houses are useful as a question about independent consents and often excessive as a literal organizational copy. Presidential signature is useful as an external objection gate and dangerous as a cult of one merge authority. Federation is useful for autonomous jurisdictions and must be adapted to the project’s actual topology.

Automatic determination of meaning is the weakest part. Code can verify a claimed category, threshold, digest, and scope. It has limited ability to decide whether a particular rule is a bill of attainder, whether a means is truly necessary and proper, whether a political question exists, or whether the foundation is just. Those decisions require interpretation, facts, representation, and responsibility. Formalization makes the input visible; it does not abolish the human character of judgment.

Where the entire experiment ends

The model has six main limits.

The first is reduction of the text. Each article of the United States Constitution is surrounded by judicial doctrine, statutes, House and Senate rules, administrative practice, a history of conflict, and unwritten norms. The prototype selects limited invariants and preserves source links. It is not a computable copy of United States constitutional law.

The second is trust in inputs. Fields such as authenticated: true, authorityVerified: true, and constitutionalCompatibilityDetermined: true represent outcomes of external review. A production system would require signatures, schemas, trusted time, logs, separated attestation, and a real challenge process. A Boolean is convenient in a laboratory and carries about the same evidentiary weight as a sign reading “everything verified” on the door of an internal-control department.

The third is WARDEN’s self-reference. The tests are written from a selected interpretation and may flawlessly confirm its implementation. Editorial audit, competing interpretations, and real disputes remain necessary to test the invariants themselves.

The fourth is material power. GitHub permissions, a cloud console, and physical access can bypass normative procedure. Code Constitution creates grounds for accountability, detection, and recovery and needs technical regulators that reduce the room for bypass. Factual ability and normative authority never coincide perfectly, even in a formal system.

The fifth is cost. The full model is justified for a long-lived project with multiple jurisdictions, sensitive data, public commitments, complex delivery, and a high price for irreversible decisions. A local utility benefits from only a few elements: clear ownership, an exact revision, tests, a decision journal, and rollback. The rest of the state apparatus may remain peacefully in Washington.

The sixth is the origin of justice. Procedure explains why a rule binds inside an order. External law, protected rights, the position of affected parties, and the capacity to change a defective foundation determine what that order may govern. The historical slavery provisions make this limit part of the source itself, not a later moral footnote.

Overall assessment of the model

The experiment produced a positive result at the level of normative architecture. All seven articles supplied transferable functions:

  • establishment and scope of an order;
  • identification of a trusted corpus;
  • amendment of the foundational root;
  • relationships among autonomous jurisdictions;
  • production of a general rule;
  • execution and observation of the result;
  • resolution of a concrete dispute.

A software system can express these functions through typed artifacts, states, digests, journals, capabilities, tests, and handoffs. The cumulative prototype demonstrates compatible interfaces and safe failure. It also shows that literal reproduction of American institutions adds needless ceremony and false political subjectivity to components.

Practical adaptation uses functional inversion: a historical rule is first reconstructed as a function and then receives a new subject, actor, scope, evidence, and limit. Congress is not renamed “the maintainer team.” Bicameralism yields independence of consent. The Appropriations Clause yields the difference between access and authority to dispose of a resource. Article III yields a concrete dispute and proved record. Article V yields the distinction between normative change and technical migration. Article VII yields an external founding bootstrap.

This is how Code Constitution was built. It is an independent normative order for software architecture, shaped through study of the United States Constitution and tested by the reverse experiment. The American model survived adaptation as a generator of architectural questions and functional contracts. Its literal institutional shell retains historical, comparative, and artistic value.

Conclusion

In the first publication, the UCA map had only begun to glow. Nine local decisions created the scope of a new order, and WARDEN checked four conditions of launch. In the finale, that map acquired a legislative source, federal links, a court, execution, kernel upgrade, and a common root of trust. The eagle left the bootloader and discovered that production was surrounded by journals, digests, and several independent actors, each capable of saying “no.” In republican architecture, that counts as a sign of health.

Article I completes the model at the source of ordinary law. legislate() proves competence, preserves one text, gathers two independent consents, conducts presentment, issues bounded capabilities, and leaves the result open to adjudication and amendment. The 151 tests confirm implementation of this contract. The series’ 424 scenarios show that seven constitutional functions can form a connected executable laboratory.

The conclusion keeps the promised scale. This series is a popular-science architectural experiment. It neither defeats law nor declares JavaScript a new species of political science. It demonstrates something more useful: software architecture already contains order, authority, boundaries, exceptions, conflicts, and methods of change. Constitutional method lets us name them before custom, emergency access, and one extremely confident maintainer write the actual constitution by themselves.

Continue the research with AI

The site renders this section from the independent question set constitution-runtime.article-i.legislate, stored in the companion catalog constitution-runtime-07-article-i-questions.yaml. Every prompt independently identifies its Article I subject, constitutional, amended, doctrinal, or engineering source, relevant prototype object, and authority boundary, allowing it to operate outside the article’s linear sequence without losing context.

The recommended route is normmaker → independent consents → exact text → presentment → competence → substantive limits → shared resources → impeachment → module interfaces → WARDEN → adaptability → conclusion of seven articles. The bilingual catalog contains the AI answer contract, sixty-one standalone prompts, branch triggers, code and visual references, and return navigation.

navigatorquestion navigator

A conversation route from the provenance of law to the final assessment of the seven-article software adaptation.

  • artifact: Article I
  • state: Normmaker
  • state: Two consents
  • state: One text
  • state: Presentment
  • state: Competence
  • state: Direct prohibitions
  • state: Shared resources
  • state: Impeachment
  • state: Cross-module route
  • state: WARDEN
  • state: Software governance
  • human-decision: Seven-article conclusion
  • 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
question navigatorIRON CREED semantic-core · asset.constitution-runtime-07-article-i.g08 · authorial brief

Publication information

Authors: Sam Starling, Oksana Dubinetska
Project context: Zhovten Games / IRONCREED
Complete research source: Code Constitution — DOI 10.5281/zenodo.21894242
Research repository: FOP-Oksana-Dubinetska/code-constitution
Historical, legal, and technical materials: text of the United States Constitution; Amendments XI–XXVII; overview of Article I; bicameralism; Origination Clause; presidential approval and veto; enumerated powers; Necessary and Proper Clause; Appropriations Clause; Senate impeachment materials; House legislative process
Related publications: “Connect America: How Article VII Bootstraps a Republic”; “What America Trusts: How Article VI Assembles the Supreme Order”; “Update America: How Article V Changes the Constitutional Kernel”; “Link America: How Article IV Turns the States into a Federal Network”; “Adjudicate America: How Article III Turns a Conflict into an Enforceable Judgment”; “Execute America: How Article II Turns a Decision into Action”
Series status: Complete · publication 7 of 7
Publication revision: 0.2 · 13 August 2026