From 55253c48b4f352e03a4490cf8399136b68cd4816 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 04:34:57 +0000 Subject: [PATCH 001/170] Estate-rule sim: stake log_weight follows heimdall-stake's log form, no cliff at unit w = max(0, 1 + log_b(x/unit)); all 14 single and 12 split golden rows now pass. Co-Authored-By: Claude Sonnet 5.5 --- .../2026-11-05-estate-rule-sim/estatesim.py | 9 ++++----- .../2026-11-05-estate-rule-sim/test_estatesim.py | 16 +++++++--------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/docs/research/2026-11-05-estate-rule-sim/estatesim.py b/docs/research/2026-11-05-estate-rule-sim/estatesim.py index eba9812..d4693bc 100644 --- a/docs/research/2026-11-05-estate-rule-sim/estatesim.py +++ b/docs/research/2026-11-05-estate-rule-sim/estatesim.py @@ -471,18 +471,17 @@ def stake_params(name, overrides=()): def log_weight(x, b, unit): - """w = 1 + log_b(x/unit): 1 at x = unit, 0 (not negative) below unit. + """w = max(0, 1 + log_b(x/unit)): 1 at x = unit, continuous below it, 0 (not negative) once x <= unit/b. - Equals CultLib heimdall-stake `weight` with floor 0, cap None and min_amount_per_identity = unit, which - is the cliff at unit; Libby's continuous log below unit is not used. Pinned to her golden vectors by - test_estatesim.StakeVectors (vectors/stake_golden.csv). + Equals CultLib heimdall-stake `weight` (PR #9, 84f932ec) with floor 0, cap None and no minimum: no cliff + at unit. Pinned to its golden vectors by test_estatesim.StakeVectors (vectors/stake_golden.csv). This is the weight of ONE IDENTITY. It is not sybil-safe: log is sub-linear, so the same x split over k identities weighs more (split_weight). Whether the log bounds a purchase depends on identities being scarce, which nothing in this module supplies. b and unit are PLACEHOLDER values (STAKE_BASE).""" if b <= 1 or unit <= 0: raise ValueError("log base must exceed 1 and unit must be positive") - return 0.0 if x < unit else 1.0 + math.log(x / unit, b) + return max(0.0, 1.0 + math.log(x / unit, b)) if x > 0 else 0.0 def stake_weight(name, euros=0.0, hours=0.0, overrides=()): diff --git a/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py b/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py index 3fb0d9f..c4e9dd0 100644 --- a/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py +++ b/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py @@ -297,7 +297,8 @@ class StakeTests(unittest.TestCase): c = self.cfg() b, u = c["euro_b"], c["euro_unit"] self.assertEqual(E.log_weight(u, b, u), 1.0) - self.assertEqual(E.log_weight(u * .99, b, u), 0.0) # below unit: no weight, not negative + self.assertAlmostEqual(E.log_weight(u / 2, b, u), 1 + math.log(.5, b)) # below unit: continuous, no cliff + self.assertEqual(E.log_weight(u / b ** 2, b, u), 0.0) # clamped at 0, never negative self.assertAlmostEqual(E.log_weight(u * b ** 3, b, u), 4.0) # each factor b adds one self.assertLess(E.log_weight(10 * u, b, u), 10) # sub-linear @@ -359,7 +360,9 @@ class StakeTests(unittest.TestCase): self.assertAlmostEqual(each, 1 + math.log(a / (k * u), b)) self.assertAlmostEqual(tot, k * (1 + math.log(a / (k * u), b))) self.assertGreater(tot, E.log_weight(a, b, u)) - self.assertEqual(E.split_weight(a, int(a / u) + 1, b, u)[0], 0.0) # every fake below unit: nothing + kk = int(a / u) + 1 # every fake just below unit: still ~1 each, no cliff + self.assertAlmostEqual(E.split_weight(a, kk, b, u)[0], kk * (1 + math.log(a / (kk * u), b))) + self.assertGreater(E.split_weight(a, kk, b, u)[0], 0.99 * a / u) best, bk = E.best_split(a, b, u) self.assertGreaterEqual(best, tot) self.assertAlmostEqual(best, a / u) # b > e: best is k = a/unit, weight 1 each @@ -509,9 +512,8 @@ class HarnessTests(unittest.TestCase): class StakeVectors(unittest.TestCase): """Pins the arm's log_weight / split_weight to CultLib heimdall-stake's golden vectors (PR #9, head 84f932ec, - copied unmodified to vectors/stake_golden.csv). The arm is Libby's function with min_amount_per_identity = unit, - so rows at or above the unit must match; a row below the unit must be 0 in the arm (the cliff) while the - vectors, which set no minimum, give the continuous value. Vectors are integer cents and micro-weights, the + copied unmodified to vectors/stake_golden.csv). The arm is Libby's function with no minimum, + and every row (14 single, 12 split) must match, including those below the unit: no cliff. Vectors are integer cents and micro-weights, the arm is float and unit-agnostic: tolerance is 1 micro-weight per identity (Libby rounds each identity, the arm the total).""" @staticmethod @@ -528,12 +530,8 @@ class StakeVectors(unittest.TestCase): with self.subTest(kind=kind, b=b, unit=u, amount=a, k=k): if kind == "single": got = E.log_weight(a, b, u) * 1e6 - if a < u: - self.assertEqual(got, 0.0) # arm's cliff = min_amount_per_identity = unit - continue else: got = E.split_weight(a, k, b, u)[0] * 1e6 - self.assertGreaterEqual(a // k, u) # every split row keeps each identity at or above unit self.assertLessEqual(abs(got - expected), max(1, k)) From b6c1e9af7373287190d330108a72cf5c0089efc7 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 07:50:04 +0000 Subject: [PATCH 002/170] Estate-rule sim: regenerate results.md and fix stale half-cap numbers and the "0 below unit" wording REPORT.md E6 and results.md still held pre-fix numbers (half-cap 0.044/0.222, s max 0.953). Regenerated with the current sim: s max 0.777; half-cap binding all four 0.000, Patrons+Minds 0.008, Patrons alone 0.165. Weight is 0 only at amount <= unit/b (run.py, REPORT.md, SPEC.md); the splitting table no longer prints a cliff "0 (below unit)". Test count 54. Co-Authored-By: Claude Sonnet 5.5 --- .../2026-11-05-estate-rule-sim/REPORT.md | 8 ++++---- docs/research/2026-11-05-estate-rule-sim/SPEC.md | 2 +- .../2026-11-05-estate-rule-sim/results.md | 16 ++++++++-------- docs/research/2026-11-05-estate-rule-sim/run.py | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/research/2026-11-05-estate-rule-sim/REPORT.md b/docs/research/2026-11-05-estate-rule-sim/REPORT.md index a5f9440..1813dcb 100644 --- a/docs/research/2026-11-05-estate-rule-sim/REPORT.md +++ b/docs/research/2026-11-05-estate-rule-sim/REPORT.md @@ -1,6 +1,6 @@ # Estate-rule sim: report (2026-11-05) -Question: does the unified estate rule (estate votes decide the estate's vote) dampen populism? Spec: `SPEC.md` (written first, four revisions, each before the results it affects). Numbers: `results.md` (235 cells, 40 replicates x 500 motions each, paired draws). Rerun: `python3 -I run.py` (about 11 minutes on 8 jobs; `--quick` for a smoke; `python3 -I test_estatesim.py` for the 52 tests). Output is byte-identical across reruns and across `--jobs` values. +Question: does the unified estate rule (estate votes decide the estate's vote) dampen populism? Spec: `SPEC.md` (written first, four revisions, each before the results it affects). Numbers: `results.md` (235 cells, 40 replicates x 500 motions each, paired draws). Rerun: `python3 -I run.py` (about 11 minutes on 8 jobs; `--quick` for a smoke; `python3 -I test_estatesim.py` for the 54 tests). Output is byte-identical across reruns and across `--jobs` values. ## Answer @@ -41,13 +41,13 @@ Limits specific to this result: copying is triggered only when the holder is ove ## Purchased stake (E6, SPEC section 5c) -Static weight analysis, not a motion simulation: it measures weight share, not PS or MT. Weight w = 1 + log_b(amount/unit), 0 below unit, per-estate b and unit (defaults b = 10, unit = 10 EUR, my choices, in SPEC 5c). The harness had no contribution mechanism, so contribution hours are a new per-agent input with their own per-estate conversion (defaults b = 10, unit = 10 hours); they add to the euro weight and matter to no buyer result below. +Static weight analysis, not a motion simulation: it measures weight share, not PS or MT. Weight w = 1 + log_b(amount/unit), 0 at amount <= unit/b, per-estate b and unit (defaults b = 10, unit = 10 EUR, my choices, in SPEC 5c). The harness had no contribution mechanism, so contribution hours are a new per-agent input with their own per-estate conversion (defaults b = 10, unit = 10 hours); they add to the euro weight and matter to no buyer result below. **The working hypothesis, that logarithmic weight bounds buyout power, is only half true here, and the true half is not the log's doing.** -- **Within the estate the log does not bound a million-euro buyer.** Against the harness's 4-patron roll (Pareto(1.16) donations from 10 EUR, 40 seeds) the buyer holds 0.524 +/- 0.008 of Patrons weight and alone decides the Patrons estate (share above one half) in 85% of seeds. The log shrinks the buyer from 100% (linear weight) to about half; it does not take it below a majority of a 4-person estate. This is the harness's own cell (roll 4, unit 10 EUR, b = 10), not a typical one. Swept over unit {1, 10, 100} EUR and roll {4, 40, 400} (40 seeds each, table in results.md) the buyer's mean share of Patrons weight runs from 0.007 to 0.953, and the buyer alone decides the estate in 0 to 100% of seeds depending on the cell (0.85 at the headline cell, 0.65 at roll 40 with unit 100, 1.00 at roll 4 with unit 100, 0.00 in the other six). The roll size, Pareto scale and unit are placeholders; the interval, not the point, is the finding. The weight is per identity, so all of this assumes one identity per buyer (next bullet). +- **Within the estate the log does not bound a million-euro buyer.** Against the harness's 4-patron roll (Pareto(1.16) donations from 10 EUR, 40 seeds) the buyer holds 0.524 +/- 0.008 of Patrons weight and alone decides the Patrons estate (share above one half) in 85% of seeds. The log shrinks the buyer from 100% (linear weight) to about half; it does not take it below a majority of a 4-person estate. This is the harness's own cell (roll 4, unit 10 EUR, b = 10), not a typical one. Swept over unit {1, 10, 100} EUR and roll {4, 40, 400} (40 seeds each, table in results.md) the buyer's mean share of Patrons weight runs from 0.007 to 0.777, and the buyer alone decides the estate in 0 to 100% of seeds depending on the cell (0.85 at the headline cell, 1.00 at roll 4 with unit 100, 0.00 in the other seven). The roll size, Pareto scale and unit are placeholders; the interval, not the point, is the finding. The weight is per identity, so all of this assumes one identity per buyer (next bullet). - **At council level the bound comes from the estate weights.** With all four estates live the buyer's council share is 0.131 (equal weights) or 0.052 (minds-heavy), below the Patrons weight W_Patrons by construction; the half-influence cap never binds in 6,480 cell-seeds. Linear weight would give 0.25 and 0.10: the log halves the buyer's share, the estate structure sets its ceiling. -- **The half-influence cap binds only when other estates are silent.** Fraction of (cell, seed) in which council share x >= .5 over 162 cells (b x unit x roll x amount x weights) x 40 seeds: all four live 0.000; Patrons + Minds live 0.044 (all of it the degenerate case where no other patron clears the unit, so there is nothing to cut against: unenforceable); Patrons alone live 0.222 (0.148 of cells bind in every seed, 0.089 of cell-seeds unenforceable). It binds more at small rolls (Patrons alone: 0.669 at roll 4 and b = 2 down to 0.000 at roll 400) and with a smaller log base. The Patrons-alone scenario is the renormalization case of prior section 10 (drop non-voting estates); how likely it is in practice is not a sim output. +- **The half-influence cap binds only when other estates are silent.** Fraction of (cell, seed) in which council share x >= .5 over 162 cells (b x unit x roll x amount x weights) x 40 seeds: all four live 0.000; Patrons + Minds live 0.008 (all of it the degenerate case where no other patron clears the unit, so there is nothing to cut against: unenforceable); Patrons alone live 0.165 (0.099 of cells bind in every seed, 0.017 of cell-seeds unenforceable). It binds more at small rolls (Patrons alone: 0.669 at roll 4 and b = 2 down to 0.000 at roll 400) and with a smaller log base. The Patrons-alone scenario is the renormalization case of prior section 10 (drop non-voting estates); how likely it is in practice is not a sim output. - **Splitting wins, by orders of magnitude.** The same 1,000,000 EUR over k identities multiplies weight by 1.9 (k = 2), 8.3 (k = 10), 66.7 (k = 100), 500 (k = 1000), and 16,667 at k = amount/unit = 100,000 (each fake identity buying exactly the unit). The multiplier is (amount/unit) / (1 + log_b(amount/unit)); for b = 10, unit = 10 it is 250 at 10,000 EUR, 2,000 at 100,000 EUR. With k = 10 fake identities the buyer's Patrons-alone share is 0.901, with k = 2 it is 0.676. This refutes the log as a purchase bound unless identities are scarce. - **The half-influence cap is per identity and splitting evades it.** In the Patrons-alone case the single identity trips the cap in 85% of seeds; at k = 2 no identity does (each holds 0.34) while the joint share is 0.676, in every seed. A cap on a person's influence needs an identity oracle the harness does not have. - **SPEC names no sybil defence** (the charter's frozen roll, A6, bounds joins after notice, not pre-notice buying of identities), so none is implemented as policy. Three candidates are quantified in results.md and none is chosen: a per-person weight cap does not help (it caps the honest single purchase and the fakes are each below it; 100,000x at cap 1); a raised unit floor reduces the multiplier (250 at 1,000 EUR, 5 at 100,000 EUR, 1.0 only at 1,000,000 EUR, where no purchase under the buyer's amount buys any weight), so it neutralises splitting only by pricing out everyone smaller; a per-identity cost neutralises only at about half the budget (bisection values 49.3%, 49.8%, 49.95% of 10,000, 100,000, 1,000,000 EUR; the threshold is c = amount/2, where a second identity is left with nothing to buy), so it would also tax the honest buyer's single identity at that rate. The choice between pricing identities, verifying people or bounding total weight per verified person is a design fork left for the operator. Nothing here rules it. diff --git a/docs/research/2026-11-05-estate-rule-sim/SPEC.md b/docs/research/2026-11-05-estate-rule-sim/SPEC.md index 4978cd7..687a6db 100644 --- a/docs/research/2026-11-05-estate-rule-sim/SPEC.md +++ b/docs/research/2026-11-05-estate-rule-sim/SPEC.md @@ -95,7 +95,7 @@ Serves `heimdall-body:follow_up:chat-s1946-1946`. Serves the purchased-stake brief (operator relayed: Patron vote power is logarithmic in donation, prior section 4; operator influence strictly below half, ruling `operator-influence-below-half`, prior section 10). Not a motion simulation: a static weight analysis, so it measures weight share and decisiveness, not PS or MT. -**Weight.** A purchase of `amount` EUR weighs w = 1 + log_b(amount/unit): 1 at amount = unit, 0 below unit (below the unit buys no weight, never negative). Each estate has its own conversion, set through `Config.overrides` entries `(estate, key, value)` with keys `euro_b`, `euro_unit`, `hours_b`, `hours_unit` (defaults in `STAKE_BASE`). Only Patrons (euros) and Members (hours) carry stake; Minds are counted once and Users are one-each, so both weigh 1. +**Weight.** A purchase of `amount` EUR weighs w = 1 + log_b(amount/unit): 1 at amount = unit, continuous below it, 0 at amount <= unit/b (never negative). Each estate has its own conversion, set through `Config.overrides` entries `(estate, key, value)` with keys `euro_b`, `euro_unit`, `hours_b`, `hours_unit` (defaults in `STAKE_BASE`). Only Patrons (euros) and Members (hours) carry stake; Minds are counted once and Users are one-each, so both weigh 1. **Defaults chosen (assumptions, not rulings; the brief gave none).** Patrons and Members alike: euro b = 10, unit = 10 EUR; hours b = 10, unit = 10 hours. b = 10 reads as "each tenfold purchase adds one vote of weight", the simplest reading of the operator's "logarithmic"; 10 EUR is the smallest ordinary Patron donation in the prior ladder (prior section 4: 10, 50, 200, 5000); 10 hours is roughly a working day or so of contribution. The sweep varies b over {2, 10, 100} and unit over {1, 10, 100} EUR; hours are not swept because no buyer outcome depends on them (see below). diff --git a/docs/research/2026-11-05-estate-rule-sim/results.md b/docs/research/2026-11-05-estate-rule-sim/results.md index 99fcf43..cd14773 100644 --- a/docs/research/2026-11-05-estate-rule-sim/results.md +++ b/docs/research/2026-11-05-estate-rule-sim/results.md @@ -793,7 +793,7 @@ PS by category threshold: ## E6 purchased stake: logarithmic weight, splitting, and the half-influence cap (SPEC section 5c) -Static weight analysis (no motions are simulated, so no PS or MT): a buyer joins the Patrons estate with one purchase; the 4-patron roll of the harness (and 40, 400) holds Pareto(1.16) donations from 10 EUR, 40 seeds each. Weight w = 1 + log_b(amount/unit), 0 below unit; defaults b = 10, unit = 10 EUR. Share s is the buyer's share of Patrons weight; x is its share of council weight (estate weight W x s over the live estates' weights); the cap binds iff x >= .5. +Static weight analysis (no motions are simulated, so no PS or MT): a buyer joins the Patrons estate with one purchase; the 4-patron roll of the harness (and 40, 400) holds Pareto(1.16) donations from 10 EUR, 40 seeds each. Weight w = 1 + log_b(amount/unit), 0 at amount <= unit/b; defaults b = 10, unit = 10 EUR. Share s is the buyer's share of Patrons weight; x is its share of council weight (estate weight W x s over the live estates' weights); the cap binds iff x >= .5. **Million-euro buyer, defaults, Patrons roll 4 (mean over seeds, 95% interval); linear = weight proportional to amount, the counterfactual the log is meant to beat** @@ -812,24 +812,24 @@ Static weight analysis (no motions are simulated, so no PS or MT): a buyer joins |---|---|---|---| | 1 | 0.425 ±0.005 (0.00) | 0.069 ±0.000 (0.00) | 0.007 ±0.000 (0.00) | | 10 | 0.524 ±0.008 (0.85) | 0.098 ±0.001 (0.00) | 0.011 ±0.000 (0.00) | -| 100 | 0.953 ±0.028 (1.00) | 0.579 ±0.040 (0.65) | 0.118 ±0.004 (0.00) | +| 100 | 0.777 ±0.023 (1.00) | 0.251 ±0.008 (0.00) | 0.032 ±0.000 (0.00) | -Interval over the swept cells: s from 0.007 to 0.953. The 0.524 headline is the harness's own cell (roll 4, unit 10), not a typical one: the buyer's majority of the estate depends on how few other patrons there are. +Interval over the swept cells: s from 0.007 to 0.777. The 0.524 headline is the harness's own cell (roll 4, unit 10), not a typical one: the buyer's majority of the estate depends on how few other patrons there are. **Cap-binding rate over the sweep (b, unit, roll, amount, weights x live set; every cell run on every seed)** | live estates | cells | cells x seeds | binding (cell, seed) | cells binding in every seed | cells never binding | binding but unenforceable | |---|---|---|---|---|---|---| | all four estates | 162 | 6480 | 0.000 | 0.000 | 1.000 | 0.000 | -| Patrons + Minds | 162 | 6480 | 0.044 | 0.000 | 0.889 | 0.044 | -| Patrons alone | 162 | 6480 | 0.222 | 0.148 | 0.704 | 0.089 | +| Patrons + Minds | 162 | 6480 | 0.008 | 0.000 | 0.981 | 0.008 | +| Patrons alone | 162 | 6480 | 0.165 | 0.099 | 0.790 | 0.017 | Binding rate in the Patrons-alone scenario by Patrons roll and by log base (fraction of cells x seeds): | roll | b=2 | b=10 | b=100 | |---|---|---|---| -| 4 | 0.669 | 0.447 | 0.333 | -| 40 | 0.286 | 0.169 | 0.094 | +| 4 | 0.669 | 0.447 | 0.114 | +| 40 | 0.250 | 0.000 | 0.000 | | 400 | 0.000 | 0.000 | 0.000 | **Splitting: the same total split over k identities (defaults, one honest identity = k 1). Multiplier = total weight of the split / weight of the single purchase** @@ -877,7 +877,7 @@ Best multiplier at 1,000,000 EUR by log base and unit (b rows, unit columns): | hours | 5 | 10 | 100 | 1000 | 10000 | |---|---|---|---|---|---| -| weight | 0.00 | 1.00 | 2.00 | 3.00 | 4.00 | +| weight | 0.70 | 1.00 | 2.00 | 3.00 | 4.00 | ## Claim tally over all cells (SPEC section 8) diff --git a/docs/research/2026-11-05-estate-rule-sim/run.py b/docs/research/2026-11-05-estate-rule-sim/run.py index d20efd8..cc3755f 100644 --- a/docs/research/2026-11-05-estate-rule-sim/run.py +++ b/docs/research/2026-11-05-estate-rule-sim/run.py @@ -228,7 +228,7 @@ def stake_section(quick): L = ["## E6 purchased stake: logarithmic weight, splitting, and the half-influence cap (SPEC section 5c)", "", "Static weight analysis (no motions are simulated, so no PS or MT): a buyer joins the Patrons estate with one purchase; " f"the {E.ROLL['Patrons']}-patron roll of the harness (and 40, 400) holds Pareto({E.PARETO_ALPHA}) donations from {E.PARETO_XM:.0f} EUR, " - f"{seeds} seeds each. Weight w = 1 + log_b(amount/unit), 0 below unit; defaults b = {E.STAKE_BASE['Patrons']['euro_b']:.0f}, " + f"{seeds} seeds each. Weight w = 1 + log_b(amount/unit), 0 at amount <= unit/b; defaults b = {E.STAKE_BASE['Patrons']['euro_b']:.0f}, " f"unit = {E.STAKE_BASE['Patrons']['euro_unit']:.0f} EUR. Share s is the buyer's share of Patrons weight; x is its share of council weight " "(estate weight W x s over the live estates' weights); the cap binds iff x >= .5.", ""] ladders = {(n, s): E.stake_ladder(n, s) for n in rolls for s in range(seeds)} @@ -306,7 +306,7 @@ def stake_section(quick): w1 = E.log_weight(a, b0, u0) bt, bk = E.best_split(a, b0, u0) L.append(f"| {a:g} | {w1:.2f} | " + " | ".join( - f"{E.split_weight(a, k, b0, u0)[0] / w1:.1f}" if a / k >= u0 else "0 (below unit)" for k in (2, 10, 100, 1000)) + + f"{E.split_weight(a, k, b0, u0)[0] / w1:.1f}" for k in (2, 10, 100, 1000)) + f" | {bk} | {bt / w1:.0f} |") L += ["", "Best multiplier at 1,000,000 EUR by log base and unit (b rows, unit columns):", "", "| b | " + " | ".join(f"unit={u:g}" for u in units) + " |", "|---|" + "---|" * len(units)] From d6c96fe1a16ec62df3908ab18cdc2c40b28968e1 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 15:54:56 +0000 Subject: [PATCH 003/170] Estate-rule sim: contribution-credit arm (E7) Linear per-person credit with a per-person cap, one standard for all including a Meta-sized contributor, measured against the existing tally and half-influence cap across contributor-share levels and splitting k=2/10/100. Credit is not vote weight; analysis only. Co-Authored-By: Claude Sonnet 5.5 --- .../2026-11-05-estate-rule-sim/REPORT.md | 11 +++ .../2026-11-05-estate-rule-sim/SPEC.md | 17 +++++ .../2026-11-05-estate-rule-sim/estatesim.py | 48 +++++++++++++ .../2026-11-05-estate-rule-sim/results.md | 68 +++++++++++++++++++ .../2026-11-05-estate-rule-sim/run.py | 68 +++++++++++++++++++ .../test_estatesim.py | 61 +++++++++++++++++ 6 files changed, 273 insertions(+) diff --git a/docs/research/2026-11-05-estate-rule-sim/REPORT.md b/docs/research/2026-11-05-estate-rule-sim/REPORT.md index 1813dcb..d773d4a 100644 --- a/docs/research/2026-11-05-estate-rule-sim/REPORT.md +++ b/docs/research/2026-11-05-estate-rule-sim/REPORT.md @@ -54,6 +54,17 @@ Static weight analysis, not a motion simulation: it measures weight share, not P Limits specific to E6: the roll, the Pareto scale, b and unit are assumptions; the buyer joins as an additional patron and buys once (no repeated purchase or liquidation); decisiveness is estate-level only, not council-level (prior section 10 shows weight share is not decisiveness); the best split is a grid maximum, a lower bound; hours play no part in a purchase scenario because estate weights are fixed and the buyer sits in Patrons, so an hours buyer (a Member who is paid or who farms hours) is untested and the conversion of hours into weight is just a per-estate parameter whose gaming is not modeled. +## E7: contribution-weighted arm (SPEC section 5d) + +Static weight analysis, not a motion simulation, and not a proposal: credit does not become vote weight here. Credit is linear in receipts (hours or credited changes), tallied per person, weight = min(credit, per-person cap), one function for a Meta-sized contributor and an ordinary member alike. Tally and half cap are E6's. Contributor share phi is the fraction of the Members estate's total raw credit; roll 15 and 150 ordinary members, 40 seeds, both estate-weight sets. + +- **The half cap binds only when Members are the only live estate, and then it is a step at phi = .5.** All four estates live: 0 binding in every cell. Members + Minds live: 0 (the Members estate carries at most half the council, so the strict cap is never reached). Members alone: 0 for phi <= .4, and for phi >= .5 with no credit cap 1.000, because a contributor at exactly half of the credit has exactly half the estate (the cap is "strictly below"). The rate does not rise past phi = .5 because the cap binds as a yes/no, not by degree. +- **A per-person credit cap moves that step, it does not remove it.** Members alone, phi >= .5, rate of binding at 100x / 20x / 5x the ordinary median credit: 0.438 / 0.075 / 0.000 (pooled over both rolls and weights, 320 trials each). The bound is the cap against the size of the ordinary roll: 5x the median holds a contributor under half of a 15-member estate, which says the cap is doing the work the half cap would do, at the price of flattening every member above 5x median. +- **Splitting evades the half cap in every case it needed to act.** Members alone, over the whole sweep, k = 2, 10, 100: the joint share reaches .5 in 5,942 cases and in 5,942 no single identity binds (1.000). Uncapped linear credit makes splitting weight-neutral (multiplier 1.00) but still evades the per-identity half cap. With a per-person credit cap splitting also multiplies weight: at phi .9, k = 10, the multiplier is 3.58 at 100x, 9.66 at 20x, 10.00 at 5x (cap bites hardest on the single identity); k = 100: 6.50 / 21.58 / 59.10. +- **Falsifiers (SPEC 5d).** (1) A credit cap contains phi .9 with half cap never binding: only at 5x median; false at 100x and 20x. (2) Credit cap survives splitting at multiplier <= 1.1 at k = 10: false in every capped row (1.23 at phi .25 with a 100x cap up to 10.00). (3) Half cap evaded under splitting: true in all 5,942. + +Limits: Pareto credit curve and its scale, the multiples of median, the Members placement, and the rolls are placeholders. A person-level cap needs an identity oracle (as E6); credit tied to merged receipts could provide one, which this sim does not test. Receipts are not audited for farming or purchase (hours-farming is the E6 hours gap, still unanalysed). Ordinary members' own credit is capped too, which matters only at 5x. + ## Robustness (E5, E5b) The sign of the PS effect holds across Users appeal 0.4/0.9/1.4, Users turnout .05/.10/.30 and Minds shared taste .3/.9/1.5. Its size scales with Users appeal loading (-0.025 at .4, -0.067 at 1.4): the rule helps in proportion to how appeal-driven the Users estate is, while its merit loss does not go away (MT gap -0.101 at .4 vs -0.063 at 1.4). If Users are not appeal-driven the rule is nearly all cost. diff --git a/docs/research/2026-11-05-estate-rule-sim/SPEC.md b/docs/research/2026-11-05-estate-rule-sim/SPEC.md index 687a6db..bb39cd8 100644 --- a/docs/research/2026-11-05-estate-rule-sim/SPEC.md +++ b/docs/research/2026-11-05-estate-rule-sim/SPEC.md @@ -111,6 +111,22 @@ Serves the purchased-stake brief (operator relayed: Patron vote power is logarit **Falsifiers fixed in advance.** (1) Working hypothesis "logarithmic weight bounds buyout power": refuted if a one-million-euro buyer's within-estate share s exceeds 1/2 at the harness's own roll, or if splitting multiplies weight by more than 2 at any k. (2) The half-influence cap is "binding" in a (cell, seed) iff x >= .5; the rate over the sweep is reported per live-estate scenario. (3) The cap is "evaded" by splitting iff the joint share is >= .5 while no single identity's share is. +## 5d. Contribution credit (revision 6, written before its results) + +Serves `heimdall-body:follow_up:chat-mind-20261106T134754647Z-t14`. A static weight analysis like 5c, for a contribution-weighted arm. It informs Meta's later call and decides nothing: credit does not become vote weight, here or in any rule above. + +**Credit.** A person's credit is the sum of their receipts (hours, or credited changes counted in the same linear unit), tallied per person. Weight is `min(credit, cap)`: linear, one function for every person, so a Meta-sized contributor is the same row of the same table as an ordinary member, with no exemption and no separate schedule. The per-person cap is a multiple of the ordinary members' median credit, swept over none, 100x, 20x, 5x (assumptions, not rulings). + +**Contributor share.** The contributor holds a fraction phi of the estate's total raw credit (before capping), swept over .05 to .9. This is the "Meta-sized" axis. Placement is the Members estate (where 5c's hours channel lives), a PLACEHOLDER. + +**Electorate.** 15 (the harness roll) and 150 ordinary members with Pareto(1.16) credit from 10 (prior section 4's contribution curve; the scale is mine), 40 seeds each, estate weights and live-estate scenarios as 5c. + +**Same tally, same half cap.** `council_share` and `influence_cap` of 5c, unchanged: binds iff council weight share x >= .5. + +**Splitting.** The contributor's credit split evenly over k = 2, 10, 100 identities. Reported per identity (binds), jointly (joint share >= .5) and as evasion (joint >= .5 with no identity binding), plus the weight multiplier against k = 1. With no credit cap, linear credit makes splitting weight-neutral; with a per-person cap it is not. + +**Falsifiers fixed in advance.** (1) Per-person credit cap "contains" a large contributor if the half cap never binds at phi .9 with a cap in force in the Members-alone scenario. (2) Credit cap "survives splitting" if the weight multiplier at k = 10 is at most 1.1 with a cap in force. (3) The half cap is evaded under splitting if joint x >= .5 with no identity binding. + ## 6. Strategic and adaptive agents A fraction ρ = .25 of ballot holders and of absent undelegated roll members are strategic. Each is myopic about the motion at hand and best-responds to everyone else's current ballots over three rounds in random order: @@ -136,6 +152,7 @@ Paired across rules: one set of random draws per motion feeds all rules (common - **E3f copy-the-ballot:** section 5b. - **E4 appeal attraction:** β sweep at α = 1.5, c = .2. - **E6 purchased stake:** section 5c. b x unit x Patrons roll x amount x estate weights x live-estate scenario, 40 seeds; splitting k sweep; candidate defences. +- **E7 contribution credit:** section 5d. phi x credit cap x roll x weights x live set x seeds; splitting k. - **E5 robustness:** Users appeal loading b ∈ {.4, .9, 1.4}; Users base turnout {.05, .10, .30}; Minds ICC (s_Minds ∈ {.3, .9, 1.5}). This is the check on the assumed parameters in section 4. ## 8. Pre-registered falsifiers diff --git a/docs/research/2026-11-05-estate-rule-sim/estatesim.py b/docs/research/2026-11-05-estate-rule-sim/estatesim.py index d4693bc..f0e5946 100644 --- a/docs/research/2026-11-05-estate-rule-sim/estatesim.py +++ b/docs/research/2026-11-05-estate-rule-sim/estatesim.py @@ -580,3 +580,51 @@ def buyer_runs(amount, n, seeds, W, live, overrides=()): wb = stake_weight("Patrons", euros=amount, overrides=overrides) return [influence_cap(wb, sum(stake_weight("Patrons", euros=x, overrides=overrides) for x in stake_ladder(n, s)), W, ESTATES.index("Patrons"), live) for s in range(seeds)] + + +# ---------------------------------------------------------------- contribution credit (SPEC section 5d) +# +# Credit is tallied per person from receipts (hours or credited changes, one linear unit each) and capped per +# person. The tally and the half-influence cap are the ones above (council_share, influence_cap). Credit is +# measured here as a candidate weight source only; this module never turns it into a vote. + +CREDIT_SEED = 20261106 +CREDIT_ESTATE = "Members" # PLACEHOLDER: where contribution credit would weigh; the hours channel above lives here + + +def credit_weight(credit, cap=None): + """One person's weight from credit: linear in receipts, min(credit, cap). One function for every person, + a Meta-sized contributor included; there is no per-person exemption or schedule.""" + return credit if cap is None else min(credit, cap) + + +def credit_ladder(n, s): + """Seed s's n ordinary members' credit (hours): Pareto(PARETO_ALPHA) from PARETO_XM (prior section 4's + contribution curve; the scale is PLACEHOLDER).""" + return pareto_ladder(n, random.Random(CREDIT_SEED + 1000 * n + s)) + + +def credit_cap_value(ladder, mult): + """Per-person cap as a multiple of the ordinary members' median credit (None = no cap).""" + if mult is None: + return None + xs = sorted(ladder) + return mult * xs[len(xs) // 2] + + +def credit_run(phi, n, s, W, live, cap_mult=None, k=1): + """Half-cap result for a contributor holding fraction `phi` of the estate's TOTAL raw credit, against n + ordinary members (seed s), the credit split evenly over k identities. Returns dict: the usual + influence_cap fields for ONE identity (`one`), the joint share (`joint_x`), `evaded` iff the joint + council share is >= HALF while no identity's is, and `w_total`.""" + e = ESTATES.index(CREDIT_ESTATE) + lad = credit_ladder(n, s) + cap = credit_cap_value(lad, cap_mult) + rest = sum(credit_weight(x, cap) for x in lad) + big = phi / (1 - phi) * sum(lad) + wi = credit_weight(big / k, cap) + tot = k * wi + one = influence_cap(wi, rest + tot - wi, W, e, live) + joint = council_share(tot, rest, W, e, live)[1] + return dict(one=one, joint_x=joint, binds=one["binds"], joint_binds=joint >= HALF - EPS, + evaded=joint >= HALF - EPS and not one["binds"], w_total=tot, rest=rest, cap=cap) diff --git a/docs/research/2026-11-05-estate-rule-sim/results.md b/docs/research/2026-11-05-estate-rule-sim/results.md index cd14773..67e1039 100644 --- a/docs/research/2026-11-05-estate-rule-sim/results.md +++ b/docs/research/2026-11-05-estate-rule-sim/results.md @@ -879,6 +879,74 @@ Best multiplier at 1,000,000 EUR by log base and unit (b rows, unit columns): |---|---|---|---|---|---| | weight | 0.70 | 1.00 | 2.00 | 3.00 | 4.00 | +## E7 contribution-weighted arm: linear credit, per-person cap, the half-influence cap (SPEC section 5d) + +Static weight analysis. One contributor holds a fraction phi of the Members estate's total raw credit (receipts: hours or credited changes, one linear unit); 15 and 150 ordinary members hold Pareto(1.16) credit from 10, 40 seeds each. Weight = min(credit, per-person cap), the same function for the contributor and everyone else. The tally and the half cap are E6's: council share x = W x s over the live estates; the cap binds iff x >= .5. Credit is not vote weight anywhere in this module; this table only says how often the half cap would have to act. + +**Half cap binds, all four estates: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1** + +| phi | none | 100x median | 20x median | 5x median | +|---|---|---|---|---| +| 0.05 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.1 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.25 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.4 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.5 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.6 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.75 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.9 | 0.000 | 0.000 | 0.000 | 0.000 | + +**Half cap binds, Members + Minds: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1** + +| phi | none | 100x median | 20x median | 5x median | +|---|---|---|---|---| +| 0.05 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.1 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.25 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.4 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.5 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.6 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.75 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.9 | 0.000 | 0.000 | 0.000 | 0.000 | + +**Half cap binds, Members alone: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1** + +| phi | none | 100x median | 20x median | 5x median | +|---|---|---|---|---| +| 0.05 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.1 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.25 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.4 | 0.000 | 0.000 | 0.000 | 0.000 | +| 0.5 | 1.000 | 0.438 | 0.075 | 0.000 | +| 0.6 | 1.000 | 0.438 | 0.075 | 0.000 | +| 0.75 | 1.000 | 0.438 | 0.075 | 0.000 | +| 0.9 | 1.000 | 0.438 | 0.075 | 0.000 | + +**Splitting: the contributor's credit split evenly over k identities. Members alone, equal weights, roll 15, mean over seeds. binds = the half cap acts on an identity; joint >= .5 = the combined share would have needed cutting; evaded = joint >= .5 and no identity binds; weight x = total weight / weight at k = 1** + +| phi | cap | k=1: binds / joint>=.5 / evaded / weight x | k=2: binds / joint>=.5 / evaded / weight x | k=10: binds / joint>=.5 / evaded / weight x | k=100: binds / joint>=.5 / evaded / weight x | +|---|---|---|---|---|---| +| 0.25 | none | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.00 | +| 0.25 | 100x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.03 / 0.03 / 1.03 | 0.00 / 0.03 / 0.03 / 1.23 | 0.00 / 0.03 / 0.03 / 1.25 | +| 0.25 | 20x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.03 / 0.03 / 1.12 | 0.00 / 0.07 / 0.07 / 1.43 | 0.00 / 0.07 / 0.07 / 2.55 | +| 0.25 | 5x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 1.75 | 0.00 / 0.12 / 0.12 / 2.87 | 0.00 / 0.12 / 0.12 / 5.46 | +| 0.5 | none | 1.00 / 1.00 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | +| 0.5 | 100x median | 0.88 / 0.88 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.08 | 0.00 / 1.00 / 1.00 / 1.31 | 0.00 / 1.00 / 1.00 / 1.88 | +| 0.5 | 20x median | 0.15 / 0.15 / 0.00 / 1.00 | 0.00 / 0.80 / 0.80 / 1.50 | 0.00 / 1.00 / 1.00 / 2.35 | 0.00 / 1.00 / 1.00 / 4.73 | +| 0.5 | 5x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 2.00 | 0.00 / 1.00 / 1.00 / 6.41 | 0.00 / 1.00 / 1.00 / 11.38 | +| 0.9 | none | 1.00 / 1.00 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.00 | +| 0.9 | 100x median | 0.88 / 0.88 / 0.00 / 1.00 | 0.00 / 1.00 / 1.00 / 1.93 | 0.00 / 1.00 / 1.00 / 3.58 | 0.00 / 1.00 / 1.00 / 6.50 | +| 0.9 | 20x median | 0.15 / 0.15 / 0.00 / 1.00 | 0.00 / 0.80 / 0.80 / 2.00 | 0.00 / 1.00 / 1.00 / 9.66 | 0.00 / 1.00 / 1.00 / 21.58 | +| 0.9 | 5x median | 0.00 / 0.00 / 0.00 / 1.00 | 0.00 / 0.00 / 0.00 / 2.00 | 0.00 / 1.00 / 1.00 / 10.00 | 0.00 / 1.00 / 1.00 / 59.10 | + +Evasion rate over the sweep (phi x cap x k in 2, 10, 100 x live set x weights x roll x seed), cases where the joint share needed cutting: + +| live estates | joint share >= .5 (k > 1) | of which no identity binds (evaded) | +|---|---|---| +| all four estates | 0 | 0 | +| Members + Minds | 0 | 0 | +| Members alone | 5942 | 5942 (1.000) | + ## Claim tally over all cells (SPEC section 8) supported 0, fails 2, undecided 233, n/a 0 diff --git a/docs/research/2026-11-05-estate-rule-sim/run.py b/docs/research/2026-11-05-estate-rule-sim/run.py index cc3755f..e0162c9 100644 --- a/docs/research/2026-11-05-estate-rule-sim/run.py +++ b/docs/research/2026-11-05-estate-rule-sim/run.py @@ -353,6 +353,73 @@ def stake_section(quick): return L +MEMBERS = E.ESTATES.index(E.CREDIT_ESTATE) +CLIVE = {"all four estates": (0, 1, 2, 3), "Members + Minds": (0, MEMBERS), "Members alone": (MEMBERS,)} +CREDIT_CAPS = (None, 100.0, 20.0, 5.0) # per-person credit cap, multiples of the ordinary members' median credit + + +def _capname(m): + return "none" if m is None else f"{m:g}x median" + + +def credit_section(quick): + """E7 contribution-weighted arm (SPEC section 5d). Pure functions of fixed seeds; no wall clock.""" + seeds = 4 if quick else 40 + phis = (.1, .5, .9) if quick else (.05, .1, .25, .4, .5, .6, .75, .9) + rolls = (E.ROLL["Members"],) if quick else (E.ROLL["Members"], 150) + ks = (1, 2, 10, 100) + L = ["## E7 contribution-weighted arm: linear credit, per-person cap, the half-influence cap (SPEC section 5d)", "", + f"Static weight analysis. One contributor holds a fraction phi of the {E.CREDIT_ESTATE} estate's total raw credit (receipts: hours or credited " + f"changes, one linear unit); {rolls[0]}" + (f" and {rolls[1]}" if len(rolls) > 1 else "") + + f" ordinary members hold Pareto({E.PARETO_ALPHA}) credit from {E.PARETO_XM:.0f}, {seeds} seeds each. Weight = min(credit, per-person cap), the same function " + "for the contributor and everyone else. The tally and the half cap are E6's: council share x = W x s over the live estates; the cap binds iff x >= .5. " + "Credit is not vote weight anywhere in this module; this table only says how often the half cap would have to act.", ""] + for ln, live in CLIVE.items(): + L += [f"**Half cap binds, {ln}: fraction of (weights x roll x seed) by contributor share phi (rows) and per-person credit cap (columns); one identity, k = 1**", "", + "| phi | " + " | ".join(_capname(m) for m in CREDIT_CAPS) + " |", "|---|" + "---|" * len(CREDIT_CAPS)] + for phi in phis: + cols = [] + for m in CREDIT_CAPS: + hit = tot = 0 + for W in E.WEIGHTS.values(): + for n in rolls: + for s in range(seeds): + hit += E.credit_run(phi, n, s, W, live, m)["binds"] + tot += 1 + cols.append(f"{hit / tot:.3f}") + L.append(f"| {phi:g} | " + " | ".join(cols) + " |") + L.append("") + L += ["**Splitting: the contributor's credit split evenly over k identities. Members alone, equal weights, roll " + f"{rolls[0]}, mean over seeds. binds = the half cap acts on an identity; joint >= .5 = the combined share would have needed cutting; " + "evaded = joint >= .5 and no identity binds; weight x = total weight / weight at k = 1**", "", + "| phi | cap | " + " | ".join(f"k={k}: binds / joint>=.5 / evaded / weight x" for k in ks) + " |", "|---|---|" + "---|" * len(ks)] + W = E.WEIGHTS["equal"] + for phi in (.25, .5, .9): + for m in CREDIT_CAPS: + cols = [] + for k in ks: + rs = [E.credit_run(phi, rolls[0], s, W, (MEMBERS,), m, k) for s in range(seeds)] + base = [E.credit_run(phi, rolls[0], s, W, (MEMBERS,), m, 1)["w_total"] for s in range(seeds)] + cols.append(f"{sum(r['binds'] for r in rs) / seeds:.2f} / {sum(r['joint_binds'] for r in rs) / seeds:.2f} / " + f"{sum(r['evaded'] for r in rs) / seeds:.2f} / {sum(r['w_total'] / b for r, b in zip(rs, base)) / seeds:.2f}") + L.append(f"| {phi:g} | {_capname(m)} | " + " | ".join(cols) + " |") + L += ["", "Evasion rate over the sweep (phi x cap x k in 2, 10, 100 x live set x weights x roll x seed), cases where the joint share needed cutting:", "", + "| live estates | joint share >= .5 (k > 1) | of which no identity binds (evaded) |", "|---|---|---|"] + for ln, live in CLIVE.items(): + j = ev = 0 + for phi in phis: + for m in CREDIT_CAPS: + for k in ks[1:]: + for Wt in E.WEIGHTS.values(): + for n in rolls: + for s in range(seeds): + r = E.credit_run(phi, n, s, Wt, live, m, k) + j += r["joint_binds"] + ev += r["evaded"] + L.append(f"| {ln} | {j} | {ev} ({ev / j:.3f}) |" if j else f"| {ln} | 0 | 0 |") + return L + [""] + + def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("--quick", action="store_true") @@ -388,6 +455,7 @@ def main(argv=None): L += [f"### {title.split(' ')[0]} / {name}", ""] + rule_table(r) + [""] L += [pair_line(r), "", "PS by category threshold:", ""] + percat_table(r) + [""] L += stake_section(a.quick) + L += credit_section(a.quick) L += ["## Claim tally over all cells (SPEC section 8)", "", f"supported {tally['supported']}, fails {tally['fails']}, undecided {tally['undecided']}, n/a {tally['n/a']}", ""] if failing: diff --git a/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py b/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py index c4e9dd0..de9defb 100644 --- a/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py +++ b/docs/research/2026-11-05-estate-rule-sim/test_estatesim.py @@ -420,6 +420,67 @@ class StakeTests(unittest.TestCase): self.assertTrue(all(x >= E.PARETO_XM for x in a)) +PINNED_CREDIT_BINDS = {None: 320, 100.0: 140, 20.0: 24, 5.0: 0} # of 320 (phi .5, .9 x roll 15, 150 x 40 seeds x 2 weights) + + +class CreditTests(unittest.TestCase): + """SPEC section 5d: contribution credit, per-person cap, the half-influence cap.""" + M = E.ESTATES.index("Members") + W = E.WEIGHTS["equal"] + ALONE = (1,) + + def test_one_standard_for_everyone(self): + for c in (3.0, 40.0, 1e6): # a Meta-sized credit gets no schedule of its own + self.assertEqual(E.credit_weight(c), c) + self.assertEqual(E.credit_weight(c, 25.0), min(c, 25.0)) + + def test_cap_is_per_person_and_a_multiple_of_the_ordinary_median(self): + lad = E.credit_ladder(15, 0) + self.assertIsNone(E.credit_cap_value(lad, None)) + self.assertEqual(E.credit_cap_value(lad, 20.0), 20.0 * sorted(lad)[7]) + + def test_contributor_holds_phi_of_raw_credit(self): + r = E.credit_run(.5, 15, 3, self.W, self.ALONE) + self.assertAlmostEqual(r["w_total"], r["rest"]) # uncapped: phi .5 means equal to everyone else + self.assertAlmostEqual(r["one"]["s"], .5) + + def test_half_cap_binds_at_half_of_credit_in_a_lone_estate_not_below(self): + self.assertTrue(E.credit_run(.5, 15, 0, self.W, self.ALONE)["binds"]) + self.assertFalse(E.credit_run(.49, 15, 0, self.W, self.ALONE)["binds"]) + + def test_other_estates_dilute_the_contributor_below_the_half_cap(self): + self.assertFalse(E.credit_run(.9, 15, 0, self.W, (0, 1, 2, 3))["binds"]) + + def test_credit_cap_reduces_weight_and_can_release_the_half_cap(self): + un = E.credit_run(.9, 15, 0, self.W, self.ALONE) + cp = E.credit_run(.9, 15, 0, self.W, self.ALONE, cap_mult=5.0) + self.assertTrue(un["binds"]) + self.assertFalse(cp["binds"]) + self.assertLess(cp["w_total"], un["w_total"]) + + def test_splitting_is_weight_neutral_without_a_cap_and_gains_with_one(self): + base = E.credit_run(.9, 15, 0, self.W, self.ALONE)["w_total"] + self.assertAlmostEqual(E.credit_run(.9, 15, 0, self.W, self.ALONE, k=10)["w_total"], base) + c1 = E.credit_run(.9, 15, 0, self.W, self.ALONE, cap_mult=20.0)["w_total"] + self.assertGreater(E.credit_run(.9, 15, 0, self.W, self.ALONE, cap_mult=20.0, k=10)["w_total"], c1) + + def test_per_identity_half_cap_is_evaded_by_splitting_credit(self): + r1 = E.credit_run(.9, 15, 0, self.W, self.ALONE, k=1) + r2 = E.credit_run(.9, 15, 0, self.W, self.ALONE, k=2) + self.assertTrue(r1["binds"] and not r1["evaded"]) + self.assertFalse(r2["binds"]) + self.assertTrue(r2["joint_binds"] and r2["evaded"]) + + def test_headline_numbers_are_pinned(self): + hit = {m: sum(E.credit_run(phi, n, s, w, self.ALONE, m)["binds"] for phi in (.5, .9) for n in (15, 150) + for s in range(40) for w in E.WEIGHTS.values()) for m in (None, 100.0, 20.0, 5.0)} + self.assertEqual(hit, PINNED_CREDIT_BINDS) + + def test_deterministic(self): + a, b = E.credit_run(.5, 15, 2, self.W, self.ALONE, 20.0, 10), E.credit_run(.5, 15, 2, self.W, self.ALONE, 20.0, 10) + self.assertEqual(a, b) + + class StrategyTests(unittest.TestCase): def test_deviation_never_makes_agent_worse_off(self): rng = random.Random(3) From 8abd9129176dda3c2dc29701a5737bf39caa6c22 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 21:26:13 +0000 Subject: [PATCH 004/170] docs: guest accounts design (role field, invite, grants, leave and erase) Co-Authored-By: Claude Sonnet 5.5 --- docs/guest-accounts.md | 255 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 docs/guest-accounts.md diff --git a/docs/guest-accounts.md b/docs/guest-accounts.md new file mode 100644 index 0000000..3044056 --- /dev/null +++ b/docs/guest-accounts.md @@ -0,0 +1,255 @@ +# Guest accounts + +Status: **design, nothing implemented.** Written for `eureka-body:follow_up:bifrost-guest-accounts` under +`eureka-body:ruling:guest-arrival-bifrost` (Meta: guests need no Matrix account of their own; they get a GameCult +account through Bifrost with a guest role, and move to member, user or patron on the same account seamlessly), +building on `eureka-body:ruling:bifrost-owns-accounts-invite-only`. I could not `view` either ruling from the +Heimdall mind, so their text here is the follow-up brief's wording; check it against the rulings. First guest: +sletz (Faust developer). Aqua decides on `#aquasynth` access, so the first grant list is hers to name. + +Read at Bifrost `bf8ff62` (`src/Bifrost.Web/Domain/BifrostModels.cs`, `Features/Membership`, `Features/Heimdall`, +`Features/Oidc`, `Features/Motions`, `Features/ConceptVotes`, `Pages/App/Members`) and Heimdall `575be9c` +(`src/app-profiles.ts`, `docs/app-profiles/bifrost.md`). + +## The shape in one paragraph + +A guest is a `UserAccount` like any other: same `Id` (the OIDC `sub`), same `NormalizedBifrostIdentity` (the Matrix +localpart, minted once). What is new is one field, `Membership.Role`, with four values: `guest`, `user`, `patron`, +`member`. Role is the single place that says what an account may do. A role change rewrites that field and writes a +receipt; it never creates a second account, never re-mints the identity, so chat history, grants and the Matrix +user stay attached. + +## What exists today + +- `UserAccount.Id` is the OIDC subject; `NormalizedBifrostIdentity` is `preferred_username` and, through MAS, the + Matrix localpart (`docs/oidc-issuer.md`). `HeimdallAccountId` is only an authenticator handle. +- `Membership.Status` is `Authenticated | PendingApproval | Active | Suspended`. `CurrentBifrostActor.IsActiveMember` + (`Status == Active`) is the one test behind `/App`, bridge transport (`BridgeActionService` l.492), motion votes + (`EffectiveVotingWeight`, `MotionGovernanceService` l.72), concept votes (`VoterIdentity.For`, member versus + account class) and the OIDC authorize, token and userinfo endpoints (`OidcEndpoints` l.50, l.131) and the + back-channel logout reconciler. +- `MemberRole` (`StandardMember`, `Producer`, `Maintainer`, `LedgerReviewer`, `PlatformAdmin`) are capability + roles a member holds in addition. They are not the new field. +- Invites are `MembershipInvitation`, keyed by GitHub login (`MembershipSynchronizationService` l.37, + `Members/Index.cshtml.cs` l.34). A guest may have no GitHub login at all. +- Heimdall sign-in (`HeimdallAuthService.StartAsync`) with `requireMemberAccess = false` already creates an + identity-only account at `Authenticated`; with member access it creates `Active`. +- Nothing exists for room grants, leaving, erasing, or any "estate" in code (estates are rulings and research + only, `docs/charter-amendment-proposal.md`). + +## Decision: one role field, status stays lifecycle + +Two authorities cannot both say "may this account vote". Today `Status == Active` says it. The cut: + +- `Membership.Status` keeps its meaning as lifecycle of the account: may it hold a session. Add `Left` and + `Erased` (see Leave and erase). `Active` means admitted and in good standing, for any role. +- `Membership.Role` (new, non-null, enum `AccountRole`) decides rights. `IsActiveMember` becomes + `Status == Active && Role == Member`, and is the only place that expression exists. Every current + `IsActiveMember` caller keeps working unchanged and a guest fails all of them without a per-site edit. +- OIDC authorize, token, userinfo and the logout reconciler change their test from "Active member" to + "`Status == Active`" (any role), so a guest, user or patron can hold a chat session and a member demoted to + `Suspended` still loses it. This is the one behavioural change outside new code, and it is the line to review. +- Backfill: `Active` becomes `member`; `Authenticated` and `PendingApproval` become `user`; an account with a + current `Patron` tier snapshot and not `Active` becomes `patron`. Nobody starts as `guest`. + +Naming risk: `MemberRole` already exists for capability roles. If the collision bites, call the new field +`Class`; the published field below follows whichever name is chosen. I use `Role` because that is the ruling's word. + +Alternative considered and not recommended: a boolean `IsGuest` on `Membership` with guests kept at `Active`. +Smaller to land, but `user` and `patron` stay implicit in status and tier snapshots, so "the role field Personas +read" would have to be derived in three places. One stored field is one reading. + +## Invite shape + +New table `GuestInvitation`, separate from `MembershipInvitation` (which is GitHub-login-keyed and leads to +approval, not to a guest). Fields: + +| field | rule | +|---|---| +| `Id` | Guid. | +| `TokenHash` | SHA-256 of a 256-bit random token. The token itself is shown to the issuer once, as a link, and never stored. | +| `IntendedIdentity` | the localpart the issuer picks (for example `sletz`), validated by `BifrostIdentityService.NormalizeIdentity`, reserved while the invite is open. Minted once on accept; a collision gets the usual `-2` suffix. | +| `Label` | free note for the issuer ("sletz, Faust developer"). | +| `RoomGrants` | the rooms to grant on accept (below), as a list of grant requests. | +| `IssuedByUserAccountId`, `IssuedAtUtc` | issuer must be a platform admin (`CanManageMembership`), as for member invites. | +| `ExpiresAtUtc` | default seven days. | +| `AcceptedByUserAccountId`, `AcceptedAtUtc`, `RevokedAtUtc` | one use; revoke before accept ends it. | + +The link is a bearer: whoever signs in first with it is the guest. That is the cost of not needing sletz's +provider handle in advance, and it is why the token is single-use and short-lived and why the accept is shown +to the issuer. Recommended over binding the invite to a provider handle (which needs a Discord or Google id the +issuer may not have). The issuer may still restrict `ExpectedProvider`; open fork, see Questions. + +## Sign-in via Heimdall + +1. Guest opens `/invite/guest/`. Bifrost checks hash, expiry, unused, unrevoked, and stores the invite id in + the existing Heimdall attempt (`HeimdallAuthService` protects attempt state with the data protector). +2. Bifrost starts Heimdall sign-in with `requireMemberAccess = false` (identity only, no entitlement policy). + Heimdall authenticates; it does not issue the identity (`docs/jurisdiction-map.md`). +3. On the callback, in one transaction: resolve `HeimdallAccountId`. + - No account: create `UserAccount` with `IntendedIdentity`, `Membership { Status = Active, Role = Guest }`, write + the room grants, mark the invite accepted, write the receipt. + - Account exists: the invite never lowers an account. A `member`, `patron` or `user` keeps their role; the grants + are added and the invite is spent. If the existing account is `Left` or `Erased`, refuse. +4. Bifrost issues its own cookie as for any account. From there the guest reaches chat through the one OIDC client. + +Gap, drift found while reading: Bifrost's `AllowedProviders` is `discord, patreon, twitch` +(`HeimdallAuthService.AllowedProviders`), but Heimdall's `bifrost` app profile allows `discord, patreon, google` +(`app-profiles.ts`, `bifrostProfile`). Twitch cannot start in Heimdall and Google is refused by Bifrost. A guest with +neither Discord, Patreon nor a Google account cannot sign in, and GitHub is not a Heimdall sign-in provider for +this app. Which provider sletz uses is unknown to me; align the two lists before the first invite. + +## Guest rights + +A guest may: sign in, hold a Bifrost cookie, hold a chat session through OIDC, see and edit their own profile +(`MemberProfile`), be in the rooms granted to them, and leave or erase (below). A guest may not: + +- vote on motions: `EffectiveVotingWeight` is `0` for any role but `member` (today it is `Max(1, ...)` for + `Active`, which would give every guest weight 1; that line must read the role); +- cast concept-mill appraisals: `VoterIdentity.For` returns no voter for a guest (not even `VoterClass.Account`); +- appear on any estate roll or in any tally. The charter proposal snapshots each estate's roll at notice (A6); + `guest` is on no roll, so a guest cannot be counted, cannot make a quorum, and reclassifying a guest after a + snapshot changes nothing for that snapshot; +- use bridge transport, claim or log work, earn points or ledger credit, or hold tier snapshots (those make them + a patron or member by changing role, not by decorating a guest); +- hold a `MemberRole` or any of the `CanManage*` flags; +- invite anyone. + +This list is enforced by role in one place (`CurrentBifrostActor`), not by a check at each use. + +## Per-room grants + +Rooms are Matrix rooms in chat, not Bifrost objects. Bifrost owns the decision, so a grant is Bifrost state: + +`GuestRoomGrant { Id, UserAccountId, RoomRef, GrantedByUserAccountId, GrantedAtUtc, ExpiresAtUtc?, RevokedAtUtc? }` + +`RoomRef` is a room id or alias as chat names it. Aqua's `#aquasynth` is the first one if she says yes. + +The grant has to reach Matrix to mean anything. Today Bifrost's only Matrix writer is the Persona mouth, with +per-Persona access tokens (`docs/bridge.md`), and it holds no admin or invite right. + +Gap (largest in this doc): something must perform "invite this Matrix user to that room" on a grant and "remove +them" on revoke or expiry. Candidates: a Bifrost-owned bot user that is a member with invite power in the granted +rooms (reuses the Matrix client API, no Synapse admin credential), or the Synapse admin API. I recommend the bot +user: narrower credential, and the room's power levels remain the real gate. Until it exists, the grant is a +record, a human invites the guest by hand, and the receipt says `delivered_by: manual`. Rooms for guests must be +invite-only; a guest who can reach a public room needs no grant, and that is a chat configuration fact I have not +verified. + +Second gap: a guest has a full Matrix account once MAS provisions the localpart, so Matrix itself will let them +create rooms or DM unless Synapse's room-creation and invite settings (`room_list_publication_rules`, +`allow_public_rooms_*`, a spam-checker or module) say otherwise. These are global in Synapse, not per user, so a +guest limit may have to be power levels in every room they are in. I did not find a per-user switch. + +## Role change on the same account id, with a receipt + +`ChangeRole(accountId, to, actor, reason)` is the only writer of `Membership.Role`. It runs in one transaction: + +1. refuse `Erased` and `Left`; refuse a no-op; +2. write `Role`, and for `member` also set `Status = Active`, `ApprovedAtUtc`, and the default `StandardMember` + capability role (the same effects as `OnPostApproveAsync`); for `patron`, nothing beyond the role (tier + snapshots come from support events as before); +3. write `AccountRoleReceipt { Id, UserAccountId, From, To, ChangedAtUtc, ChangedByUserAccountId, Reason }`; +4. leave `UserAccount.Id`, `NormalizedBifrostIdentity`, `HeimdallAccountId`, grants and profile untouched. + +Who may change: a platform admin (`CanManageMembership`). Promoting to `member` is the existing approve path; +this design routes it through `ChangeRole` so one writer exists. Promoting to `member` also applies whatever the +charter says about joining an estate (not decided; see Questions). Demotion (member to guest) is allowed and +receipted; it also removes the `MemberRole`s and capability flags in the same transaction. + +The receipt is a Postgres row today, like `AuditEvent`. Bifrost's rule is that durable state has a CultCache `.cc` +witness (`docs/jurisdiction-map.md`, Design Rules); the witness is owed (Gaps). + +Seamless means: the guest's session cookie, OIDC subject, Matrix id, display name and room memberships do not +change on promotion. A cookie issued before promotion carries identity claims only, never the role, so it needs +no refresh; the actor is read from the database each request (`CurrentBifrostActorAccessor`). + +## Leave and erase + +Neither exists in Bifrost today. Two different acts: + +**Leave** (guest or any role, self-service): sets `Status = Left`, revokes every grant, and expels the account +from granted rooms through the same effector as grants. The OIDC reconciler already notices a non-`Active` +subject within 30 seconds and logs MAS out, and the token and userinfo endpoints refuse. The account row and +`Id` stay, so a later invite can restore it (a `Left` account re-accepting is a role change from itself, receipted). +Nothing else about the person is deleted by leaving. + +**Erase** (self-service, or admin on request): irreversible. In one transaction: blank `DisplayName`, `AvatarUrl`, +`MemberProfile`, `GitHubLogin`/`GitHubUserId`, clear `HeimdallAccountId` (the authenticator link), set +`Status = Erased`, keep `Id` and `NormalizedBifrostIdentity` as a tombstone so the localpart is never reissued to +someone else (OIDC says it is minted once), keep receipts but with names stripped. The reason to keep a tombstone +row is that receipts and audit events point at the id. + +An erasing guest has no votes, ledger entries or points, because guests cannot create them. A member or patron +who erases does, and those are accounting records: their erase is a separate question (Questions). Guest erase +is the case this design covers. + +Outside Bifrost, erase is incomplete without two effectors: + +- Matrix: Synapse's deactivate-with-erase admin call and MAS deactivation for the user. Federation is disabled in + the chat map (`gamecult-ops/docs/gamecult-chat-map.md`: federation paths 404), which helps: messages are + not copied to other servers. Other members' clients, and any export or training copy, are not reached by an + erase. Whether chat content is training data is `heimdall-body`'s consent rulings (Heimdall PR #6), which already + define exit by redaction; a guest's messages follow whatever that doc says, not this one. +- Heimdall: I found no account-delete or unlink path in Heimdall `src`. Clearing `HeimdallAccountId` on the Bifrost + side leaves the Heimdall account and its provider link alive. Heimdall needs an erase call keyed by the account id + before "erased" is true end to end. + +## What Eureka reads + +Personas read the role, not the account. Do not put it in OIDC: the issuer promises "no membership detail leaves +Bifrost" (`docs/oidc-issuer.md`) and chat does not need it. Publish a typed CultMesh document under the +`gamecult.bifrost.governance` family (the nearest existing schema namespace, `verse-service-contract.md` l.60), id +`gamecult.bifrost.account.v1`, key = account id: + +| field | type | note | +|---|---|---| +| `account_id` | uuid | OIDC `sub`; never changes. | +| `identity` | string | `NormalizedBifrostIdentity`; the Matrix localpart, so Matrix user id is `@:` (server name per MAS config, not verified here). | +| `display_name` | string | blank once erased. | +| `role` | `guest` \| `user` \| `patron` \| `member` | the field Personas read. | +| `status` | `authenticated` \| `pending_approval` \| `active` \| `suspended` \| `left` \| `erased` | | +| `role_since` | UTC ms | from the latest `AccountRoleReceipt`. | +| `rooms` | list of room refs | only for `guest`: the live grants. Others get rooms by estate. | + +A Persona deciding how to treat someone looks up `identity` from the Matrix sender and reads `role`. A sender with +no document is not a Bifrost account (a bridge ghost or an unlinked user) and is `unknown`, never defaulted to +`guest` or `user`. Bifrost does not decide Persona behavior; it states the role. + +No such publisher or witness exists; Bifrost has no `.cc` export for accounts today. + +## Cut sequence (not specs) + +1. `Membership.Role`, backfill, `IsActiveMember` and the OIDC tests moved to the new reading, vote and concept-vote + exclusions, with tests that fail if a guest gets weight or a voter key. +2. `GuestInvitation`, the accept path, the Heimdall provider list aligned. +3. `AccountRoleReceipt` and `ChangeRole`, with `OnPostApproveAsync` routed through it. +4. `GuestRoomGrant` and the Matrix effector. +5. Leave, then erase (Bifrost side), then the Matrix and Heimdall effectors. +6. The account document and its `.cc` witness. + +## Gaps, plainly + +- The Matrix effector for grants, leave and erase does not exist, and no credential for it is provisioned. +- Synapse cannot cap what a guest does per user; room-creation and invite limits are global (unverified: I did not + read the live Synapse config). +- Heimdall has no erase path. Bifrost and Heimdall disagree on provider lists today. +- No `.cc` witness or CultMesh publisher for accounts or receipts. Bifrost's account state is Postgres only. +- Matrix id shape (`@:`) depends on MAS importing `preferred_username` as localpart; the OIDC doc + says so, I did not check the deployed MAS. +- Tie to the answer-collector consent doc (Heimdall PR #6): a guest posting in a room may be posting to a sample + collector. That doc keys on `member_id`, and says a sender with no linked member is dropped. Whether a guest has a + `member_id`, and so whether their answers are collected at all, is not decided here. Default: not collected. +- Erase for member and patron roles (ledger and vote records) is unmapped. + +## Questions for the deciders + +1. **Is `Role` the right name** given `MemberRole`, and is one stored role (this doc) preferred over a boolean + `IsGuest`? Recommendation: stored role. Confidence: medium; the boolean is cheaper if user and patron are not + yet needed. +2. **Bearer link or provider-bound invite?** Recommendation: bearer, single use, seven days, optional + `ExpectedProvider`. Confidence: medium; this is a trust call about how sletz will be sent the link. +3. **Which Heimdall provider will sletz sign in with?** Needed before the lists are aligned. +4. **Do guests get a `member_id` for the answer collector?** Default no. +5. **Does promotion to member join the Members estate immediately**, or does the charter's notice and snapshot + rule apply to the roll? The charter text is a proposal, not in force. From c757acf525da1d60406ba0386f22c36a9f75ba85 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 7 Nov 2026 18:42:43 +0000 Subject: [PATCH 005/170] Make every cookie host-only: __Host- names, Secure, Path=/, no Domain Session, OAuth correlation, antiforgery, voter and Heimdall attempt cookies all take the __Host- prefix. The prefix forbids a narrower Path, so the voter (was /mill) and attempt (was /auth/heimdall) cookies move to Path=/. Co-Authored-By: Claude Sonnet 5.5 --- .../Features/ConceptVotes/VoterKeyResolver.cs | 5 +- .../Features/Heimdall/HeimdallAuthService.cs | 8 +- .../Features/Shared/BifrostCookies.cs | 17 +++ src/Bifrost.Web/Program.cs | 14 +++ .../Bifrost.Web.Tests/ConceptVotePageTests.cs | 5 +- .../ConceptVoteRateLimitTests.cs | 3 +- .../Bifrost.Web.Tests/CookieHardeningTests.cs | 101 ++++++++++++++++++ .../HeimdallCompletionTests.cs | 18 ++-- .../Support/HeimdallTestKit.cs | 3 +- 9 files changed, 155 insertions(+), 19 deletions(-) create mode 100644 src/Bifrost.Web/Features/Shared/BifrostCookies.cs create mode 100644 tests/Bifrost.Web.Tests/CookieHardeningTests.cs diff --git a/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs b/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs index ce9fbec..2948700 100644 --- a/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs +++ b/src/Bifrost.Web/Features/ConceptVotes/VoterKeyResolver.cs @@ -1,4 +1,5 @@ using System.Security.Cryptography; +using Bifrost.Web.Features.Shared; using Microsoft.AspNetCore.DataProtection; namespace Bifrost.Web.Features.ConceptVotes; @@ -7,8 +8,8 @@ namespace Bifrost.Web.Features.ConceptVotes; // decides the voter key and class. The cookie holds a protected random id, never a count, class or account. public sealed class VoterKeyResolver(IDataProtectionProvider dataProtection) { - public const string CookieName = "bifrost_voter"; - public const string CookiePath = "/mill"; + public const string CookieName = BifrostCookies.Voter; + public const string CookiePath = BifrostCookies.Path; public static readonly TimeSpan CookieLifetime = TimeSpan.FromDays(365); private const string Purpose = "Bifrost.ConceptVotes.DeviceToken.v1"; diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index 3e0b3a1..7749402 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs @@ -446,13 +446,13 @@ public sealed record HeimdallAccount( /// /// The attempt cookies: a ring of fixed names, so the Cookie header a browser sends to -/// /auth/heimdall is bounded by construction (a worst-case attempt is about 2.4 KB; nginx's line limit is 8 KB). +/// every path is bounded by construction (the __Host- prefix forces Path=/; a worst-case attempt is about 2.4 KB, nginx's line limit is 8 KB). /// A start takes a free slot or overwrites the one expiring first; an overwritten attempt finds no cookie and /// is refused. The attempt's nonce lives inside the protected value, never in the cookie name. /// public static class HeimdallAttemptCookie { - public const string Prefix = "bifrost_heimdall_"; + public const string Prefix = BifrostCookies.HeimdallAttemptPrefix; public const int SlotCount = 2; public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10); @@ -465,7 +465,7 @@ public static class HeimdallAttemptCookie HttpOnly = true, Secure = true, SameSite = SameSiteMode.Lax, - Path = "/auth/heimdall", + Path = BifrostCookies.Path, MaxAge = Lifetime }; @@ -473,5 +473,5 @@ public static class HeimdallAttemptCookie /// The options a deletion carries: only the attempt cookie's Path, which a cookie is matched on. It carries no /// Max-Age, which would take precedence over the expiry Delete writes and leave the emptied cookie alive. /// - public static CookieOptions DeleteOptions() => new() { Path = "/auth/heimdall" }; + public static CookieOptions DeleteOptions() => new() { Path = BifrostCookies.Path }; } diff --git a/src/Bifrost.Web/Features/Shared/BifrostCookies.cs b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs new file mode 100644 index 0000000..1c099e8 --- /dev/null +++ b/src/Bifrost.Web/Features/Shared/BifrostCookies.cs @@ -0,0 +1,17 @@ +namespace Bifrost.Web.Features.Shared; + +// Every cookie Bifrost sets carries the __Host- prefix: the browser then accepts it only with Secure, Path=/ and no +// Domain, so no sibling subdomain of gamecult.org (the preview host is same-site) can plant or shadow one by setting +// a Domain=gamecult.org cookie of the same name. The prefix forbids a narrower Path, so these all live at Path=/. +public static class BifrostCookies +{ + public const string HostPrefix = "__Host-"; + + public const string Session = HostPrefix + "bifrost_session"; + public const string OAuthCorrelation = HostPrefix + "bifrost_oauth_correlation"; + public const string Antiforgery = HostPrefix + "bifrost_antiforgery"; + public const string Voter = HostPrefix + "bifrost_voter"; + public const string HeimdallAttemptPrefix = HostPrefix + "bifrost_heimdall_"; + + public const string Path = "/"; +} diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index d0656d3..c8a524a 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -76,6 +76,13 @@ builder.Services .AddOptions() .BindConfiguration(ConceptVoteOptions.SectionName); +builder.Services.AddAntiforgery(options => +{ + options.Cookie.Name = BifrostCookies.Antiforgery; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.Cookie.Path = BifrostCookies.Path; +}); + builder.Services.AddRazorPages(options => { options.Conventions.AuthorizePage("/Membership/Status"); @@ -167,6 +174,10 @@ var authenticationBuilder = builder.Services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { + options.Cookie.Name = BifrostCookies.Session; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.Cookie.Path = BifrostCookies.Path; + options.Cookie.Domain = null; options.LoginPath = "/auth/sign-in"; options.AccessDeniedPath = "/Membership/Status"; options.SlidingExpiration = true; @@ -183,6 +194,9 @@ if (configuredGitHubOAuthOptions.IsConfigured) options.TokenEndpoint = "https://github.com/login/oauth/access_token"; options.UserInformationEndpoint = "https://api.github.com/user"; options.SaveTokens = true; + options.CorrelationCookie.Name = BifrostCookies.OAuthCorrelation; + options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always; + options.CorrelationCookie.Path = BifrostCookies.Path; options.Scope.Add("read:user"); options.Scope.Add("user:email"); options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); diff --git a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs index 5434e8d..d0675d7 100644 --- a/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs +++ b/tests/Bifrost.Web.Tests/ConceptVotePageTests.cs @@ -1,3 +1,4 @@ +using Bifrost.Web.Features.Shared; using System.Net; using System.Text.RegularExpressions; using Bifrost.Web.Data; @@ -14,7 +15,7 @@ namespace Bifrost.Web.Tests; public sealed partial class ConceptVotePageTests : IClassFixture { - private const string CookieName = "bifrost_voter"; + private const string CookieName = BifrostCookies.Voter; private const string Purpose = "Bifrost.ConceptVotes.DeviceToken.v1"; private readonly TestWebApplicationFactory _factory; @@ -40,7 +41,7 @@ public sealed partial class ConceptVotePageTests : IClassFixture { private const string Site = "https://localhost"; - private const string CookieName = "bifrost_voter"; + private const string CookieName = BifrostCookies.Voter; private readonly LimitedFactory _factory; diff --git a/tests/Bifrost.Web.Tests/CookieHardeningTests.cs b/tests/Bifrost.Web.Tests/CookieHardeningTests.cs new file mode 100644 index 0000000..3a43ebc --- /dev/null +++ b/tests/Bifrost.Web.Tests/CookieHardeningTests.cs @@ -0,0 +1,101 @@ +using Bifrost.Web.Features.ConceptVotes; +using Bifrost.Web.Features.Heimdall; +using Bifrost.Web.Features.Shared; +using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.OAuth; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace Bifrost.Web.Tests; + +// Every cookie is host-only: __Host- name, Secure, Path=/, no Domain. These pin the literals on purpose, so removing +// the prefix, Secure or Path=/ from any of them fails here and not only in a test that reads the same constant. +public sealed class CookieHardeningTests(CookieHardeningTests.OAuthConfiguredFactory factory) + : IClassFixture +{ + // Program reads GitHubOAuth at startup, before the base factory's in-memory settings land, so the GitHub scheme + // is only registered when the settings arrive as host settings. + public sealed class OAuthConfiguredFactory : TestWebApplicationFactory + { + protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) + { + builder.UseSetting("GitHubOAuth:ClientId", "configured-for-tests"); + builder.UseSetting("GitHubOAuth:ClientSecret", "configured-for-tests"); + base.ConfigureWebHost(builder); + } + } + + [Fact] + public void Cookie_names_carry_the_host_prefix_and_live_at_the_root() + { + Assert.Equal("__Host-bifrost_session", BifrostCookies.Session); + Assert.Equal("__Host-bifrost_oauth_correlation", BifrostCookies.OAuthCorrelation); + Assert.Equal("__Host-bifrost_antiforgery", BifrostCookies.Antiforgery); + Assert.Equal("__Host-bifrost_voter", VoterKeyResolver.CookieName); + Assert.Equal("__Host-bifrost_heimdall_", HeimdallAttemptCookie.Prefix); + Assert.All(HeimdallAttemptCookie.SlotNames, x => Assert.StartsWith("__Host-", x, StringComparison.Ordinal)); + Assert.Equal("/", BifrostCookies.Path); + Assert.Equal("/", VoterKeyResolver.CookiePath); + } + + [Fact] + public void Session_cookie_is_host_only() + { + var cookie = factory.Services.GetRequiredService>() + .Get(CookieAuthenticationDefaults.AuthenticationScheme).Cookie; + AssertHostOnly(cookie.Name, cookie.SecurePolicy, cookie.Path, cookie.Domain); + Assert.True(cookie.HttpOnly); + } + + [Fact] + public void Oauth_correlation_cookie_is_host_only() + { + var cookie = factory.Services.GetRequiredService>().Get("GitHub").CorrelationCookie; + AssertHostOnly(cookie.Name, cookie.SecurePolicy, cookie.Path, cookie.Domain); + Assert.True(cookie.HttpOnly); + } + + [Fact] + public void Antiforgery_cookie_is_host_only() + { + var cookie = factory.Services.GetRequiredService>().Value.Cookie; + AssertHostOnly(cookie.Name, cookie.SecurePolicy, cookie.Path, cookie.Domain); + } + + [Fact] + public void Voter_and_attempt_cookies_set_secure_root_path_and_no_domain() + { + var context = new DefaultHttpContext(); + new VoterKeyResolver(new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider()).Mint(context); + context.Response.Cookies.Append("__Host-bifrost_heimdall_0", "v", HeimdallAttemptCookie.Options()); + var deletion = new DefaultHttpContext(); + deletion.Response.Cookies.Delete("__Host-bifrost_heimdall_0", HeimdallAttemptCookie.DeleteOptions()); + + var headers = context.Response.Headers.SetCookie.Concat(deletion.Response.Headers.SetCookie).ToArray(); + Assert.Equal(3, headers.Length); + foreach (var header in headers) + { + var attributes = header!.Split(';').Select(x => x.Trim().ToLowerInvariant()).ToArray(); + Assert.StartsWith("__host-", attributes[0], StringComparison.Ordinal); + Assert.Contains("path=/", attributes); + Assert.DoesNotContain(attributes, x => x.StartsWith("domain", StringComparison.Ordinal)); + } + + Assert.All(headers.Take(2), header => + { + Assert.Contains("secure", header!.Split(';').Select(x => x.Trim().ToLowerInvariant())); + Assert.Contains("httponly", header!.Split(';').Select(x => x.Trim().ToLowerInvariant())); + }); + } + + private static void AssertHostOnly(string? name, CookieSecurePolicy secure, string? path, string? domain) + { + Assert.StartsWith("__Host-", name, StringComparison.Ordinal); + Assert.Equal(CookieSecurePolicy.Always, secure); + Assert.Equal("/", path); + Assert.Null(domain); + } +} diff --git a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs index 3439b43..68f0a94 100644 --- a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs @@ -526,7 +526,7 @@ public sealed class HeimdallCompletionTests Assert.Contains("httponly", attributes); Assert.Contains("secure", attributes); Assert.Contains("samesite=lax", attributes); - Assert.Contains("path=/auth/heimdall", attributes); + Assert.Contains("path=/", attributes); Assert.Contains("max-age=600", attributes); Assert.NotEqual(first.Cookie, second.Cookie); Assert.DoesNotContain(first.Nonce, first.Cookie!); @@ -564,7 +564,7 @@ public sealed class HeimdallCompletionTests Assert.Contains("