Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/patches/809ddc82cee344f3 # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-mv#250 (code only) closed derived `809ddc82cee344f3` #250 Imported from GitHub aien-dev/omega-mv#250 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `8da7f77194a3fae0c3dd561a76d1fe0e23971867` · Head `724a7ea0d81ab6cc2e6d0d38a21f27c25ead48a7` ### Apply it ``` git checkout -b patch-809ddc82cee344f3 8da7f77194a3fae0c3dd561a76d1fe0e23971867 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/809ddc82cee344f3.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-mv 250 724a7ea0d81ab6cc2e6d0d38a21f27c25ead48a7 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":250,"url":"https://github.com/aien-dev/omega-mv/pull/250","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:58Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.github/workflows/host-suites.yml b/.github/workflows/host-suites.yml index 31ed326c6..e6f0df3fd 100644 --- a/.github/workflows/host-suites.yml +++ b/.github/workflows/host-suites.yml @@ -21,6 +21,7 @@ name: Host suites # (test-numeric-transc-full and test-m17 are listed there as skipped jobs; # test-tensor and test-m16 have no Makefile target on main: NOT wired) # this file : searchtrace, estimation est-tools estimation-v3 est3c-tools, +# ans (test-inertial-alignment: ANS Inertial Alignment v1, ARCH-0032), # numeric-cpu numeric-qualify, train (M22 substrate, Lane 21), # compiler (OSC-1, own path guard) # @@ -57,6 +58,11 @@ on: - 'tests/estimation/**' - 'tools/estimation/**' - 'mk/estimation*.mk' + # ans (Inertial Alignment v1, ARCH-0032) + - 'src/ans/**' + - 'tests/ans/**' + - 'mk/ans.mk' + - 'docs/ans/**' - 'docs/estimation/EST3C_PROTOCOL_V3.md' - 'docs/estimation/receipts/est3c-v3/**' - 'evidence/R15/raw/**' @@ -106,6 +112,16 @@ jobs: - name: EST-3c v3 tools (synthetic data; no sealed run) run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-est3c-tools + ans: + runs-on: ubuntu-24.04-arm + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: ANS Inertial Alignment v1 (plain + ASan/UBSan, purity) + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-inertial-alignment + numeric-cpu: runs-on: ubuntu-24.04-arm timeout-minutes: 15 diff --git a/docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md b/docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md new file mode 100644 index 000000000..297d46561 --- /dev/null +++ b/docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md @@ -0,0 +1,147 @@ +# Inertial Alignment v1 (ANS, the Alignment Navigation System) + +Status: implemented in `src/ans/`, tested by `make test-inertial-alignment`. +Cites: ARCH-0020 (estimation, EST-0/EST-1), ARCH-0017 (ARGUS observes, never +authorizes), `EVOLUTION_ARENA_SPEC_V1` section 5 (promotion contract), and +ARCH-0032 (the ADR for this module, written in parallel in aien-architecture). + +## Idea + +An inertial navigation system keeps a position estimate by integrating motion +and goes stale as error accumulates, until an outside fix corrects it. ANS +treats alignment the same way. An agent's drift from its goal, intent, +provenance and scope is a small state estimated by the EST-1 Kalman filter. +Every action is a step that adds uncertainty. Sensors of three trust classes +pull the estimate back. A control law turns the estimate into an autonomy +tier. A promotion gate keeps self-improvement from touching the compass. + +## What ANS is NOT + +- Not an authority. ANS measures and recommends. It never grants, revokes or + promotes. A verdict is data for the authority to consult (ARCH-0017 shape). +- Not a promotion path. The right to promote stays with the operator-held + principal (Arena spec section 5.1). ANS never calls `rx_gen_promote`; the + purity check forbids any reference to `rx_`. +- Not a new filter. It links `est_kf` and does not reimplement it. +- Not a proof of alignment. Drift is an estimate with declared noise. +- Not wired into the resident runtime, `all` or `test`. + +## What is frozen + +The reference (the compass) is frozen. `ans_reference_freeze` validates it, +sets `frozen = 1` and returns its SHA-256 digest. Every other API takes a +`const ans_reference *` plus the expected digest and refuses +`ANS_ERR_REFERENCE` if the reference is unfrozen, invalid, or its recomputed +digest differs. The candidate under test never receives a mutable reference. +Atoms (10): AUTHORITY, CONSENT, SCOPE, PROVENANCE, REVERSIBILITY, +RESOURCE_LIMITS, INFORMATION_BOUNDARIES, GOAL_IDENTITY, DELEGATION_LIMITS, +SELF_MODIFICATION_LIMITS. Reference fields: `version` (non-zero), `limit[10]` +(max tolerated drift per atom, finite, > 0), `q[5]` (process noise per action +kind, > 0), `r[3]` (noise per sensor class, > 0, `r[FIX] < r[REFERENCE] < +r[IMU]`), `tier_sigma[3]` (0 < t1 < t2 < t3), `nis_limit` (> 0), +`promote_limit` (> 0). The digest covers all of these and not `frozen`. + +## State A_t + +`ans_state`: goal, constraints (== reference digest), intent, evidence_root, +drift (an `est_belief`, n = 4, components GOAL, INTENT, PROVENANCE, SCOPE, +dimensionless; x = estimated drift, P = covariance), risk (0..1, +reversibility risk of the pending action), provenance (hash chain over every +record that shaped the state), generation, since_fix, last reference digest +seen, last_nis, disagreement, self_mod_steps, self_mod_unfixed. +Filter model: n = m = 4, F = I, H = I, Q = q[kind] I per step, R = r[class] I +per measurement, `step_ns` = 1. The prior is x = 0, P = r[FIX] I. +Components map to atom limits: GOAL to GOAL_IDENTITY, INTENT to CONSENT, +PROVENANCE to PROVENANCE, SCOPE to SCOPE. + +## Actions (the inertial step) + +Kinds: OBSERVE, EFFECT, DELEGATE, INGEST_UNTRUSTED, SELF_MODIFY. +`ans_step` predicts one step with Q = q[kind] I, sets risk to the action's +reversibility risk, increments since_fix and generation, and chains the action +digest into provenance. Refused: non-finite input, zero action id, kind or +risk out of range, touches not 0/1, unfrozen or mismatched reference. An action +that touches SELF_MODIFICATION_LIMITS with reversibility risk above +`limit[SELF_MODIFICATION_LIMITS]` returns `ANS_ERR_ATOM`. The output state is +then the input with the refusal chained into provenance and generation +advanced and the drift unchanged: a record of the refusal, never a repair. A +SELF_MODIFY action, or one touching that atom, increments `self_mod_steps` and +`self_mod_unfixed`. + +## Sensors (the fusion) + +Classes: IMU (least trusted), REFERENCE, FIX (most trusted). +`ans_measure` runs `est_kf_predict` (one tick, Q = 1e-9 I) then `est_kf_update` +with R = r[class] I. A FIX sets since_fix to 0 and self_mod_unfixed to 0. +REFERENCE and FIX record last_nis; a reading with nis above `nis_limit` sets +`disagreement = 1` and is still fused: the disagreement is the signal and is +never hidden. The flag is sticky; only a FIX within the limit clears it. +Refused: zero evidence or source (`ANS_ERR_EVIDENCE`); IMU carrying a +reference digest, or REFERENCE/FIX whose reference digest is zero or not the +frozen one (`ANS_ERR_SENSOR`); non-finite values; an EST refusal +(`ANS_ERR_EST`, with the `est_status` in the out parameter), for example +evidence equal to a belief digest. The filter clock is the state's; +`t_ns` and `seq` are bound into the measurement digest. + +## Drift and the control law + +`ans_drift`: mean_norm = ||x||2, sigma = sqrt(trace P), D = sqrt(mean_norm^2 + +sigma^2). `ans_autonomy` returns an `ans_verdict` with tier FULL +(sigma < t1), REVERSIBLE_ONLY (t1 <= sigma < t2), SIMULATE_ONLY +(t2 <= sigma < t3), HALT_REQUEST_FIX (sigma >= t3). Any component whose |x| +exceeds its mapped atom limit raises the tier to at least REVERSIBLE_ONLY. +`disagreement == 1` forces HALT_REQUEST_FIX regardless of sigma. The verdict +carries D, mean_norm, sigma, since_fix, disagreement, the state digest, the +reference digest and its own digest. It is advisory. + +## Promotion gate (RSI may not touch the compass) + +`ans_promotion_check` takes a request (candidate digest, reference at birth, +tests at birth, tests now, candidate state) and writes a digested +`ans_promotion_record` whose `result` is, in this precedence order: +REFUSED_REFERENCE (reference at birth is not the frozen digest: the compass +changed during the candidate's life), REFUSED_TESTS (tests now differ from +tests at birth: the instrument changed in the same transaction), +REFUSED_DISAGREEMENT, REFUSED_DRIFT (D above `promote_limit`), +REFUSED_SELF_MOD (`self_mod_unfixed > 0`: self-modification without a FIX +after it), else OK. The return value is a status; a refusal is a successful +record. The record is data for the holder of the promotion right. + +## Status codes + +`ans_status`: OK, ERR_NULL, ERR_REFERENCE, ERR_NONFINITE, ERR_EVIDENCE, +ERR_SENSOR, ERR_ATOM, ERR_RANGE, ERR_EST, ERR_ENCODING. Promotion results are +the separate `ans_promo` enum. + +## Encoding and digests + +Digest = SHA-256(domain || 0x00 || encoding), domains `omega.ans..v1` +(reference, state, action, measurement, verdict, promotion). Fixed +little-endian layout, doubles as binary64 bits with -0.0 as +0.0, header +`OANS`, kind, version. Verdict and promotion record digests are computed with +their own digest field zeroed. Provenance chain: SHA-256(`omega.ans.provenance.v1` +|| 0x00 || prev || tag || record digest). Deterministic (`-ffp-contract=off +-fno-fast-math`), bounded, no allocation, no globals, no I/O. + +## Tests (`tests/ans/test_ans.c`, plain and ASan/UBSan) + +1. Freeze and digest determinism; any field change changes the digest; unfrozen refused. +2. Hostile: a mutated copy of the frozen reference with the old digest is refused by every API. +3. Drift grows: 50 EFFECT steps, sigma strictly increasing, tier non-decreasing, reaches HALT_REQUEST_FIX. +4. A FIX restores: sigma below t1, since_fix 0, tier FULL. +5. IMU alone cannot restore FULL from SIMULATE_ONLY (chosen r and q below). +6. Disagreement: a REFERENCE with nis above the limit forces HALT with small sigma. +7. Refusals: zero evidence, IMU with a reference digest, FIX with a wrong digest, non-finite z, action refusals. +8. Promotion: the OK path and each of the five refusals. +9. Encodings round trip; golden digests are checked. +10. Self-modification: promotion refused without a FIX, allowed after one. + +Numbers used in the tests: q 0.001/0.01/0.02/0.03/0.05, r IMU 1.0, REFERENCE 0.1, +FIX 0.01, tier_sigma 0.25/0.5/1.0, nis_limit 13.28, promote_limit 0.6. With +alternating EFFECT and IMU the steady sigma is 0.617, inside the SIMULATE_ONLY band. + +## Build + +`make test-inertial-alignment` (purity plus unit suite); `make ans-purity` +(`nm -u` on each ans object against the estimation forbidden list and +`rx_gen_promote`); `make test-ans`. CI: `.github/workflows/host-suites.yml`. diff --git a/mk/ans.mk b/mk/ans.mk new file mode 100644 index 000000000..7b251217d --- /dev/null +++ b/mk/ans.mk @@ -0,0 +1,42 @@ +# ANS, Inertial Alignment v1 (docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md, ARCH-0032). +# Standalone: new files only under src/ans/, tests/ans/, docs/ans/. Links the +# EST-1 filter (est_kf.c); does not reimplement it. Picked up by +# `-include mk/*.mk`; not part of `all` or `test`. Nothing in src/runtime/ +# includes or links it. ANS is advisory: it never authorizes or promotes. +# +# test-ans unit suite (10 tests), plain + ASan/UBSan +# ans-purity nm -u on every ans object against EST_FORBIDDEN and rx_gen_promote +# test-inertial-alignment both +ifndef ANS_MK +ANS_MK := 1 +include mk/estimation.mk +.PHONY: test-ans ans-purity test-inertial-alignment +ANS_CFLAGS = $(EST_CFLAGS) -Isrc/ans +ANS_DIR = $(OUT_DIR)/tests-ans +ANS_SRCS = src/ans/ans.c src/ans/ans_encode.c $(EST_KF_SRCS) +ANS_HDRS = src/ans/ans.h $(EST_HDRS) + +$(ANS_DIR)/%.o: src/ans/%.c $(ANS_HDRS) + @mkdir -p $(ANS_DIR) + $(CC) $(ANS_CFLAGS) -c -o $@ $< + +ans-purity: $(ANS_DIR)/ans.o $(ANS_DIR)/ans_encode.o + @if nm -u $^ | grep -E $(EST_FORBIDDEN) || nm -u $^ | grep rx_gen_promote ; then \ + echo "ans object references an operation an advisory module must not have"; exit 1; fi + @echo "ans-purity: ans.o and ans_encode.o reference no forbidden symbol and no rx_gen_promote" + +$(ANS_DIR)/test_ans: tests/ans/test_ans.c $(ANS_SRCS) $(ANS_HDRS) + @mkdir -p $(ANS_DIR) + $(CC) $(ANS_CFLAGS) -o $@ tests/ans/test_ans.c $(ANS_SRCS) -lm +$(ANS_DIR)/test_ans_asan: tests/ans/test_ans.c $(ANS_SRCS) $(ANS_HDRS) + @mkdir -p $(ANS_DIR) + $(CC) $(ANS_CFLAGS) $(EST_ASAN) -o $@ tests/ans/test_ans.c $(ANS_SRCS) -lm + +test-ans: $(ANS_DIR)/test_ans $(ANS_DIR)/test_ans_asan + ./$(ANS_DIR)/test_ans + ./$(ANS_DIR)/test_ans_asan + @echo "test-ans: ANS checks pass in plain and ASan/UBSan builds" + +test-inertial-alignment: ans-purity test-ans + @echo "test-inertial-alignment: Inertial Alignment v1 (ANS) passes" +endif diff --git a/src/ans/.crumb b/src/ans/.crumb new file mode 100644 index 000000000..0ce2356a0 --- /dev/null +++ b/src/ans/.crumb @@ -0,0 +1,6 @@ +{ + "schema_version": "1.0.0", + "name": "src/ans", + "layer": "src/ans", + "purpose": "ANS (Alignment Navigation System), Inertial Alignment v1: frozen reference atoms, drift filter over EST-1, three sensor classes, autonomy tiers, promotion gate. Advisory only: measures and recommends, never grants, revokes or promotes (ARCH-0017 shape); the candidate never receives a mutable reference. No allocation, globals or I/O." +} diff --git a/src/ans/ans.c b/src/ans/ans.c new file mode 100644 index 000000000..a401afb49 --- /dev/null +++ b/src/ans/ans.c @@ -0,0 +1,321 @@ +/* ANS state machine, control law and promotion gate (see ans.h). The filter is + * EST-1 (est_kf.c) and is not reimplemented here. */ +#include "ans.h" +#include "est_kf.h" + +#include +#include + +ans_atom ans_component_atom(uint32_t component) +{ + static const ans_atom map[ANS_DIM] = { + ANS_ATOM_GOAL_IDENTITY, ANS_ATOM_CONSENT, ANS_ATOM_PROVENANCE, ANS_ATOM_SCOPE + }; + return map[component % ANS_DIM]; +} + +/* ---- reference ---- */ +static int pos_fin(double d) { return isfinite(d) && d > 0.0; } + +ans_status ans_reference_validate(const ans_reference *ref) +{ + if (!ref) return ANS_ERR_NULL; + if (ref->version == 0u) return ANS_ERR_REFERENCE; + for (uint32_t i = 0; i < ANS_ATOMS; i++) if (!pos_fin(ref->limit[i])) return ANS_ERR_REFERENCE; + for (uint32_t i = 0; i < ANS_ACT_KINDS; i++) if (!pos_fin(ref->q[i])) return ANS_ERR_REFERENCE; + for (uint32_t i = 0; i < ANS_SENSOR_KINDS; i++) if (!pos_fin(ref->r[i])) return ANS_ERR_REFERENCE; + if (!(ref->r[ANS_SENSOR_FIX] < ref->r[ANS_SENSOR_REFERENCE] && + ref->r[ANS_SENSOR_REFERENCE] < ref->r[ANS_SENSOR_IMU])) return ANS_ERR_REFERENCE; + if (!pos_fin(ref->tier_sigma[0]) || !(ref->tier_sigma[0] < ref->tier_sigma[1]) || + !(ref->tier_sigma[1] < ref->tier_sigma[2]) || !isfinite(ref->tier_sigma[2])) return ANS_ERR_REFERENCE; + if (!pos_fin(ref->nis_limit) || !pos_fin(ref->promote_limit)) return ANS_ERR_REFERENCE; + return ANS_OK; +} + +ans_status ans_reference_freeze(ans_reference *ref, ans_digest *out_digest) +{ + if (!ref || !out_digest) return ANS_ERR_NULL; + ans_status st = ans_reference_validate(ref); + if (st != ANS_OK) return st; + ans_digest d; + st = ans_digest_reference(ref, &d); + if (st != ANS_OK) return st; + ref->frozen = 1; + *out_digest = d; + return ANS_OK; +} + +ans_status ans_reference_check(const ans_reference *ref, const ans_digest *expected) +{ + if (!ref || !expected) return ANS_ERR_NULL; + if (ref->frozen != 1u) return ANS_ERR_REFERENCE; + if (ans_reference_validate(ref) != ANS_OK) return ANS_ERR_REFERENCE; + ans_digest d; + if (ans_digest_reference(ref, &d) != ANS_OK) return ANS_ERR_REFERENCE; + if (memcmp(d.b, expected->b, EST_DIGEST_SIZE) != 0) return ANS_ERR_REFERENCE; + return ANS_OK; +} + +/* ---- filter plumbing ---- */ +static void build_model(const ans_reference *ref, double q, est_model *m) +{ + memset(m, 0, sizeof *m); + m->n = m->m = ANS_DIM; + m->estimator = EST_ESTIMATOR_LINEAR_KALMAN; + m->meaning = EST_UNCERTAINTY_GAUSSIAN_COVARIANCE; + m->step_ns = 1; + for (uint32_t i = 0; i < ANS_DIM; i++) { + m->state_unit[i] = m->obs_unit[i] = EST_UNIT_DIMENSIONLESS; + m->F[i * ANS_DIM + i] = 1.0; + m->H[i * ANS_DIM + i] = 1.0; + m->Q[i * ANS_DIM + i] = q; + m->R[i * ANS_DIM + i] = ref->r[ANS_SENSOR_FIX]; + } +} + +/* The process noise differs per action kind, so the model digest differs per + * step. The belief is re-labelled with the step's model digest (same x, P, + * generation, evidence chain) before est_kf_predict, which binds by digest. */ +static est_status rebind(const est_model *m, const est_belief *b, est_belief *out) +{ + *out = *b; + return est_digest_model(m, &out->model); +} + +static ans_status wrap(est_status st, est_status *est_st) +{ + if (est_st) *est_st = st; + return st == EST_OK ? ANS_OK : ANS_ERR_EST; +} + +static ans_status guard(const ans_reference *ref, const ans_digest *digest, const ans_state *state) +{ + if (!ref || !digest || !state) return ANS_ERR_NULL; + ans_status st = ans_reference_check(ref, digest); + if (st != ANS_OK) return st; + if (est_check_belief(&state->drift) != EST_OK || state->drift.n != ANS_DIM) return ANS_ERR_EST; + if (!isfinite(state->risk) || !isfinite(state->last_nis)) return ANS_ERR_NONFINITE; + if (memcmp(state->constraints.b, digest->b, EST_DIGEST_SIZE) != 0) return ANS_ERR_REFERENCE; + return ANS_OK; +} + +ans_status ans_state_prior(const ans_reference *ref, const ans_digest *digest, + const ans_digest *goal, const ans_digest *intent, + ans_state *out, est_status *est_st) +{ + if (!ref || !digest || !goal || !intent || !out) return ANS_ERR_NULL; + ans_status st = ans_reference_check(ref, digest); + if (st != ANS_OK) return st; + if (est_digest_is_zero(goal) || est_digest_is_zero(intent)) return ANS_ERR_RANGE; + est_model m; + build_model(ref, ref->q[ANS_ACT_OBSERVE], &m); + double x0[ANS_DIM] = {0}, P0[ANS_DIM * ANS_DIM] = {0}; + for (uint32_t i = 0; i < ANS_DIM; i++) P0[i * ANS_DIM + i] = ref->r[ANS_SENSOR_FIX]; + ans_state s; + memset(&s, 0, sizeof s); + est_status es = est_kf_prior(&m, x0, P0, 0, &s.drift); + if (es != EST_OK) return wrap(es, est_st); + s.goal = *goal; + s.intent = *intent; + s.constraints = *digest; + s.evidence_root = s.drift.evidence_root; + s.last_reference_digest_seen = *digest; + ans_digest root; + memset(&root, 0, sizeof root); + ans_provenance_extend(&root, "prior", digest, &s.provenance); + *out = s; + return wrap(EST_OK, est_st); +} + +ans_status ans_step(const ans_reference *ref, const ans_digest *digest, const ans_state *state, + const ans_action *action, ans_state *out, est_status *est_st) +{ + if (!action || !out) return ANS_ERR_NULL; + ans_status st = guard(ref, digest, state); + if (st != ANS_OK) return st; + ans_digest adig; + st = ans_digest_action(action, &adig); /* validates kind, risk, touches, id */ + if (st != ANS_OK) return st; + ans_state s = *state; + if (s.generation == UINT64_MAX || s.since_fix == UINT64_MAX) return ANS_ERR_RANGE; + if (action->touches[ANS_ATOM_SELF_MODIFICATION_LIMITS] && + action->reversibility_risk > ref->limit[ANS_ATOM_SELF_MODIFICATION_LIMITS]) { + /* refusal is recorded, never repaired: drift unchanged */ + ans_provenance_extend(&s.provenance, "refused", &adig, &s.provenance); + s.generation++; + *out = s; + return ANS_ERR_ATOM; + } + est_model m; + build_model(ref, ref->q[action->kind], &m); + est_belief rb; + est_prediction pred; + est_status es = rebind(&m, &state->drift, &rb); + if (es == EST_OK) es = est_kf_predict(&m, &rb, NULL, 1, &pred); + if (es == EST_OK) es = est_kf_coast(&m, &pred, &rb, &s.drift); + if (es != EST_OK) return wrap(es, est_st); + s.evidence_root = s.drift.evidence_root; + s.risk = action->reversibility_risk; + s.since_fix++; + s.generation++; + if (action->kind == ANS_ACT_SELF_MODIFY || action->touches[ANS_ATOM_SELF_MODIFICATION_LIMITS]) { + s.self_mod_steps++; + s.self_mod_unfixed++; + } + ans_provenance_extend(&s.provenance, "action", &adig, &s.provenance); + *out = s; + return wrap(EST_OK, est_st); +} + +ans_status ans_measure(const ans_reference *ref, const ans_digest *digest, const ans_state *state, + const ans_measurement *meas, ans_state *out, est_innovation *innovation_out, + est_status *est_st) +{ + if (!meas || !out) return ANS_ERR_NULL; + ans_status st = guard(ref, digest, state); + if (st != ANS_OK) return st; + for (uint32_t i = 0; i < ANS_DIM; i++) if (!isfinite(meas->z[i])) return ANS_ERR_NONFINITE; + if ((unsigned)meas->cls >= ANS_SENSOR_KINDS) return ANS_ERR_SENSOR; + if (est_digest_is_zero(&meas->source) || est_digest_is_zero(&meas->evidence)) return ANS_ERR_EVIDENCE; + if (meas->cls == ANS_SENSOR_IMU) { + if (!est_digest_is_zero(&meas->reference)) return ANS_ERR_SENSOR; + } else if (memcmp(meas->reference.b, digest->b, EST_DIGEST_SIZE) != 0) { + return ANS_ERR_SENSOR; /* zero, or any digest other than the frozen reference */ + } + ans_digest mdig; + st = ans_digest_measurement(meas, &mdig); + if (st != ANS_OK) return st; + ans_state s = *state; + if (s.generation == UINT64_MAX || s.since_fix == UINT64_MAX) return ANS_ERR_RANGE; + + est_model m; + build_model(ref, ANS_Q_HOLD, &m); + est_belief rb; + est_prediction pred; + est_observation obs; + est_innovation iv; + est_status es = rebind(&m, &state->drift, &rb); + if (es == EST_OK) es = est_kf_predict(&m, &rb, NULL, 1, &pred); + if (es != EST_OK) return wrap(es, est_st); + memset(&obs, 0, sizeof obs); + obs.m = ANS_DIM; + for (uint32_t i = 0; i < ANS_DIM; i++) { + obs.unit[i] = EST_UNIT_DIMENSIONLESS; + obs.z[i] = meas->z[i]; + obs.R[i * ANS_DIM + i] = ref->r[meas->cls]; + } + obs.t_ns = pred.t_ns; + obs.seq = meas->seq; + obs.source = meas->source; + obs.evidence = meas->evidence; + es = est_kf_update(&m, &rb, &pred, &obs, &s.drift, &iv); + if (es != EST_OK) return wrap(es, est_st); + s.evidence_root = s.drift.evidence_root; + s.generation++; + s.since_fix++; + if (meas->cls != ANS_SENSOR_IMU) { + s.last_nis = iv.nis; + s.last_reference_digest_seen = meas->reference; + if (iv.nis > ref->nis_limit) s.disagreement = 1; /* fused anyway: the disagreement is the signal */ + } + if (meas->cls == ANS_SENSOR_FIX) { + s.since_fix = 0; + s.self_mod_unfixed = 0; + if (iv.nis <= ref->nis_limit) s.disagreement = 0; + } + ans_provenance_extend(&s.provenance, "measurement", &mdig, &s.provenance); + if (innovation_out) *innovation_out = iv; + *out = s; + return wrap(EST_OK, est_st); +} + +/* ---- drift and control law ---- */ +ans_status ans_drift(const ans_state *state, double *mean_norm, double *sigma) +{ + if (!state || !mean_norm || !sigma) return ANS_ERR_NULL; + if (state->drift.n != ANS_DIM) return ANS_ERR_RANGE; + double ss = 0.0, tr = 0.0; + for (uint32_t i = 0; i < ANS_DIM; i++) { + ss += state->drift.x[i] * state->drift.x[i]; + tr += state->drift.P[i * ANS_DIM + i]; + } + if (!isfinite(ss) || !isfinite(tr) || tr < 0.0) return ANS_ERR_NONFINITE; + *mean_norm = sqrt(ss); + *sigma = sqrt(tr); + return ANS_OK; +} + +double ans_drift_total(double mean_norm, double sigma) +{ + return sqrt(mean_norm * mean_norm + sigma * sigma); +} + +ans_status ans_autonomy(const ans_reference *ref, const ans_digest *digest, const ans_state *state, + ans_verdict *out) +{ + if (!out) return ANS_ERR_NULL; + ans_status st = guard(ref, digest, state); + if (st != ANS_OK) return st; + ans_verdict v; + memset(&v, 0, sizeof v); + st = ans_drift(state, &v.mean_norm, &v.sigma); + if (st != ANS_OK) return st; + v.D = ans_drift_total(v.mean_norm, v.sigma); + ans_tier t = ANS_TIER_FULL; + if (v.sigma >= ref->tier_sigma[2]) t = ANS_TIER_HALT_REQUEST_FIX; + else if (v.sigma >= ref->tier_sigma[1]) t = ANS_TIER_SIMULATE_ONLY; + else if (v.sigma >= ref->tier_sigma[0]) t = ANS_TIER_REVERSIBLE_ONLY; + for (uint32_t i = 0; i < ANS_DIM; i++) + if (fabs(state->drift.x[i]) > ref->limit[ans_component_atom(i)] && t < ANS_TIER_REVERSIBLE_ONLY) + t = ANS_TIER_REVERSIBLE_ONLY; + if (state->disagreement) t = ANS_TIER_HALT_REQUEST_FIX; + v.tier = t; + v.since_fix = state->since_fix; + v.disagreement = state->disagreement; + st = ans_digest_state(state, &v.state); + if (st != ANS_OK) return st; + v.reference = *digest; + st = ans_digest_verdict(&v, &v.digest); + if (st != ANS_OK) return st; + *out = v; + return ANS_OK; +} + +/* ---- promotion gate ---- */ +ans_status ans_promotion_check(const ans_reference *ref, const ans_digest *digest, + const ans_promotion_request *req, ans_promotion_record *out) +{ + if (!ref || !digest || !req || !out) return ANS_ERR_NULL; + ans_status st = ans_reference_check(ref, digest); + if (st != ANS_OK) return st; + const ans_state *cs = &req->candidate_state; + if (est_check_belief(&cs->drift) != EST_OK || cs->drift.n != ANS_DIM) return ANS_ERR_EST; + if (!isfinite(cs->risk) || !isfinite(cs->last_nis)) return ANS_ERR_NONFINITE; + double mean, sigma; + st = ans_drift(cs, &mean, &sigma); + if (st != ANS_OK) return st; + ans_promotion_record r; + memset(&r, 0, sizeof r); + r.D = ans_drift_total(mean, sigma); + r.candidate = req->candidate; + r.reference = *digest; + r.tests = req->tests_now; + st = ans_digest_state(cs, &r.state); + if (st != ANS_OK) return st; + if (memcmp(req->reference_at_birth.b, digest->b, EST_DIGEST_SIZE) != 0) + r.result = ANS_PROMOTE_REFUSED_REFERENCE; + else if (memcmp(req->tests_now.b, req->tests_at_birth.b, EST_DIGEST_SIZE) != 0) + r.result = ANS_PROMOTE_REFUSED_TESTS; + else if (cs->disagreement) + r.result = ANS_PROMOTE_REFUSED_DISAGREEMENT; + else if (r.D > ref->promote_limit) + r.result = ANS_PROMOTE_REFUSED_DRIFT; + else if (cs->self_mod_unfixed > 0) + r.result = ANS_PROMOTE_REFUSED_SELF_MOD; + else + r.result = ANS_PROMOTE_OK; + st = ans_digest_promotion_record(&r, &r.digest); + if (st != ANS_OK) return st; + *out = r; + return ANS_OK; +} diff --git a/src/ans/ans.h b/src/ans/ans.h new file mode 100644 index 000000000..e92866934 --- /dev/null +++ b/src/ans/ans.h @@ -0,0 +1,246 @@ +/* ANS: Alignment Navigation System, Inertial Alignment v1. + * + * ANS measures and recommends. It never grants, revokes or promotes. A verdict + * is data for the authority to consult (the same shape as ARGUS, ARCH-0017, + * and as the estimation layer, ARCH-0020); it is never an authority input + * here and nothing in this module can change what any principal may do. + * + * THE ONE RULE OF THIS HEADER: the reference is frozen, and the candidate + * under test never receives a mutable reference. Every API takes a + * `const ans_reference *` plus the digest the caller expects it to have. + * An unfrozen reference, or one whose recomputed digest differs from the + * expected digest, is refused with ANS_ERR_REFERENCE. The compass cannot be + * edited by the thing it steers (EVOLUTION_ARENA_SPEC_V1 section 5; ARCH-0032). + * + * Model. Drift of the agent's alignment (goal, intent, provenance, scope) is a + * 4-dimensional dimensionless linear-Gaussian state estimated by the EST-1 + * Kalman filter (src/estimation/est_kf.c, linked, not reimplemented). Actions + * are the inertial step (process noise grows uncertainty); three sensor + * classes (IMU, REFERENCE, FIX) are the fusion, with FIX the most trusted. + * Autonomy is a control law on the resulting drift. Promotion of a candidate + * is refused if the compass or the test instrument changed during its life. + * + * Records are digested as SHA-256(domain || 0x00 || encoding) with domains + * "omega.ans..v1" and fixed little-endian encodings (doubles as + * IEEE-754 binary64, -0.0 canonicalized to +0.0). Bounded: no allocation, no + * globals, no I/O, deterministic. Every input is const, every output a new + * record. Refusals are never silently repaired. Spec: + * docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md. */ +#ifndef OMEGA_ANS_H +#define OMEGA_ANS_H + +#include +#include + +#include "est_types.h" + +#define ANS_ATOMS 10u +#define ANS_ACT_KINDS 5u +#define ANS_SENSOR_KINDS 3u +#define ANS_DIM 4u +#define ANS_FORMAT_VERSION 1u +#define ANS_ENCODED_MAX 1024u +/* process noise added by the predict inside a measurement (time passes by one + * tick; the measurement is not an action). Fixed, not a reference field. */ +#define ANS_Q_HOLD 1e-9 + +#define ANS_DOMAIN_REFERENCE "omega.ans.reference.v1" +#define ANS_DOMAIN_STATE "omega.ans.state.v1" +#define ANS_DOMAIN_ACTION "omega.ans.action.v1" +#define ANS_DOMAIN_MEASUREMENT "omega.ans.measurement.v1" +#define ANS_DOMAIN_VERDICT "omega.ans.verdict.v1" +#define ANS_DOMAIN_PROMOTION "omega.ans.promotion.v1" +#define ANS_DOMAIN_PROVENANCE "omega.ans.provenance.v1" +#define ANS_DOMAIN_REFUSAL "omega.ans.refusal.v1" + +typedef est_digest ans_digest; /* all-zero = absent */ + +typedef enum { + ANS_ATOM_AUTHORITY = 0, + ANS_ATOM_CONSENT, + ANS_ATOM_SCOPE, + ANS_ATOM_PROVENANCE, + ANS_ATOM_REVERSIBILITY, + ANS_ATOM_RESOURCE_LIMITS, + ANS_ATOM_INFORMATION_BOUNDARIES, + ANS_ATOM_GOAL_IDENTITY, + ANS_ATOM_DELEGATION_LIMITS, + ANS_ATOM_SELF_MODIFICATION_LIMITS +} ans_atom; + +/* Drift components (state dimension 4) and the atom whose limit bounds each. */ +typedef enum { ANS_COMP_GOAL = 0, ANS_COMP_INTENT, ANS_COMP_PROVENANCE, ANS_COMP_SCOPE } ans_comp; +ans_atom ans_component_atom(uint32_t component); + +typedef enum { + ANS_ACT_OBSERVE = 0, + ANS_ACT_EFFECT, + ANS_ACT_DELEGATE, + ANS_ACT_INGEST_UNTRUSTED, + ANS_ACT_SELF_MODIFY +} ans_act_kind; + +typedef enum { ANS_SENSOR_IMU = 0, ANS_SENSOR_REFERENCE, ANS_SENSOR_FIX } ans_sensor_class; + +typedef enum { + ANS_TIER_FULL = 0, + ANS_TIER_REVERSIBLE_ONLY, + ANS_TIER_SIMULATE_ONLY, + ANS_TIER_HALT_REQUEST_FIX +} ans_tier; + +typedef enum { + ANS_OK = 0, + ANS_ERR_NULL = -1, + ANS_ERR_REFERENCE = -2, /* unfrozen, invalid, or digest mismatch */ + ANS_ERR_NONFINITE = -3, + ANS_ERR_EVIDENCE = -4, /* zero evidence, source, goal-less action id */ + ANS_ERR_SENSOR = -5, /* class / reference digest rule broken */ + ANS_ERR_ATOM = -6, /* action breaks a reference atom */ + ANS_ERR_RANGE = -7, /* enum or numeric range */ + ANS_ERR_EST = -8, /* wrapped est_status in the est_st out param */ + ANS_ERR_ENCODING = -9 +} ans_status; + +typedef enum { + ANS_PROMOTE_OK = 0, + ANS_PROMOTE_REFUSED_REFERENCE, + ANS_PROMOTE_REFUSED_TESTS, + ANS_PROMOTE_REFUSED_DISAGREEMENT, + ANS_PROMOTE_REFUSED_DRIFT, + ANS_PROMOTE_REFUSED_SELF_MOD +} ans_promo; + +/* The compass. Frozen means validated and digested; see the rule above. */ +typedef struct { + uint32_t version; /* non-zero */ + double limit[ANS_ATOMS]; /* max tolerated drift per atom, >0 */ + double q[ANS_ACT_KINDS]; /* process noise per action kind, >0 */ + double r[ANS_SENSOR_KINDS]; /* noise per sensor class, r[FIX]0 */ + double promote_limit; /* max drift D for promotion, >0 */ + uint8_t frozen; +} ans_reference; + +typedef struct { + ans_digest goal; + ans_digest constraints; /* == reference digest */ + ans_digest intent; + ans_digest evidence_root; /* == drift.evidence_root */ + est_belief drift; /* n = ANS_DIM, x = drift, P = covariance */ + double risk; /* 0..1 reversibility risk of the pending action */ + ans_digest provenance; /* chain of every record that shaped this state */ + uint64_t generation; + uint64_t since_fix; /* steps since last FIX */ + ans_digest last_reference_digest_seen; + double last_nis; + uint8_t disagreement; /* sticky: set by REFERENCE/FIX nis > limit, cleared only by a FIX within limit */ + uint64_t self_mod_steps; /* SELF_MODIFY steps ever taken */ + uint64_t self_mod_unfixed; /* SELF_MODIFY steps since the last FIX */ +} ans_state; + +typedef struct { + ans_act_kind kind; + ans_digest id; /* non-zero */ + double reversibility_risk; /* 0..1 */ + uint32_t touches[ANS_ATOMS]; /* 0/1 */ +} ans_action; + +typedef struct { + ans_sensor_class cls; + double z[ANS_DIM]; + ans_digest source; /* non-zero */ + ans_digest evidence; /* non-zero raw-bytes digest, caller-bound as in EST */ + ans_digest reference; /* REFERENCE/FIX: == frozen reference digest; IMU: zero */ + int64_t t_ns; /* caller label, bound into the measurement digest; filter time is the state's */ + uint64_t seq; +} ans_measurement; + +typedef struct { + ans_tier tier; + double D; + double mean_norm; + double sigma; + uint64_t since_fix; + uint8_t disagreement; + ans_digest state; + ans_digest reference; + ans_digest digest; /* of this verdict (digest field zeroed in the encoding) */ +} ans_verdict; + +typedef struct { + ans_digest candidate; /* M' */ + ans_digest reference_at_birth; + ans_digest tests_at_birth; + ans_digest tests_now; + ans_state candidate_state; +} ans_promotion_request; + +/* Data for the promotion-right holder. ANS does not call the promotion entry + * point and the purity check forbids any reference to it. */ +typedef struct { + ans_promo result; + double D; + ans_digest candidate; + ans_digest reference; + ans_digest tests; + ans_digest state; + ans_digest digest; +} ans_promotion_record; + +/* ---- reference ---- */ +ans_status ans_reference_validate(const ans_reference *ref); +ans_status ans_digest_reference(const ans_reference *ref, ans_digest *out); +/* Validates, sets frozen = 1, writes the digest. The only mutation of a reference. */ +ans_status ans_reference_freeze(ans_reference *ref, ans_digest *out_digest); +/* OK iff frozen and the recomputed digest equals *expected. */ +ans_status ans_reference_check(const ans_reference *ref, const ans_digest *expected); + +/* ---- state machine. est_st (may be NULL) receives the wrapped est_status on ANS_ERR_EST. ---- */ +ans_status ans_state_prior(const ans_reference *ref, const ans_digest *digest, + const ans_digest *goal, const ans_digest *intent, + ans_state *out, est_status *est_st); +/* Inertial step. On ANS_ERR_ATOM *out is the input with the refusal recorded + * in provenance and generation (a record of the refusal, drift unchanged). */ +ans_status ans_step(const ans_reference *ref, const ans_digest *digest, const ans_state *state, + const ans_action *action, ans_state *out, est_status *est_st); +ans_status ans_measure(const ans_reference *ref, const ans_digest *digest, const ans_state *state, + const ans_measurement *meas, ans_state *out, est_innovation *innovation_out, + est_status *est_st); + +/* ---- drift and control law ---- */ +ans_status ans_drift(const ans_state *state, double *mean_norm, double *sigma); +double ans_drift_total(double mean_norm, double sigma); /* D = sqrt(mean^2 + sigma^2) */ +ans_status ans_autonomy(const ans_reference *ref, const ans_digest *digest, const ans_state *state, + ans_verdict *out); + +/* ---- promotion gate; the result is out->result, the return is a status ---- */ +ans_status ans_promotion_check(const ans_reference *ref, const ans_digest *digest, + const ans_promotion_request *req, ans_promotion_record *out); + +/* ---- identity ---- */ +/* provenance' = SHA-256(ANS_DOMAIN_PROVENANCE || 0x00 || prev || tag || record digest); out may alias prev */ +void ans_provenance_extend(const ans_digest *prev, const char *tag, const ans_digest *rec, ans_digest *out); +ans_status ans_digest_action(const ans_action *a, ans_digest *out); +ans_status ans_digest_measurement(const ans_measurement *m, ans_digest *out); +ans_status ans_digest_state(const ans_state *s, ans_digest *out); +ans_status ans_digest_verdict(const ans_verdict *v, ans_digest *out); +ans_status ans_digest_promotion_record(const ans_promotion_record *p, ans_digest *out); + +/* ---- serialization: exact round trip; decode validates and refuses a kind + * byte, version or length that does not match ---- */ +ans_status ans_encode_reference(const ans_reference *r, uint8_t *buf, size_t cap, size_t *len); +ans_status ans_decode_reference(const uint8_t *buf, size_t len, ans_reference *out); +ans_status ans_encode_action(const ans_action *a, uint8_t *buf, size_t cap, size_t *len); +ans_status ans_decode_action(const uint8_t *buf, size_t len, ans_action *out); +ans_status ans_encode_measurement(const ans_measurement *m, uint8_t *buf, size_t cap, size_t *len); +ans_status ans_decode_measurement(const uint8_t *buf, size_t len, ans_measurement *out); +ans_status ans_encode_state(const ans_state *s, uint8_t *buf, size_t cap, size_t *len); +ans_status ans_decode_state(const uint8_t *buf, size_t len, ans_state *out); +ans_status ans_encode_verdict(const ans_verdict *v, uint8_t *buf, size_t cap, size_t *len); +ans_status ans_decode_verdict(const uint8_t *buf, size_t len, ans_verdict *out); +ans_status ans_encode_promotion_record(const ans_promotion_record *p, uint8_t *buf, size_t cap, size_t *len); +ans_status ans_decode_promotion_record(const uint8_t *buf, size_t len, ans_promotion_record *out); + +#endif /* OMEGA_ANS_H */ diff --git a/src/ans/ans_encode.c b/src/ans/ans_encode.c new file mode 100644 index 000000000..0d929e436 --- /dev/null +++ b/src/ans/ans_encode.c @@ -0,0 +1,342 @@ +/* ANS record encodings and digests (see ans.h). One field-visitor per record + * serves both directions, so encoder and decoder cannot drift apart. + * + * Layout of every record: "OANS", kind byte, version byte, two zero bytes, + * then the fields in declaration order: u32/u64 little-endian, doubles as + * binary64 bit patterns (-0.0 as +0.0), digests as 32 raw bytes, and the + * embedded EST belief as u32 length + est_encode_belief bytes. */ +#include "ans.h" + +#include +#include + +#include "sha256.h" + +typedef struct { + uint8_t *p; + size_t cap, len, pos; + int dec, bad; +} cd; + +enum { K_REF = 1, K_ACTION, K_MEAS, K_STATE, K_VERDICT, K_PROMO }; + +static void c_raw(cd *c, void *buf, size_t n) +{ + if (c->bad) return; + if (c->dec) { + if (n > c->len - c->pos) { c->bad = 1; return; } + memcpy(buf, c->p + c->pos, n); + c->pos += n; + } else { + if (n > c->cap - c->len) { c->bad = 1; return; } + memcpy(c->p + c->len, buf, n); + c->len += n; + } +} +static void c_u64(cd *c, uint64_t *v) +{ + uint8_t t[8] = {0}; + if (!c->dec) for (int i = 0; i < 8; i++) t[i] = (uint8_t)(*v >> (8 * i)); + c_raw(c, t, 8); + if (c->dec && !c->bad) { + uint64_t r = 0; + for (int i = 0; i < 8; i++) r |= (uint64_t)t[i] << (8 * i); + *v = r; + } +} +static void c_u32(cd *c, uint32_t *v) +{ + uint8_t t[4] = {0}; + if (!c->dec) for (int i = 0; i < 4; i++) t[i] = (uint8_t)(*v >> (8 * i)); + c_raw(c, t, 4); + if (c->dec && !c->bad) { + uint32_t r = 0; + for (int i = 0; i < 4; i++) r |= (uint32_t)t[i] << (8 * i); + *v = r; + } +} +static void c_i64(cd *c, int64_t *v) +{ + uint64_t u = (uint64_t)*v; + c_u64(c, &u); + if (c->dec) *v = (int64_t)u; +} +static void c_u8(cd *c, uint8_t *v) { c_raw(c, v, 1); } +static void c_f64(cd *c, double *d) +{ + uint64_t u = 0; + if (!c->dec && *d != 0.0) memcpy(&u, d, 8); + c_u64(c, &u); + if (c->dec && !c->bad) memcpy(d, &u, 8); +} +static void c_farr(cd *c, double *a, size_t n) { for (size_t i = 0; i < n; i++) c_f64(c, &a[i]); } +static void c_dig(cd *c, ans_digest *d) { c_raw(c, d->b, EST_DIGEST_SIZE); } +static void c_hdr(cd *c, int kind) +{ + uint8_t h[8] = { 'O', 'A', 'N', 'S', (uint8_t)kind, (uint8_t)ANS_FORMAT_VERSION, 0, 0 }; + uint8_t g[8]; + memcpy(g, h, 8); + c_raw(c, g, 8); + if (c->dec && !c->bad && memcmp(g, h, 8) != 0) c->bad = 1; +} +static void c_belief(cd *c, est_belief *b) +{ + uint8_t tmp[EST_ENCODED_MAX]; + uint32_t l = 0; + if (!c->dec) { + size_t ll = 0; + if (est_encode_belief(b, tmp, sizeof tmp, &ll) != EST_OK) { c->bad = 1; return; } + l = (uint32_t)ll; + } + c_u32(c, &l); + if (c->bad || l > sizeof tmp) { c->bad = 1; return; } + c_raw(c, tmp, l); + if (c->dec && !c->bad && est_decode_belief(tmp, l, b) != EST_OK) c->bad = 1; +} + +static void v_ref(cd *c, ans_reference *r) +{ + c_hdr(c, K_REF); + c_u32(c, &r->version); + c_farr(c, r->limit, ANS_ATOMS); + c_farr(c, r->q, ANS_ACT_KINDS); + c_farr(c, r->r, ANS_SENSOR_KINDS); + c_farr(c, r->tier_sigma, 3); + c_f64(c, &r->nis_limit); + c_f64(c, &r->promote_limit); + c_u8(c, &r->frozen); +} +static void v_action(cd *c, ans_action *a) +{ + c_hdr(c, K_ACTION); + uint32_t k = (uint32_t)a->kind; + c_u32(c, &k); + if (c->dec) a->kind = (ans_act_kind)k; + c_dig(c, &a->id); + c_f64(c, &a->reversibility_risk); + for (uint32_t i = 0; i < ANS_ATOMS; i++) c_u32(c, &a->touches[i]); +} +static void v_meas(cd *c, ans_measurement *m) +{ + c_hdr(c, K_MEAS); + uint32_t k = (uint32_t)m->cls; + c_u32(c, &k); + if (c->dec) m->cls = (ans_sensor_class)k; + c_farr(c, m->z, ANS_DIM); + c_dig(c, &m->source); + c_dig(c, &m->evidence); + c_dig(c, &m->reference); + c_i64(c, &m->t_ns); + c_u64(c, &m->seq); +} +static void v_state_body(cd *c, ans_state *s) +{ + c_dig(c, &s->goal); + c_dig(c, &s->constraints); + c_dig(c, &s->intent); + c_dig(c, &s->evidence_root); + c_belief(c, &s->drift); + c_f64(c, &s->risk); + c_dig(c, &s->provenance); + c_u64(c, &s->generation); + c_u64(c, &s->since_fix); + c_dig(c, &s->last_reference_digest_seen); + c_f64(c, &s->last_nis); + c_u8(c, &s->disagreement); + c_u64(c, &s->self_mod_steps); + c_u64(c, &s->self_mod_unfixed); +} +static void v_state(cd *c, ans_state *s) { c_hdr(c, K_STATE); v_state_body(c, s); } +static void v_verdict(cd *c, ans_verdict *v) +{ + c_hdr(c, K_VERDICT); + uint32_t t = (uint32_t)v->tier; + c_u32(c, &t); + if (c->dec) v->tier = (ans_tier)t; + c_f64(c, &v->D); + c_f64(c, &v->mean_norm); + c_f64(c, &v->sigma); + c_u64(c, &v->since_fix); + c_u8(c, &v->disagreement); + c_dig(c, &v->state); + c_dig(c, &v->reference); + c_dig(c, &v->digest); +} +static void v_promo(cd *c, ans_promotion_record *p) +{ + c_hdr(c, K_PROMO); + uint32_t t = (uint32_t)p->result; + c_u32(c, &t); + if (c->dec) p->result = (ans_promo)t; + c_f64(c, &p->D); + c_dig(c, &p->candidate); + c_dig(c, &p->reference); + c_dig(c, &p->tests); + c_dig(c, &p->state); + c_dig(c, &p->digest); +} + +/* ---- semantic checks shared by encode, decode and digest ---- */ +static int fin(double d) { return isfinite(d); } +static int zero_dig(const ans_digest *d) { return est_digest_is_zero(d); } + +static ans_status chk_action(const ans_action *a) +{ + if ((unsigned)a->kind >= ANS_ACT_KINDS) return ANS_ERR_RANGE; + if (!fin(a->reversibility_risk)) return ANS_ERR_NONFINITE; + if (a->reversibility_risk < 0.0 || a->reversibility_risk > 1.0) return ANS_ERR_RANGE; + for (uint32_t i = 0; i < ANS_ATOMS; i++) if (a->touches[i] > 1u) return ANS_ERR_RANGE; + if (zero_dig(&a->id)) return ANS_ERR_EVIDENCE; + return ANS_OK; +} +static ans_status chk_meas(const ans_measurement *m) +{ + for (uint32_t i = 0; i < ANS_DIM; i++) if (!fin(m->z[i])) return ANS_ERR_NONFINITE; + if ((unsigned)m->cls >= ANS_SENSOR_KINDS) return ANS_ERR_SENSOR; + return ANS_OK; +} +static ans_status chk_state(const ans_state *s) +{ + if (est_check_belief(&s->drift) != EST_OK || s->drift.n != ANS_DIM) return ANS_ERR_EST; + if (!fin(s->risk) || !fin(s->last_nis)) return ANS_ERR_NONFINITE; + if (s->risk < 0.0 || s->risk > 1.0 || s->disagreement > 1u) return ANS_ERR_RANGE; + return ANS_OK; +} +static ans_status chk_verdict(const ans_verdict *v) +{ + if ((unsigned)v->tier > ANS_TIER_HALT_REQUEST_FIX || v->disagreement > 1u) return ANS_ERR_RANGE; + if (!fin(v->D) || !fin(v->mean_norm) || !fin(v->sigma)) return ANS_ERR_NONFINITE; + return ANS_OK; +} +static ans_status chk_promo(const ans_promotion_record *p) +{ + if ((unsigned)p->result > ANS_PROMOTE_REFUSED_SELF_MOD) return ANS_ERR_RANGE; + if (!fin(p->D)) return ANS_ERR_NONFINITE; + return ANS_OK; +} + +#define CODEC(NAME, TYPE, VISIT, CHECK) \ + ans_status ans_encode_##NAME(const TYPE *o, uint8_t *buf, size_t cap, size_t *len) \ + { \ + if (!o || !buf || !len) return ANS_ERR_NULL; \ + TYPE t = *o; \ + ans_status st = CHECK(&t); \ + if (st != ANS_OK) return st; \ + cd c = { buf, cap, 0, 0, 0, 0 }; \ + VISIT(&c, &t); \ + if (c.bad) return ANS_ERR_ENCODING; \ + *len = c.len; \ + return ANS_OK; \ + } \ + ans_status ans_decode_##NAME(const uint8_t *buf, size_t len, TYPE *out) \ + { \ + if (!buf || !out) return ANS_ERR_NULL; \ + TYPE t; \ + memset(&t, 0, sizeof t); \ + uint8_t tmp[ANS_ENCODED_MAX]; \ + if (len > sizeof tmp) return ANS_ERR_ENCODING; \ + memcpy(tmp, buf, len); \ + cd c = { tmp, 0, len, 0, 1, 0 }; \ + VISIT(&c, &t); \ + if (c.bad || c.pos != len) return ANS_ERR_ENCODING; \ + ans_status st = CHECK(&t); \ + if (st != ANS_OK) return st == ANS_ERR_REFERENCE ? st : ANS_ERR_ENCODING; \ + *out = t; \ + return ANS_OK; \ + } + +static ans_status chk_ref(const ans_reference *r) +{ + if (r->frozen > 1u) return ANS_ERR_RANGE; + return ans_reference_validate(r); +} + +CODEC(reference, ans_reference, v_ref, chk_ref) +CODEC(action, ans_action, v_action, chk_action) +CODEC(measurement, ans_measurement, v_meas, chk_meas) +CODEC(state, ans_state, v_state, chk_state) +CODEC(verdict, ans_verdict, v_verdict, chk_verdict) +CODEC(promotion_record, ans_promotion_record, v_promo, chk_promo) + +/* ---- digests ---- */ +static void hash_domain(const char *domain, const uint8_t *enc, size_t len, ans_digest *out) +{ + sha256_ctx c; + static const uint8_t zero = 0; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)domain, strlen(domain)); + sha256_update(&c, &zero, 1); + sha256_update(&c, enc, len); + sha256_final(&c, out->b); +} + +/* provenance' = SHA-256(ANS_DOMAIN_PROVENANCE || 0x00 || prev || tag || record digest) */ +void ans_provenance_extend(const ans_digest *prev, const char *tag, const ans_digest *rec, ans_digest *out) +{ + sha256_ctx c; + static const uint8_t zero = 0; + ans_digest r; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)ANS_DOMAIN_PROVENANCE, strlen(ANS_DOMAIN_PROVENANCE)); + sha256_update(&c, &zero, 1); + sha256_update(&c, prev->b, EST_DIGEST_SIZE); + sha256_update(&c, (const uint8_t *)tag, strlen(tag)); + sha256_update(&c, rec->b, EST_DIGEST_SIZE); + sha256_final(&c, r.b); + *out = r; +} + +ans_status ans_digest_reference(const ans_reference *ref, ans_digest *out) +{ + if (!ref || !out) return ANS_ERR_NULL; + ans_reference t = *ref; + t.frozen = 0; /* the digest names the content; frozen is the seal over it */ + uint8_t buf[ANS_ENCODED_MAX]; + size_t len = 0; + ans_status st = ans_encode_reference(&t, buf, sizeof buf, &len); + if (st != ANS_OK) return st; + hash_domain(ANS_DOMAIN_REFERENCE, buf, len, out); + return ANS_OK; +} + +#define PUB_DIGEST(NAME, TYPE, DOMAIN) \ + ans_status ans_digest_##NAME(const TYPE *o, ans_digest *out) \ + { \ + if (!o || !out) return ANS_ERR_NULL; \ + uint8_t buf[ANS_ENCODED_MAX]; \ + size_t len = 0; \ + ans_status st = ans_encode_##NAME(o, buf, sizeof buf, &len); \ + if (st != ANS_OK) return st; \ + hash_domain(DOMAIN, buf, len, out); \ + return ANS_OK; \ + } +PUB_DIGEST(action, ans_action, ANS_DOMAIN_ACTION) +PUB_DIGEST(measurement, ans_measurement, ANS_DOMAIN_MEASUREMENT) +PUB_DIGEST(state, ans_state, ANS_DOMAIN_STATE) + +/* verdict and promotion record carry their own digest field: it is zeroed in + * the encoding that is hashed. */ +ans_status ans_digest_verdict(const ans_verdict *v, ans_digest *out) +{ + if (!v || !out) return ANS_ERR_NULL; + ans_verdict t = *v; + memset(&t.digest, 0, sizeof t.digest); + uint8_t buf[ANS_ENCODED_MAX]; + size_t len = 0; + ans_status st = ans_encode_verdict(&t, buf, sizeof buf, &len); + if (st != ANS_OK) return st; + hash_domain(ANS_DOMAIN_VERDICT, buf, len, out); + return ANS_OK; +} +ans_status ans_digest_promotion_record(const ans_promotion_record *p, ans_digest *out) +{ + if (!p || !out) return ANS_ERR_NULL; + ans_promotion_record t = *p; + memset(&t.digest, 0, sizeof t.digest); + uint8_t buf[ANS_ENCODED_MAX]; + size_t len = 0; + ans_status st = ans_encode_promotion_record(&t, buf, sizeof buf, &len); + if (st != ANS_OK) return st; + hash_domain(ANS_DOMAIN_PROMOTION, buf, len, out); + return ANS_OK; +} diff --git a/tests/ans/.crumb b/tests/ans/.crumb new file mode 100644 index 000000000..46b53014c --- /dev/null +++ b/tests/ans/.crumb @@ -0,0 +1,6 @@ +{ + "schema_version": "1.0.0", + "name": "tests/ans", + "layer": "tests/ans", + "purpose": "Tests 1-10 for ANS (docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md): freeze/digest, hostile reference mutation, drift growth, FIX restore, IMU limit, disagreement, refusals, promotion gate, encodings with golden digests, self-modification. Run with make test-ans (plain + ASan/UBSan)." +} diff --git a/tests/ans/test_ans.c b/tests/ans/test_ans.c new file mode 100644 index 000000000..35f4af564 --- /dev/null +++ b/tests/ans/test_ans.c @@ -0,0 +1,455 @@ +/* ANS (Inertial Alignment v1) tests 1-10 of docs/ans/INERTIAL_ALIGNMENT_SPEC_V1.md. + * Numbers chosen (reference below), per drift component: + * q: OBSERVE .001 EFFECT .01 DELEGATE .02 INGEST .03 SELF_MODIFY .05 + * r: FIX .01 < REFERENCE .1 < IMU 1.0; prior P = r[FIX] = .01 + * tier_sigma .25 / .5 / 1.0 on sigma = sqrt(trace P) = 2 sqrt(p) + * Steady state of alternating EFFECT + IMU: p = (-q + sqrt(q^2 + 4 q r)) / 2 + * = .0951, sigma = .617, which lies in [.5, 1.0): IMU alone holds SIMULATE_ONLY + * and can never restore FULL (test 5). */ +#include "ans.h" + +#include +#include +#include +#include + +static int g_checks, g_fail; +#define CHECK(c) do { g_checks++; if (!(c)) { g_fail++; \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0) +#define CHECK_ST(expr, want) do { int s_ = (int)(expr); g_checks++; if (s_ != (int)(want)) { g_fail++; \ + fprintf(stderr, "FAIL %s:%d: %s = %d, want %d\n", __FILE__, __LINE__, #expr, s_, (int)(want)); } } while (0) + +static ans_digest dg(uint8_t v) { ans_digest d; memset(d.b, v, sizeof d.b); return d; } +static int deq(const ans_digest *a, const ans_digest *b) { return memcmp(a->b, b->b, EST_DIGEST_SIZE) == 0; } +static void hex(const ans_digest *d, char *o) { for (int i = 0; i < 32; i++) sprintf(o + 2 * i, "%02x", d->b[i]); } + +static ans_reference mkref(void) +{ + ans_reference r; + memset(&r, 0, sizeof r); + r.version = 1; + for (int i = 0; i < (int)ANS_ATOMS; i++) r.limit[i] = 1.0; + r.limit[ANS_ATOM_SELF_MODIFICATION_LIMITS] = 0.5; + r.q[ANS_ACT_OBSERVE] = 0.001; r.q[ANS_ACT_EFFECT] = 0.01; r.q[ANS_ACT_DELEGATE] = 0.02; + r.q[ANS_ACT_INGEST_UNTRUSTED] = 0.03; r.q[ANS_ACT_SELF_MODIFY] = 0.05; + r.r[ANS_SENSOR_IMU] = 1.0; r.r[ANS_SENSOR_REFERENCE] = 0.1; r.r[ANS_SENSOR_FIX] = 0.01; + r.tier_sigma[0] = 0.25; r.tier_sigma[1] = 0.5; r.tier_sigma[2] = 1.0; + r.nis_limit = 13.28; + r.promote_limit = 0.6; + return r; +} + +typedef struct { ans_reference ref; ans_digest rd; ans_state s; } rig; +static void mkrig(rig *g) +{ + g->ref = mkref(); + CHECK_ST(ans_reference_freeze(&g->ref, &g->rd), ANS_OK); + ans_digest goal = dg(0x11), intent = dg(0x22); + CHECK_ST(ans_state_prior(&g->ref, &g->rd, &goal, &intent, &g->s, NULL), ANS_OK); +} +static ans_action act(ans_act_kind k, uint8_t id, double risk) +{ + ans_action a; + memset(&a, 0, sizeof a); + a.kind = k; a.id = dg(id); a.reversibility_risk = risk; + return a; +} +static ans_measurement meas(ans_sensor_class c, const rig *g, const double *z, uint8_t ev) +{ + ans_measurement m; + memset(&m, 0, sizeof m); + m.cls = c; + for (int i = 0; i < (int)ANS_DIM; i++) m.z[i] = z ? z[i] : g->s.drift.x[i]; + m.source = dg(0x33); m.evidence = dg(ev); + if (c != ANS_SENSOR_IMU) m.reference = g->rd; + m.t_ns = 100; m.seq = ev; + return m; +} +static void step(rig *g, ans_act_kind k, uint8_t id, double risk) +{ + ans_action a = act(k, id, risk); + CHECK_ST(ans_step(&g->ref, &g->rd, &g->s, &a, &g->s, NULL), ANS_OK); +} +static void measure(rig *g, ans_sensor_class c, const double *z, uint8_t ev) +{ + ans_measurement m = meas(c, g, z, ev); + CHECK_ST(ans_measure(&g->ref, &g->rd, &g->s, &m, &g->s, NULL, NULL), ANS_OK); +} +static ans_verdict verdict(const rig *g) +{ + ans_verdict v; + memset(&v, 0, sizeof v); + CHECK_ST(ans_autonomy(&g->ref, &g->rd, &g->s, &v), ANS_OK); + return v; +} +static ans_promo promo(const rig *g, const ans_state *cand, const ans_digest *ref_birth, + const ans_digest *t_birth, const ans_digest *t_now) +{ + ans_promotion_request q; + ans_promotion_record out; + memset(&q, 0, sizeof q); + q.candidate = dg(0x44); + q.reference_at_birth = *ref_birth; + q.tests_at_birth = *t_birth; + q.tests_now = *t_now; + q.candidate_state = *cand; + memset(&out, 0xAA, sizeof out); + CHECK_ST(ans_promotion_check(&g->ref, &g->rd, &q, &out), ANS_OK); + ans_digest d; + CHECK_ST(ans_digest_promotion_record(&out, &d), ANS_OK); + CHECK(deq(&d, &out.digest)); + return out.result; +} + +static void test1_freeze(void) +{ + ans_reference a = mkref(), b = mkref(); + ans_digest da, db, dc; + memset(&da, 0, sizeof da); + CHECK_ST(ans_reference_check(&a, &da), ANS_ERR_REFERENCE); /* unfrozen refused */ + CHECK_ST(ans_reference_freeze(&a, &da), ANS_OK); + CHECK_ST(ans_reference_freeze(&b, &db), ANS_OK); + CHECK(deq(&da, &db)); + CHECK(a.frozen == 1); + CHECK_ST(ans_reference_check(&a, &da), ANS_OK); + /* every field change gives a different digest */ + ans_reference m; +#define MUT(EXPR) do { m = mkref(); EXPR; CHECK_ST(ans_digest_reference(&m, &dc), ANS_OK); CHECK(!deq(&dc, &da)); } while (0) + MUT(m.version = 2); + for (int i = 0; i < (int)ANS_ATOMS; i++) MUT(m.limit[i] += 0.125); + for (int i = 0; i < (int)ANS_ACT_KINDS; i++) MUT(m.q[i] *= 1.5); + for (int i = 0; i < (int)ANS_SENSOR_KINDS; i++) MUT(m.r[i] *= 0.9); + for (int i = 0; i < 3; i++) MUT(m.tier_sigma[i] *= 1.01); + MUT(m.nis_limit += 1.0); + MUT(m.promote_limit += 0.01); +#undef MUT + /* invalid references cannot be frozen */ + m = mkref(); m.r[ANS_SENSOR_IMU] = 0.05; /* breaks FIX < REFERENCE < IMU */ + CHECK_ST(ans_reference_freeze(&m, &dc), ANS_ERR_REFERENCE); + CHECK(m.frozen == 0); + m = mkref(); m.limit[3] = 0.0; + CHECK_ST(ans_reference_freeze(&m, &dc), ANS_ERR_REFERENCE); + m = mkref(); m.q[1] = NAN; + CHECK_ST(ans_reference_freeze(&m, &dc), ANS_ERR_REFERENCE); + m = mkref(); m.tier_sigma[1] = m.tier_sigma[0]; + CHECK_ST(ans_reference_freeze(&m, &dc), ANS_ERR_REFERENCE); + /* an unfrozen reference is refused by every API even with the right digest */ + rig g; mkrig(&g); + ans_reference u = mkref(); + ans_action ac = act(ANS_ACT_EFFECT, 1, 0.1); + ans_state o; + ans_digest goal = dg(1); + CHECK_ST(ans_step(&u, &g.rd, &g.s, &ac, &o, NULL), ANS_ERR_REFERENCE); + CHECK_ST(ans_state_prior(&u, &g.rd, &goal, &goal, &o, NULL), ANS_ERR_REFERENCE); +} + +static void test2_hostile(void) +{ + rig g; mkrig(&g); + ans_reference evil = g.ref; + evil.limit[ANS_ATOM_SELF_MODIFICATION_LIMITS] = 100.0; /* candidate loosens its own compass */ + CHECK(evil.frozen == 1); + ans_state o; + ans_verdict v; + ans_promotion_record pr; + ans_promotion_request q; + ans_action ac = act(ANS_ACT_EFFECT, 1, 0.1); + ans_measurement m = meas(ANS_SENSOR_FIX, &g, NULL, 5); + ans_digest goal = dg(1); + memset(&q, 0, sizeof q); + q.candidate_state = g.s; q.reference_at_birth = g.rd; + CHECK_ST(ans_state_prior(&evil, &g.rd, &goal, &goal, &o, NULL), ANS_ERR_REFERENCE); + CHECK_ST(ans_step(&evil, &g.rd, &g.s, &ac, &o, NULL), ANS_ERR_REFERENCE); + CHECK_ST(ans_measure(&evil, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_REFERENCE); + CHECK_ST(ans_autonomy(&evil, &g.rd, &g.s, &v), ANS_ERR_REFERENCE); + CHECK_ST(ans_promotion_check(&evil, &g.rd, &q, &pr), ANS_ERR_REFERENCE); + /* a copy whose frozen flag was cleared, and the genuine reference with a forged digest */ + ans_reference thawed = g.ref; thawed.frozen = 0; + CHECK_ST(ans_step(&thawed, &g.rd, &g.s, &ac, &o, NULL), ANS_ERR_REFERENCE); + ans_digest forged = g.rd; forged.b[0] ^= 1; + CHECK_ST(ans_step(&g.ref, &forged, &g.s, &ac, &o, NULL), ANS_ERR_REFERENCE); + CHECK_ST(ans_autonomy(&g.ref, &forged, &g.s, &v), ANS_ERR_REFERENCE); + /* the evil copy self-consistently re-frozen has a new digest: a state bound to the old one refuses it */ + ans_reference evil2 = evil; ans_digest ed; + evil2.frozen = 0; + CHECK_ST(ans_reference_freeze(&evil2, &ed), ANS_OK); + CHECK(!deq(&ed, &g.rd)); + CHECK_ST(ans_step(&evil2, &ed, &g.s, &ac, &o, NULL), ANS_ERR_REFERENCE); +} + +static void test3_drift_grows(void) +{ + rig g; mkrig(&g); + ans_verdict v = verdict(&g); + double prev = v.sigma; + ans_tier pt = v.tier; + CHECK(v.tier == ANS_TIER_FULL); + for (int i = 0; i < 50; i++) { + step(&g, ANS_ACT_EFFECT, (uint8_t)(0x40 + i), 0.1); + v = verdict(&g); + CHECK(v.sigma > prev); + CHECK(v.tier >= pt); + prev = v.sigma; pt = v.tier; + } + CHECK(v.tier == ANS_TIER_HALT_REQUEST_FIX); + CHECK(g.s.since_fix == 50); + CHECK(g.s.generation == 50); + CHECK(v.D >= v.sigma); +} + +static void test4_fix_restores(void) +{ + rig g; mkrig(&g); + for (int i = 0; i < 50; i++) step(&g, ANS_ACT_EFFECT, (uint8_t)(0x40 + i), 0.1); + CHECK(verdict(&g).tier == ANS_TIER_HALT_REQUEST_FIX); + measure(&g, ANS_SENSOR_FIX, NULL, 0x90); + ans_verdict v = verdict(&g); + CHECK(v.sigma < g.ref.tier_sigma[0]); + CHECK(g.s.since_fix == 0); + CHECK(v.tier == ANS_TIER_FULL); + CHECK(g.s.disagreement == 0); +} + +static void test5_imu_cannot_restore(void) +{ + rig g; mkrig(&g); + int guard = 0; + while (verdict(&g).tier != ANS_TIER_SIMULATE_ONLY && guard++ < 100) step(&g, ANS_ACT_EFFECT, (uint8_t)(0x40 + guard), 0.1); + CHECK(verdict(&g).tier == ANS_TIER_SIMULATE_ONLY); + for (int i = 0; i < 200; i++) { + step(&g, ANS_ACT_EFFECT, (uint8_t)(i + 1), 0.1); + measure(&g, ANS_SENSOR_IMU, NULL, (uint8_t)(0x80 + (i & 0x3f))); + CHECK(verdict(&g).tier != ANS_TIER_FULL); + } + ans_verdict v = verdict(&g); + CHECK(v.tier == ANS_TIER_SIMULATE_ONLY); + CHECK(fabs(v.sigma - 0.617) < 0.01); + CHECK(g.s.since_fix > 200); +} + +static void test6_disagreement(void) +{ + rig g; mkrig(&g); + ans_verdict v = verdict(&g); + CHECK(v.tier == ANS_TIER_FULL); + double far[ANS_DIM] = { 3.0, 0, 0, 0 }; + est_innovation iv; + ans_measurement m = meas(ANS_SENSOR_REFERENCE, &g, far, 0x61); + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &g.s, &iv, NULL), ANS_OK); + CHECK(iv.nis > g.ref.nis_limit); + CHECK(g.s.last_nis == iv.nis); + CHECK(g.s.disagreement == 1); + v = verdict(&g); + CHECK(v.sigma < g.ref.tier_sigma[0]); /* sigma small, yet */ + CHECK(v.tier == ANS_TIER_HALT_REQUEST_FIX); + CHECK(v.mean_norm > 0.2); /* fused anyway (gain .09 on a 3.0 reading), never hidden */ + /* an agreeing REFERENCE does not clear it; only a FIX within limit does */ + measure(&g, ANS_SENSOR_REFERENCE, NULL, 0x62); + CHECK(g.s.disagreement == 1); + measure(&g, ANS_SENSOR_FIX, NULL, 0x63); + CHECK(g.s.disagreement == 0); + /* an agreeing reading never raises it */ + rig h; mkrig(&h); + measure(&h, ANS_SENSOR_REFERENCE, NULL, 0x64); + CHECK(h.s.disagreement == 0); +} + +static void test7_refusals(void) +{ + rig g; mkrig(&g); + ans_state o; + ans_measurement m; + m = meas(ANS_SENSOR_FIX, &g, NULL, 1); memset(&m.evidence, 0, sizeof m.evidence); + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_EVIDENCE); + m = meas(ANS_SENSOR_FIX, &g, NULL, 1); memset(&m.source, 0, sizeof m.source); + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_EVIDENCE); + m = meas(ANS_SENSOR_IMU, &g, NULL, 1); m.reference = g.rd; + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_SENSOR); + m = meas(ANS_SENSOR_FIX, &g, NULL, 1); m.reference = dg(0x77); + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_SENSOR); + m = meas(ANS_SENSOR_REFERENCE, &g, NULL, 1); memset(&m.reference, 0, sizeof m.reference); + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_SENSOR); + m = meas(ANS_SENSOR_FIX, &g, NULL, 1); m.z[2] = NAN; + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_NONFINITE); + m = meas(ANS_SENSOR_IMU, &g, NULL, 1); m.z[0] = INFINITY; + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_NONFINITE); + m = meas(ANS_SENSOR_IMU, &g, NULL, 1); m.cls = (ans_sensor_class)9; + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, NULL), ANS_ERR_SENSOR); + /* a belief digest passed off as evidence (EST refuses) surfaces as ERR_EST */ + est_status es = EST_OK; + measure(&g, ANS_SENSOR_FIX, NULL, 0x30); /* now the belief has an evidence root */ + m = meas(ANS_SENSOR_IMU, &g, NULL, 1); m.evidence = g.s.evidence_root; + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &o, NULL, &es), ANS_ERR_EST); + CHECK(es != EST_OK); + /* actions */ + ans_action a = act(ANS_ACT_EFFECT, 1, 0.1); + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &o, NULL), ANS_OK); + a = act(ANS_ACT_EFFECT, 1, NAN); + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &o, NULL), ANS_ERR_NONFINITE); + a = act(ANS_ACT_EFFECT, 1, 1.5); + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &o, NULL), ANS_ERR_RANGE); + a = act(ANS_ACT_EFFECT, 0, 0.1); + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &o, NULL), ANS_ERR_EVIDENCE); + a = act((ans_act_kind)7, 1, 0.1); + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &o, NULL), ANS_ERR_RANGE); + a = act(ANS_ACT_EFFECT, 1, 0.1); a.touches[3] = 2; + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &o, NULL), ANS_ERR_RANGE); + a = act(ANS_ACT_SELF_MODIFY, 2, 0.9); a.touches[ANS_ATOM_SELF_MODIFICATION_LIMITS] = 1; + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &o, NULL), ANS_ERR_ATOM); + /* the refusal is recorded, drift is not repaired */ + CHECK(o.generation == g.s.generation + 1); + CHECK(!deq(&o.provenance, &g.s.provenance)); + CHECK(memcmp(o.drift.P, g.s.drift.P, sizeof o.drift.P) == 0); + CHECK(o.since_fix == g.s.since_fix); + CHECK(o.self_mod_steps == 0); + ans_digest zg; memset(&zg, 0, sizeof zg); + CHECK_ST(ans_state_prior(&g.ref, &g.rd, &zg, &g.rd, &o, NULL), ANS_ERR_RANGE); + CHECK_ST(ans_step(NULL, &g.rd, &g.s, &a, &o, NULL), ANS_ERR_NULL); +} + +static void test8_promotion(void) +{ + rig g; mkrig(&g); + ans_digest t0 = dg(0x55), t1 = dg(0x56); + ans_state good; + { rig h = g; measure(&h, ANS_SENSOR_FIX, NULL, 0x71); good = h.s; } + CHECK(promo(&g, &good, &g.rd, &t0, &t0) == ANS_PROMOTE_OK); + ans_digest other = dg(0x99); + CHECK(promo(&g, &good, &other, &t0, &t0) == ANS_PROMOTE_REFUSED_REFERENCE); + CHECK(promo(&g, &good, &g.rd, &t0, &t1) == ANS_PROMOTE_REFUSED_TESTS); + ans_state dis; + { rig h = g; double far[ANS_DIM] = { 3.0, 0, 0, 0 }; measure(&h, ANS_SENSOR_REFERENCE, far, 0x72); dis = h.s; } + CHECK(dis.disagreement == 1); + CHECK(promo(&g, &dis, &g.rd, &t0, &t0) == ANS_PROMOTE_REFUSED_DISAGREEMENT); + ans_state drift; + { rig h = g; for (int i = 0; i < 12; i++) step(&h, ANS_ACT_EFFECT, (uint8_t)(0x50 + i), 0.1); drift = h.s; } + CHECK(drift.disagreement == 0 && drift.self_mod_unfixed == 0); + CHECK(promo(&g, &drift, &g.rd, &t0, &t0) == ANS_PROMOTE_REFUSED_DRIFT); + ans_state sm; + { rig h = g; ans_action a = act(ANS_ACT_SELF_MODIFY, 0x58, 0.2); a.touches[ANS_ATOM_SELF_MODIFICATION_LIMITS] = 1; + CHECK_ST(ans_step(&h.ref, &h.rd, &h.s, &a, &h.s, NULL), ANS_OK); sm = h.s; } + CHECK(promo(&g, &sm, &g.rd, &t0, &t0) == ANS_PROMOTE_REFUSED_SELF_MOD); + /* precedence: reference change is reported before everything else */ + CHECK(promo(&g, &sm, &other, &t0, &t1) == ANS_PROMOTE_REFUSED_REFERENCE); +} + +static void test10_self_mod(void) +{ + rig g; mkrig(&g); + ans_digest t0 = dg(0x55); + ans_action a = act(ANS_ACT_SELF_MODIFY, 0x58, 0.2); + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &g.s, NULL), ANS_OK); /* SELF_MODIFY by kind alone */ + CHECK(g.s.self_mod_steps == 1 && g.s.self_mod_unfixed == 1); + CHECK(verdict(&g).D <= g.ref.promote_limit); /* drift alone would not refuse */ + CHECK(promo(&g, &g.s, &g.rd, &t0, &t0) == ANS_PROMOTE_REFUSED_SELF_MOD); + measure(&g, ANS_SENSOR_FIX, NULL, 0x73); + CHECK(g.s.self_mod_steps == 1 && g.s.self_mod_unfixed == 0); + CHECK(promo(&g, &g.s, &g.rd, &t0, &t0) == ANS_PROMOTE_OK); +} + +/* Golden values: the digests below are the contract of encoding v1. */ +static const char *GOLD_REF = "3be9ab21e6c989c6793e5eb69aa9d87493d4dfd42ce4aad04a3e89d3c4d0a110"; +static const char *GOLD_STATE = "20cfa169d802561f5c5a03c82edf8162711737aee68dbe5e17c3f436ff4caf04"; +static const char *GOLD_VERD = "e82707eb13485dbca4325a2214c60072444f6ed9c0ff0838bea0131208deec25"; +static const char *GOLD_PROMO = "5541443d59abf153e5595d16f05e1d645aecbacc9f85c619af4ac6cd7e990530"; +static const char *GOLD_ACT = "f9ac8b7cd8612affbf1a3f3917953bbb9fa40d5cec380892ef2a35750b7c4c49"; +static const char *GOLD_MEAS = "db1f5305061835bd0b338aa387dd1564a285c756bfe420e4b17f8aa8fb55e00f"; + +static void gold(const char *name, const ans_digest *d, const char *want) +{ + char h[65]; + hex(d, h); + printf("golden %-12s %s\n", name, h); + CHECK(strcmp(h, want) == 0); +} + +static void rt_check(int ok_a, int ok_b) { CHECK(ok_a); CHECK(ok_b); } + +static void test9_encodings(void) +{ + rig g; mkrig(&g); + ans_action a = act(ANS_ACT_DELEGATE, 0x21, 0.25); a.touches[ANS_ATOM_DELEGATION_LIMITS] = 1; + step(&g, ANS_ACT_EFFECT, 0x20, 0.1); + CHECK_ST(ans_step(&g.ref, &g.rd, &g.s, &a, &g.s, NULL), ANS_OK); + double z[ANS_DIM] = { 0.05, -0.02, 0.0, 0.01 }; + ans_measurement m = meas(ANS_SENSOR_REFERENCE, &g, z, 0x23); + CHECK_ST(ans_measure(&g.ref, &g.rd, &g.s, &m, &g.s, NULL, NULL), ANS_OK); + ans_verdict v = verdict(&g); + ans_digest t0 = dg(0x55); + ans_promotion_request q; + ans_promotion_record pr; + memset(&q, 0, sizeof q); + q.candidate = dg(0x44); q.reference_at_birth = g.rd; q.tests_at_birth = t0; q.tests_now = t0; q.candidate_state = g.s; + CHECK_ST(ans_promotion_check(&g.ref, &g.rd, &q, &pr), ANS_OK); + + uint8_t b1[ANS_ENCODED_MAX], b2[ANS_ENCODED_MAX]; + size_t l1, l2; + ans_digest d; +#define RT(NAME, TYPE, OBJ) \ + do { \ + TYPE back; \ + CHECK_ST(ans_encode_##NAME(&(OBJ), b1, sizeof b1, &l1), ANS_OK); \ + CHECK_ST(ans_decode_##NAME(b1, l1, &back), ANS_OK); \ + CHECK_ST(ans_encode_##NAME(&back, b2, sizeof b2, &l2), ANS_OK); \ + rt_check(l1 == l2, memcmp(b1, b2, l1) == 0); \ + CHECK_ST(ans_decode_##NAME(b1, l1 - 1, &back), ANS_ERR_ENCODING); \ + CHECK_ST(ans_encode_##NAME(&(OBJ), b2, l1 - 1, &l2), ANS_ERR_ENCODING); \ + uint8_t bad[ANS_ENCODED_MAX]; memcpy(bad, b1, l1); bad[4] ^= 0x7f; \ + CHECK_ST(ans_decode_##NAME(bad, l1, &back), ANS_ERR_ENCODING); \ + memcpy(bad, b1, l1); bad[5] = 9; \ + CHECK_ST(ans_decode_##NAME(bad, l1, &back), ANS_ERR_ENCODING); \ + memcpy(bad, b1, l1); bad[l1] = 0; \ + CHECK_ST(ans_decode_##NAME(bad, l1 + 1, &back), ANS_ERR_ENCODING); \ + } while (0) + RT(reference, ans_reference, g.ref); + RT(action, ans_action, a); + RT(measurement, ans_measurement, m); + RT(state, ans_state, g.s); + RT(verdict, ans_verdict, v); + RT(promotion_record, ans_promotion_record, pr); +#undef RT + /* cross-kind decode refused */ + { ans_action back; CHECK_ST(ans_encode_state(&g.s, b1, sizeof b1, &l1), ANS_OK); + CHECK_ST(ans_decode_action(b1, l1, &back), ANS_ERR_ENCODING); } + /* a decoded reference keeps its digest and its seal */ + { ans_reference back; ans_digest d2; + CHECK_ST(ans_encode_reference(&g.ref, b1, sizeof b1, &l1), ANS_OK); + CHECK_ST(ans_decode_reference(b1, l1, &back), ANS_OK); + CHECK_ST(ans_digest_reference(&back, &d2), ANS_OK); + CHECK(deq(&d2, &g.rd)); CHECK(back.frozen == 1); CHECK_ST(ans_reference_check(&back, &g.rd), ANS_OK); } + /* digest stability and domain separation */ + ans_digest da, db; + CHECK_ST(ans_digest_state(&g.s, &da), ANS_OK); + CHECK_ST(ans_digest_state(&g.s, &db), ANS_OK); + CHECK(deq(&da, &db)); + { ans_state t = g.s; t.last_nis += 1e-9; CHECK_ST(ans_digest_state(&t, &db), ANS_OK); CHECK(!deq(&da, &db)); } + CHECK(!deq(&g.rd, &da)); + /* determinism: the same sequence yields the same final state digest */ + { rig h; mkrig(&h); step(&h, ANS_ACT_EFFECT, 0x20, 0.1); + CHECK_ST(ans_step(&h.ref, &h.rd, &h.s, &a, &h.s, NULL), ANS_OK); + CHECK_ST(ans_measure(&h.ref, &h.rd, &h.s, &m, &h.s, NULL, NULL), ANS_OK); + CHECK_ST(ans_digest_state(&h.s, &db), ANS_OK); CHECK(deq(&da, &db)); } + /* goldens */ + gold("reference", &g.rd, GOLD_REF); + CHECK_ST(ans_digest_action(&a, &d), ANS_OK); gold("action", &d, GOLD_ACT); + CHECK_ST(ans_digest_measurement(&m, &d), ANS_OK); gold("measurement", &d, GOLD_MEAS); + gold("state", &da, GOLD_STATE); + gold("verdict", &v.digest, GOLD_VERD); + gold("promotion", &pr.digest, GOLD_PROMO); +} + +int main(void) +{ + test1_freeze(); + test2_hostile(); + test3_drift_grows(); + test4_fix_restores(); + test5_imu_cannot_restore(); + test6_disagreement(); + test7_refusals(); + test8_promotion(); + test9_encodings(); + test10_self_mod(); + printf("test_ans: %d checks, %d failures: %s\n", g_checks, g_fail, g_fail ? "FAIL" : "PASS"); + return g_fail ? 1 : 0; +} ```