Aureon public MCP server from Aureon-OS main cf35ec95 (PR #224)
Browse filesFiles changed (39)
- .dockerignoreAdded+9
- COVERAGE_PLAN.mdAdded+225
- DockerfileAdded+65
- README.mdAdded+199
- __init__.pyAdded+11
- __main__.pyAdded+4
- alignment_layer.pyAdded+387
- alignment_measure.pyAdded+119
- body.pyAdded+1405
- body_sweep.pyAdded+43
- call_sweep.pyAdded+359
- call_worker.pyAdded+243
- coverage_plan.pyAdded+506
- guard_loader.pyAdded+181
- http_guard.pyAdded+454
- inventory_scan.pyAdded+405
- layers.pyAdded+594
- measure.pyAdded+202
- measurement_stamp.pyAdded+81
- more_layers.pyAdded+632
- paths.pyAdded+50
- pin_blob.pyAdded+350
- protocol_measure.pyAdded+258
- quiet.pyAdded+23
- requirements.txtAdded+7
- server.pyAdded+185
- space.pyAdded+106
- space_measure.pyAdded+240
- stage1_measure.pyAdded+119
- stage1_rest.pyAdded+531
- stage2_arguments.pyAdded+306
- stage2_import_sweep.pyAdded+226
- stage2_layer.pyAdded+782
- surfaces.pyAdded+279
- sweep_guard.pyAdded+516
- sweep_layout.pyAdded+116
- test-requirements.txtAdded+8
- text.pyAdded+26
- tools.pyAdded+805
123456789.env.env.*__pycache__/*.pyc.pytest_cache/*.pem*.keycredentials.jsonsecrets.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225# Public MCP coverage plan
Counts are the pinned `docs/mcp/inventory.json`. A public entry point is a public function or method. Reachable means `public_entry_refusal` returns None, so `body_call` will run it. A listed module or class is not an entry point. The sha256 below is `INVENTORY_SHA256`. A different inventory file is not loaded.
Inventory sha256: `4bc19ea9b5444a7b8a9abbd3fabf635d083bd25bea6c1b2d6eab2605b4f5716b`
Reproduce:
```bashenv -u PYTHONPATH PYTHONPATH=mcp python3.12 -m aureon_public.coverage_plan --checkbash measured/aureon_public_stage1_run.shbash measured/aureon_public_stage2_sweep.shbash measured/aureon_public_call_sweep.shbash measured/aureon_public_protocol_run.shbash measured/aureon_public_space_run.shenv -u PYTHONPATH /tmp/aureon-public-venv/bin/python -m pytest tests/test_aureon_public_mcp.py tests/test_aureon_body.py tests/bio/test_mcp_interior_attribution.py tests/bio/test_mcp_membrane.py tests/bio/test_mcp_transport.py tests/test_aureon_public_alignment.py tests/test_aureon_public_stage1.py tests/test_aureon_public_stage2.py tests/test_aureon_public_protocol.py tests/test_aureon_public_space.py --tb=line```
That pytest command is the gate. It runs in `/tmp/aureon-public-venv`, the venv `measured/aureon_public_stage1_run.sh` creates (`VENV` overrides the path). The file list is `tests/test_aureon_public_mcp.py`, `tests/test_aureon_body.py`, `tests/bio/test_mcp_interior_attribution.py`, `tests/bio/test_mcp_membrane.py`, `tests/bio/test_mcp_transport.py`, `tests/test_aureon_public_alignment.py`, `tests/test_aureon_public_stage1.py`, `tests/test_aureon_public_stage2.py`, `tests/test_aureon_public_protocol.py`, and `tests/test_aureon_public_space.py`. `tests/test_async_socket_isolation.py` is not in the gate list. It imports `pytest_socket`, and `mcp/aureon_public/test-requirements.txt` does not install that plugin.
`--write` rewrites this file from the same function. `measured/aureon_public_stage1_run.sh` installs `mcp/aureon_public/requirements.txt` and `mcp/aureon_public/test-requirements.txt`, then rewrites both `measured/aureon_public_alignment.json` and `measured/aureon_public_stage1.json`. It writes those two files under a temp directory first and copies them into `measured/` only after both stamps have finished. `measurement_stamp` raises `RuntimeError` when `git status --porcelain` is not empty, so the second stamp must not see the first file. `test-requirements.txt` is the test install: pytest, pytest-timeout, flask, pandas, and scipy. It is not the public server runtime. `measured/aureon_public_stage2_sweep.sh` and `measured/aureon_public_call_sweep.sh` copy the checkout with `cp -a` under an ordinary temp parent, place fake `NEXUS-LIVE-FEED-` and `Aureon-Trading--Project-Sero` checkouts beside that copy, block sockets, and rewrite their measured records. Each sweep record names the pin, the `aureon/` tree hash beside that pin, the `aureon_source` kind, and that temp parent. `measured/aureon_public_protocol_run.sh` starts this server over stdio and over Streamable HTTP bound to `127.0.0.1`, with `AUREON_PUBLIC_REQUIRE_PIN=1`. An MCP SDK 1.30.0 client calls `tools/list`, `resources/list`, `prompts/list`, and one `tools/call` (`alignment_consonance_read` with ratio 1.0). The raw pages are `measured/aureon_public_protocol.json`. `measured/aureon_public_space_run.sh` starts `python -m aureon_public.space` with `AUREON_PUBLIC_API_KEY` set and records the same client calling `tools/list` and `tools/call` on `127.0.0.1`. The raw pages are `measured/aureon_public_space.json`. These measured records name `code_commit`, the parent of the commit that contains the record file. A record cannot name the commit that adds the file.
Listed symbols: 20083. Public entry points: 4388. Reachable now: 69. Tested: 69. Refused: 4319. The plan on main recorded 879 reachable. An earlier draft head of the stage-1 PR recorded 89 reachable, before the call sweep. Methods open because a constructor is allowlisted: 16. The refused-imports fence is unchanged.Reachable means `public_entry_refusal` returns None. Tested means a public tool calls that entry point and `tests/test_aureon_public_stage1.py` or `tests/test_aureon_public_stage2.py` exercises the tool. Refused means a public entry point the server will not run. Plan stages 3 and 4 stay closed. The call sweep calls every entry point that was still reachable, with no arguments, and calls each stage-2 entry point again with the real arguments in `stage2_arguments.py`. `SwarmAgent.update` is also called with the hive fixture named below. It refuses one that opens a connection, starts a process, writes outside the sandbox, or loads queen, miner, swarm_motion, inhouse_ai, ollama_config, or an HTTP client. `get_unified_directive` is refused that way. It does not build the queen and miner bridges.
## Stage order
The stage is the inventory safety text, not a new scan.
1. Deterministic read-only. No key, order, live-fetch, process, or write sentence, and the package is not operator-only.2. A process or write sentence, and still no key, order, or live-fetch sentence.3. Operator-scoped, with no pure public row and no key, order, or live-fetch sentence.4. Last. Any key, order, or live-fetch sentence, plus the refused-imports fence. The fence is `_BLOCKED` and `unified_margin_trader`. This run does not add to it and does not import it.
Packages still excluded by `more_layers`: atn, command_centers, conversion, identity, inhouse_ai, miner, monitors, swarm_motion. `generated` left that list because its score model is deterministic and does not fetch. The other exclusions stay.
Within a stage, packages are alphabetical. The first package is `alignment`.Stage 1 is the deterministic read-only packages. This run opens generated and swarm, after alignment. Organism is stage 4 because its join loads the in-house adapter chain.Stage 2 is open. A stage-2 module whose import loads an adapter or an HTTP client, starts a process, or writes outside the sandbox is refused. A stage-2 entry point is refused when the no-argument call or a real-argument call does any of those, or does not finish. `atn` stays excluded. `conversion` has no public function or method and stays excluded.
## Counts
| Stage | Package | Listed | Public entry points | Reachable now | Tested | Refused || ---: | --- | ---: | ---: | ---: | ---: | ---: || 1 | alignment | 36 | 24 | 11 | 11 | 13 || 1 | generated | 8 | 4 | 4 | 4 | 0 || 1 | swarm | 79 | 41 | 15 | 15 | 26 || 2 | atn | 57 | 28 | 0 | 0 | 28 || 2 | cognition | 44 | 14 | 1 | 1 | 13 || 2 | conversion | 170 | 0 | 0 | 0 | 0 || 2 | decoders | 161 | 80 | 4 | 4 | 76 || 2 | evaluation | 20 | 10 | 6 | 6 | 4 || 2 | gates | 24 | 12 | 3 | 3 | 9 || 2 | observer | 104 | 63 | 24 | 24 | 39 || 2 | s51 | 55 | 24 | 1 | 1 | 23 || 3 | accounting | 50 | 0 | 0 | 0 | 0 || 3 | miner | 15 | 0 | 0 | 0 | 0 || 4 | analytics | 464 | 167 | 0 | 0 | 167 || 4 | appliance | 15 | 7 | 0 | 0 | 7 || 4 | approval | 82 | 42 | 0 | 0 | 42 || 4 | autonomous | 1745 | 0 | 0 | 0 | 0 || 4 | bio | 474 | 206 | 0 | 0 | 206 || 4 | bots | 611 | 0 | 0 | 0 | 0 || 4 | bots_intelligence | 234 | 0 | 0 | 0 | 0 || 4 | bridges | 281 | 0 | 0 | 0 | 0 || 4 | briefing | 62 | 34 | 0 | 0 | 34 || 4 | code_architect | 98 | 0 | 0 | 0 | 0 || 4 | command_centers | 260 | 0 | 0 | 0 | 0 || 4 | connectors | 47 | 0 | 0 | 0 | 0 || 4 | core | 986 | 452 | 0 | 0 | 452 || 4 | data_feeds | 251 | 118 | 0 | 0 | 118 || 4 | exchanges | 643 | 0 | 0 | 0 | 0 || 4 | governance | 204 | 105 | 0 | 0 | 105 || 4 | grants | 77 | 44 | 0 | 0 | 44 || 4 | harmonic | 605 | 278 | 0 | 0 | 278 || 4 | identity | 16 | 0 | 0 | 0 | 0 || 4 | inhouse_ai | 145 | 0 | 0 | 0 | 0 || 4 | integrations | 167 | 65 | 0 | 0 | 65 || 4 | intelligence | 597 | 274 | 0 | 0 | 274 || 4 | launch | 97 | 0 | 0 | 0 | 0 || 4 | monitors | 345 | 158 | 0 | 0 | 158 || 4 | observability | 27 | 9 | 0 | 0 | 9 || 4 | operator | 1080 | 0 | 0 | 0 | 0 || 4 | organism | 3 | 1 | 0 | 0 | 1 || 4 | plumber | 497 | 271 | 0 | 0 | 271 || 4 | portals | 74 | 51 | 0 | 0 | 51 || 4 | portfolio | 322 | 0 | 0 | 0 | 0 || 4 | queen | 1348 | 566 | 0 | 0 | 566 || 4 | saas | 83 | 0 | 0 | 0 | 0 || 4 | scanners | 335 | 0 | 0 | 0 | 0 || 4 | search | 21 | 5 | 0 | 0 | 5 || 4 | simulation | 440 | 200 | 0 | 0 | 200 || 4 | strategies | 474 | 0 | 0 | 0 | 0 || 4 | swarm_motion | 49 | 10 | 0 | 0 | 10 || 4 | trading | 2023 | 0 | 0 | 0 | 0 || 4 | unified_margin_trader | 1643 | 0 | 0 | 0 | 0 || 4 | utils | 1162 | 455 | 0 | 0 | 455 || 4 | vault | 418 | 195 | 0 | 0 | 195 || 4 | wisdom | 755 | 375 | 0 | 0 | 375 |
## Fence
These packages are stage 4 because they are on the refused-imports fence or an inventory row says order. `body_call` returns `live_orders: refused` and does not import them.
- `bots`- `bots_intelligence`- `bridges`- `exchanges`- `scanners`- `trading`- `unified_margin_trader`
## Stage 4
`alignment/unified_directive.py` `get_unified_directive` is not a stage-1 tool. Queen is stage 4. Miner is stage 3. `body_call` refuses it now. The no-argument call is in the call sweep.
Calling `get_unified_directive` constructs `UnifiedHarmonicDirective` with auto-wire on. That constructs `QueenAIBridge` and `MinerAIBridge`. Each bridge loads `AureonBrainAdapter` as the reasoning backend when the Ollama switchboard is missing or unhealthy, and each bridge wires itself to a `ThoughtBus`. The call imports `aureon.queen`, `aureon.miner`, and `aureon.swarm_motion`, and it attempted a connection to `127.0.0.1:11434`. The sweep blocked that socket.
## This run
`alignment` stays the first stage-1 package. `get_pillar_alignment` stays, with `auto_load_pillars` false. `get_unified_directive` is not a stage-1 tool. This run opens `generated` and `swarm`. `organism` is not opened.Generated was on the more_layers exclusion list. It is open because `aureon/generated/research_cinema/harmonic_nexus_score_model.py` imports only dataclasses and its module docstring calls it a deterministic helper, not trading authority. The four entry points are `build_default_inputs`, `HarmonicNexusScoreInputs.normalized`, `harmonic_nexus_score`, and `score_breakdown`. `tests/generated/test_harmonic_nexus_score_model.py` shows all-ones inputs score 100.0. That 100 is the weighted sum in that file. It does not score any Aureon or HNC claim and cannot be quoted as evidence.`body_call` refuses `organism/repository_layers.py` `compose_repository_layers`. With the checkout beside `NEXUS-LIVE-FEED-` and `Aureon-Trading--Project-Sero`, that call uses `Path(__file__).parents[3]`, independent of `AUREON_REPOS_ROOT`, and execs those sibling modules outside the pin. One call also loads `core.organism_composition`, and through that `aureon.inhouse_ai.llm_adapter`, `agent_runner`, `orchestrator`, `aureon.ollama_config`, and `aureon.autonomous.aureon_internal_coding_workforce`. `inhouse_ai` stays excluded. Organism reachable is 0.`body_call` refuses `swarm/capability_grid.py` `build_lane`. `build_lane("fintech")` imports `aureon.accounting`, and that package init reaches `aureon.autonomous.aureon_internal_coding_workforce`, which imports `aureon.inhouse_ai` and `aureon.ollama_config`. Swarm reachable is 15.The swarm tools use fixtures from the swarm tests or fixed example arguments. `SwarmAgent.update` uses the first call in `tests/test_swarm_hive.py` `test_agent_keeps_a_normalized_soft_simplex`: agent `a1`, role `research`, actions hold, advance, and retreat, CONTEXT `[0.4, 0.2, -0.1, 0.3, 0.0, 0.1, -0.2, 0.05]`, an empty cluster, and no echo. The function returns None. Classes that need nested agent instances stay off the constructor allowlist: Cluster, Company, Zone, FleadhCompany, VisitorAgent, and WorkerAgent. Name-blocked `run_` entry points stay refused. `SwarmAgent.purity` and `ClusterCoherence.warm` are properties. The worker calls methods, so `body_call` and `dispatch` refuse them. `CausalEchoBus.possibilities` is refused because one call cannot park an ensemble and then read it. `issue_auris_node_receipt` needs a `TrustedAurisNodeResolver` that is not built from JSON. `validate_auris_node_receipt`, `validate_hnc_evidence`, `validate_provider_moment`, `validate_council_receipt`, and `validate_seat_receipt` are refused: the receipt is assembled by the test harness, and the public result cap would drop its fields.Stage 2 tools call through `dispatch`. The inputs are the tests and committed files named on each tool. `atn` stays excluded because its modules load an HTTP client. `conversion` has no public function or method and stays excluded. The constructor allowlist, the `__post_init__` refusal, the `AUREON_PUBLIC_SWEEP` start refusal, and the pin check are unchanged.Import refusals:- `atn/aureon_atn_backtest.py`: module import loads an adapter or http client- `atn/aureon_atn_forensics.py`: module import loads an adapter or http client- `atn/aureon_atn_monitor.py`: module import loads an adapter or http client- `decoders/emerald_spec.py`: module import loads an adapter or http client- `decoders/grail_convergence.py`: module import loads an adapter or http clientImport errors that are not refusals:- `s51/aureon_51.py`: ImportError: Refused imports: aureon.exchanges, aureon.trading, unified_margin_trader, aureon.bots, aureon.bots_intelligence, aureon.bridges, aureon.scanners. No keys are present. Refused: aureon.exchanges- `s51/aureon_51_live.py`: ModuleNotFoundError: No module named 'websockets'Call refusals from the sweep:- `alignment/unified_directive.py` `get_unified_directive`: call loads a banned chain or opens a connection- `evaluation/measured_proof.py` `self_coder_report`: call loads a banned chain or opens a connection. The same call started a process. The sweep blocked it.- `gates/panel.py` `auris_panel`: call loads a banned chain or opens a connection- `gates/panel.py` `build_vault`: call loads a banned chain or opens a connection- `gates/switchboard.py` `read_organism`: call loads a banned chain or opens a connectionThese five were reachable and had no tool. `body_call` and `dispatch` refuse them. The constructor allowlist is unchanged.- `decoders/book_of_ur.py` `test_phi_resonance_me`: untested stage-2 entry point is not called. The argument is a SumerianMe. That class is not on the constructor allowlist, so the public server does not build one. The sweep uses the catalog entry ENSHIP from aureon/decoders/book_of_ur.py.- `observer/momentum.py` `set_momentum_tracker`: untested stage-2 entry point is not called. The argument is a MomentumTracker. The class is not on the constructor allowlist. The sweep constructs an empty tracker inside the worker.- `observer/predictor.py` `make_predictor`: untested stage-2 entry point is not called. The argument is a HarmonicObserver. The class is not on the constructor allowlist. The sweep uses the construction in tests/observer/test_predictor_contract.py: trace_interval_s 1.0 and publish_to_bus false.- `observer/wave_predictor.py` `make_predictor`: untested stage-2 entry point is not called. The argument is a WavePredictor. The class is not on the constructor allowlist. The sweep constructs an empty predictor inside the worker.- `observer/wave_predictor.py` `set_wave_predictor`: untested stage-2 entry point is not called. The argument is a WavePredictor. The class is not on the constructor allowlist. The sweep constructs an empty predictor inside the worker.## Count reconciliation
Main `c1ae468d` recorded reachable 85. Stage 1 was 39 (alignment 11, generated 4, swarm 24). Stage 2 was 46 (atn 0, cognition 1, conversion 0, decoders 5, evaluation 7, gates 3, observer 29, s51 1). 39 + 46 = 85. Tested on that main was the 29 stage-1 tool entry points below. Stage 2 tested was 0. Registering a tool does not add a reachable row. The tool calls an entry point that was already reachable.Stage 1 reachable now: 30. Stage 2 reachable now: 39. 30 + 39 = 69.Stage 1 tested now: 30. Stage 2 tested now: 39. 30 + 39 = 69.Every stage-1 entry point that was tested on main is still tested. None dropped out:No stage-1 tested entry point dropped out.- `alignment/harmonic_resonance.py` `HarmonicAnalysis.to_dict`- `alignment/harmonic_resonance.py` `analyse_frequency_harmony`- `alignment/harmonic_resonance.py` `compute_phase_coherence`- `alignment/harmonic_resonance.py` `compute_signal_consensus`- `alignment/harmonic_resonance.py` `consonance_score`- `alignment/harmonic_resonance.py` `derive_phase`- `alignment/harmonic_resonance.py` `full_harmonic_analysis`- `alignment/harmonic_resonance.py` `geometric_mean`- `alignment/pillar_alignment.py` `AlignmentCycleResult.to_dict`- `alignment/pillar_alignment.py` `get_pillar_alignment`- `alignment/unified_directive.py` `MasterDirective.to_dict`- `generated/research_cinema/harmonic_nexus_score_model.py` `HarmonicNexusScoreInputs.normalized`- `generated/research_cinema/harmonic_nexus_score_model.py` `build_default_inputs`- `generated/research_cinema/harmonic_nexus_score_model.py` `harmonic_nexus_score`- `generated/research_cinema/harmonic_nexus_score_model.py` `score_breakdown`- `swarm/agent.py` `SwarmAgent.propose`- `swarm/agent.py` `SwarmAgent.substrate`- `swarm/agent.py` `SwarmAgent.to_dict`- `swarm/agent.py` `SwarmAgent.update`- `swarm/coherence.py` `ClusterCoherence.gamma`- `swarm/coherence.py` `ClusterCoherence.to_dict`- `swarm/druidic_council.py` `CouncilReceipt.to_dict`- `swarm/druidic_council.py` `SeatReceipt.to_dict`- `swarm/druidic_council.py` `build_seat_receipt`- `swarm/druidic_council.py` `voice_for_gamma`- `swarm/fleadh.py` `steer_flow`- `swarm/memory_bus.py` `CausalEchoBus.echo`- `swarm/memory_bus.py` `CausalEchoBus.to_dict`- `swarm/queen_gate.py` `Actualization.to_dict`- `swarm/steering.py` `SteeringField.steer`Stage 1 has no reachable entry point left untested.Stage 2 reachable fell by 7, from 46 to 39, on the stage-2 run. The call sweep refused `self_coder_report`. Five reachable entry points had no tool. `log_blocked_fallback` would write a fallback log for an event that did not happen, so `body_call` refuses it. This follow-up then closes the 10 stage-1 points that were reachable and not tested. Nine are refused. `SwarmAgent.update` is tested on the hive fixture.- `evaluation/measured_proof.py` `self_coder_report`: call loads a banned chain or opens a connection.- `decoders/book_of_ur.py` `test_phi_resonance_me`: untested stage-2 entry point is not called.- `observer/momentum.py` `set_momentum_tracker`: untested stage-2 entry point is not called.- `observer/predictor.py` `make_predictor`: untested stage-2 entry point is not called.- `observer/wave_predictor.py` `make_predictor`: untested stage-2 entry point is not called.- `observer/wave_predictor.py` `set_wave_predictor`: untested stage-2 entry point is not called.- `observer/live_data_policy.py` `log_blocked_fallback`: fallback log is not emitted for an event that did not happen.- `swarm/agent.py` `SwarmAgent.purity`: property is not called; the worker calls methods.- `swarm/auris_node_receipts.py` `issue_auris_node_receipt`: trusted resolver is not built from JSON.- `swarm/auris_node_receipts.py` `validate_auris_node_receipt`: receipt is assembled by the test harness; the public result cap would drop its fields.- `swarm/auris_node_receipts.py` `validate_hnc_evidence`: receipt is assembled by the test harness; the public result cap would drop its fields.- `swarm/auris_node_receipts.py` `validate_provider_moment`: receipt is assembled by the test harness; the public result cap would drop its fields.- `swarm/capability_grid.py` `build_lane`: stage 4 entry point is not called.- `swarm/coherence.py` `ClusterCoherence.warm`: property is not called; the worker calls methods.- `swarm/druidic_council.py` `validate_council_receipt`: receipt is assembled by the test harness; the public result cap would drop its fields.- `swarm/druidic_council.py` `validate_seat_receipt`: receipt is assembled by the test harness; the public result cap would drop its fields.- `swarm/memory_bus.py` `CausalEchoBus.possibilities`: one call cannot park an ensemble and read it.Main `cf43882e` recorded reachable 78 and tested 68. This follow-up refuses nine stage-1 entry points and tests `SwarmAgent.update`. Reachable and tested are both 69. 30 + 39 = 69.
The pin stays `8aa6a2d971cc529484e2a5e261e28afafab4e4f4`. The alignment modules at this checkout match that pin, so the tools do not need a newer commit. `GUARD_BLOB` and `INVENTORY_SHA256` are unchanged.
## MCP SDK
This server imports `FastMCP` from `mcp.server.fastmcp` and passes `host`, `port`, and `streamable_http_path` to that constructor. The requirement is `mcp==1.30.0,<2` in `mcp/aureon_public/requirements.txt` and `mcp/pyproject.toml`. That specifier matches 1.30.0 and excludes every 2.x release. Migration to SDK v2 is a later decision.
The claim that official Python SDK v2 renamed `FastMCP` to `MCPServer` was checked against the published package and the v2 source. The claim is true.
- PyPI project `mcp`: `info.version` is 2.3.0. The newest 1.x release is 1.30.0. https://pypi.org/pypi/mcp/json- Release v2.0.0, published 28 July 2026, says `FastMCP` is now `MCPServer`, v1.x is maintenance-only on branch `v1.x`, and a project that is not migrating should keep a `<2` upper bound, for example `mcp>=1.28,<2`. https://github.com/modelcontextprotocol/python-sdk/releases/tag/v2.0.0- Migration guide, section `FastMCP` renamed to `MCPServer`: `from mcp.server.fastmcp import FastMCP` becomes `from mcp.server.mcpserver import MCPServer`. https://py.sdk.modelcontextprotocol.io/v2/migration/- Tag v2.0.0 and tag v2.3.0 `src/mcp/server/__init__.py` export `MCPServer` from `.mcpserver`. https://github.com/modelcontextprotocol/python-sdk/blob/v2.3.0/src/mcp/server/__init__.py- Tag v2.3.0 `src/mcp/server/mcpserver/server.py` defines `class MCPServer`. `MCPServer.__init__` takes no `host`, `port`, or `streamable_http_path`. Those arguments are on `run(transport="streamable-http")`. The default name when none is passed is `mcp-server`. `instructions` is no longer the second positional parameter. https://github.com/modelcontextprotocol/python-sdk/blob/v2.3.0/src/mcp/server/mcpserver/server.py- `src/mcp/server/fastmcp/__init__.py` on tag v2.3.0 is not published. The raw URL returns HTTP 404. https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/v2.3.0/src/mcp/server/fastmcp/__init__.py- v1 documentation stays at https://py.sdk.modelcontextprotocol.io/v1/
The same v2.0.0 notes also replace `ClientSession` plus the transport clients with `Client`, and the v2.3.0 constructor no longer accepts `host`, `port`, or `streamable_http_path`. This server still passes those three to `FastMCP`, and the measured client still uses `ClientSession`. Staying on 1.30.0 keeps that call shape.
The protocol proof is the stdio session and the Streamable HTTP session bound to `127.0.0.1`. The Space scaffold is `mcp/aureon_public/Dockerfile` and `python -m aureon_public.space`. It is not deployed. `AUREON_PUBLIC_API_KEY` enforces a bearer token. `AUREON_PUBLIC_OPEN=1` serves the read-only surface with no key. With neither, Streamable HTTP binds to `127.0.0.1` only. Stages 3 and 4 stay closed.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# Hugging Face Space scaffold for aureon-public. This image is not deployed# and this file does not create a Hugging Face repository.## Build from this directory:# docker build -f Dockerfile -t aureon-public .## The runtime install matches measured/aureon_public_stage1_run.sh:# requirements.txt (mcp==1.30.0,<2 and the aureon pin), then the mcp package# with --no-deps. test-requirements.txt is not installed.## No API key is baked in. AUREON_PUBLIC_API_KEY is a runtime secret. The image# sets AUREON_PUBLIC_OPEN=1 so the read-only surface can bind on the Space port# when that secret is absent. AUREON_PUBLIC_SWEEP is not set.
FROM python:3.12-slim-bookworm
RUN apt-get update \ && apt-get install -y --no-install-recommends git ca-certificates \ && rm -rf /var/lib/apt/lists/*
# Full history of main so git rev-parse of the aureon pin still resolves.# A shallow clone would omit that commit.# AUREON_REF defaults to the merge commit of #225. That tree contains the# aureon pin. Do not set cf43882e as a standing default.ARG AUREON_REPO=https://github.com/RA-CONSULTING/Aureon-OS.gitARG AUREON_REF=0390194b80cddb66c8cfd052efe3aa4f9d1545d6# The first Hugging Face build log must show the AUREON_REF build arg.RUN test -n "$AUREON_REF" \ && echo "AUREON_REF=${AUREON_REF}" \ && git clone --branch main --single-branch "$AUREON_REPO" /opt/aureon-os \ && git -C /opt/aureon-os checkout "$AUREON_REF" \ && git config --system --add safe.directory /opt/aureon-os
# Overlay this directory so the image runs the scaffold beside the Dockerfile,# including files that are not on AUREON_REF yet. The overlay is the public# package only. It does not replace aureon/ and it does not add a key.COPY . /opt/aureon-os/mcp/aureon_public/
WORKDIR /opt/aureon-osRUN python -m pip install --no-cache-dir -U pip \ && python -m pip install --no-cache-dir -r mcp/aureon_public/requirements.txt \ && python -m pip install --no-cache-dir -e mcp --no-deps \ && rm -rf /root/.cache/pip
RUN useradd --create-home --uid 1000 aureon \ && mkdir -p /tmp/aureon-public-space \ && chown -R aureon:aureon /tmp/aureon-public-spaceUSER aureonWORKDIR /tmp/aureon-public-space
# Listen on 0.0.0.0. The MCP SDK turns DNS-rebinding protection on when the# process binds 127.0.0.1, and then answers 421 to Host: *.hf.space.# Open mode and keyed mode on the Space stay on 0.0.0.0. A process with# neither AUREON_PUBLIC_OPEN=1 nor AUREON_PUBLIC_API_KEY still refuses that bind.ENV AUREON_PUBLIC_REQUIRE_PIN=1 \ AUREON_OBSERVER_MODE=dry_run \ AUREON_PUBLIC_OPEN=1 \ AUREON_PUBLIC_HOST=0.0.0.0 \ AUREON_PUBLIC_MAX_INFLIGHT=4 \ PORT=7860 \ PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1
EXPOSE 7860CMD ["python", "-m", "aureon_public.space"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199---title: aureon-publicemoji: "🔷"colorFrom: bluecolorTo: graysdk: dockerapp_port: 7860pinned: falselicense: mit---
# aureon-public
This is a partial release covering stages 1 and 2 of 4. Stages 3 and 4 stay closed. That includes miner, queen, exchanges, orders, and keys. `COVERAGE_PLAN.md` records the counts: listed symbols 20083, public entry points 4388, reachable now 69, tested 69, refused 4319. Stage 1 reachable now is 30 and stage 1 tested now is 30. Stage 2 reachable now is 39 and stage 2 tested now is 39. 30 + 39 = 69 reachable. 30 + 39 = 69 tested.
Miner is stage 3: 15 listed, 0 public entry points, reachable 0, tested 0, refused 0. Queen is stage 4: 1348 listed, 566 public entry points, reachable 0, tested 0, refused 566. Exchanges are stage 4: 643 listed, 0 public entry points, reachable 0, tested 0, refused 0. Accounting is stage 3 with reachable 0. Trading is stage 4 with reachable 0.
The measured tests are the call sweep. It calls every entry point that was still reachable, with no arguments, and calls each stage-2 entry point again with the real arguments in `stage2_arguments.py`. Connections, process starts, and writes outside the sandbox are logged: the committed record says sockets blocked, processes blocked, and writes outside the sandbox blocked. A call that opens a connection, starts a process, writes outside the sandbox, or loads queen, miner, swarm_motion, inhouse_ai, ollama_config, or an HTTP client is refused. Other arguments have not been swept.
The Space entry is `python -m aureon_public.space`. It sets `AUREON_PUBLIC_REQUIRE_PIN=1` and `AUREON_OBSERVER_MODE=dry_run`, and it refuses to start when `AUREON_PUBLIC_SWEEP` is set. The image installs `requirements.txt` (`mcp==1.30.0,<2` and aureon pin `8aa6a2d971cc529484e2a5e261e28afafab4e4f4`) and then the mcp package with `--no-deps`, the same runtime install as `measured/aureon_public_stage1_run.sh`. The image does not install test requirements and does not contain `AUREON_PUBLIC_API_KEY`.
`AUREON_PUBLIC_OPEN=1` is set in the image, so the read-only stage-1 and stage-2 surface is served on port 7860 without a key. Set `AUREON_PUBLIC_API_KEY` in the Space secret settings to require `Authorization: Bearer`. A missing or wrong bearer then receives HTTP 401. With neither the key nor `AUREON_PUBLIC_OPEN=1`, the process binds to `127.0.0.1` only and refuses `0.0.0.0`. The image keeps `AUREON_PUBLIC_HOST=0.0.0.0` whenever it is in open mode or keyed mode. The MCP SDK turns DNS-rebinding protection on for a `127.0.0.1` bind and then answers HTTP 421 to `Host: *.hf.space`. A `0.0.0.0` bind accepts that Host header, which is what Hugging Face's proxy sends. The public HTTP server uses MCP SDK 1.30 stateless JSON responses (`stateless_http` and `json_response`). `GET /mcp` returns HTTP 405. That long-lived event stream is not used, and it does not take an in-flight call slot. `AUREON_PUBLIC_MAX_INFLIGHT` (default 4, the same size as the public worker pool) caps concurrent in-flight POST `/mcp` requests. Each tool call starts a worker process. A POST over that cap returns HTTP 503 with `error` `busy`. `AUREON_PUBLIC_RATE_LIMIT` (default 120) and `AUREON_PUBLIC_RATE_WINDOW_S` (default 60) limit requests per client. `AUREON_PUBLIC_TRUSTED_PROXY_HOPS` defaults to 1. When `X-Forwarded-For` is present and has at least that many values, the client is the value that many hops from the right. With the default, that is the last value, including a header whose only value is the client address. A fake first hop in front of that value does not get its own bucket. Zero trusted proxy hops ignores the header and uses the socket peer. The real Hugging Face header shape has to be confirmed on the private Space before this default is treated as settled. `AUREON_PUBLIC_FORWARDED_DIAG=1` records hop count and whether each hop is an IPv4 address, an IPv6 address, or something else. It does not store the addresses. Open mode buckets by that address only. A bearer is the client id only when it matches `AUREON_PUBLIC_API_KEY`. The tracked-id table is capped by `AUREON_PUBLIC_RATE_MAX_CLIENTS` (default 4096) and drops expired windows. `AUREON_PUBLIC_MAX_BODY_BYTES` (default 1048576) counts bytes as they arrive, including a chunked body with no content-length. Every body message is counted until `more_body` is false or the client disconnects. Empty chunks do not stop that count, and the unread remainder is not passed through. `AUREON_PUBLIC_REQUEST_TIMEOUT_S` (default 30) limits a POST and also bounds that body read. A rate limit returns HTTP 429. A body over the cap returns HTTP 413. An idle or unfinished body returns HTTP 408 with `error` `body_timeout`. A POST that passes the timeout returns HTTP 504.
This scaffold is not deployed and it does not create a Hugging Face repository. The measured session was taken without Docker. `.github/workflows/aureon-public-space.yml` builds this image on a pull request and runs `python -m aureon_public.space --check`. `AUREON_REF` defaults to `0390194b80cddb66c8cfd052efe3aa4f9d1545d6`, the merge commit of #225. That tree contains the aureon pin. Do not point `AUREON_REF` at cf43882e as a standing default. The first Hugging Face build log must show the `AUREON_REF` build arg. Uvicorn is started with `proxy_headers` off and an empty `forwarded_allow_ips`, so `X-Forwarded-For` is read only by this server's own middleware.
MCP lets outside models call Aureon's tools. No outside model or API becomes Aureon's reasoning. The cognition runs in Aureon's own code.
This process is a read-only FastMCP server named `aureon-public`. It exposes the milestone-1 tools, resources, and prompts. It does not place orders, read keys, start circulation, self-code, self-repair, or write the repository or `state/`.
`aureon` is pinned to commit `8aa6a2d971cc529484e2a5e261e28afafab4e4f4`, the same pin as the Hugging Face Spaces. A local checkout run uses its own commit, not the pin. The MCP SDK requirement is `mcp==1.30.0,<2` in `requirements.txt` and `pyproject.toml`. That installs 1.30.0 and excludes every 2.x release. This server imports `FastMCP` from `mcp.server.fastmcp`. The check that MCP 2 renamed that class to `MCPServer` is in `COVERAGE_PLAN.md`, with the sources. Migration to SDK v2 is a later decision.
Any public hosting, including this aureon-public Space scaffold, must set `AUREON_PUBLIC_REQUIRE_PIN=1`. That refuses to start unless `aureon_source` is kind `pinned` at `8aa6a2d971cc529484e2a5e261e28afafab4e4f4`. Local runs of `python -m aureon_public` leave the variable unset and keep the visible `aureon_source` label. `python -m aureon_public.space` calls `enforce_public_pin()` before it binds.
The operator process is separate: `python -m aureon_operator`. It stays off unless `AUREON_OPERATOR_MCP=1`, speaks stdio only, and refuses live orders. It does not import `aureon.trading` or the other blocked packages.
`repo_root()` and `aureon_source()` raise `FileNotFoundError` when the process is not inside a checkout that contains `huggingface/hnc-field/guard.py` and `aureon/core/hnc_field.py`. This server needs that checkout. It does not invent a 'no checkout' status.
A layer counts as full depth only where its real entry points are called.Each figure is reachable public functions and methods out of the public functions and methods in the pinned `docs/mcp/inventory.json`.
| Package | Reachable | Public entry points || --- | ---: | ---: || accounting | 0 | 0 || alignment | 11 | 24 || analytics | 0 | 167 || appliance | 0 | 7 || approval | 0 | 42 || atn | 0 | 28 || autonomous | 0 | 0 || bio | 0 | 206 || bots | 0 | 0 || bots_intelligence | 0 | 0 || bridges | 0 | 0 || briefing | 0 | 34 || code_architect | 0 | 0 || cognition | 1 | 14 || command_centers | 0 | 0 || connectors | 0 | 0 || conversion | 0 | 0 || core | 0 | 452 || data_feeds | 0 | 118 || decoders | 4 | 80 || evaluation | 6 | 10 || exchanges | 0 | 0 || gates | 3 | 12 || generated | 4 | 4 || governance | 0 | 105 || grants | 0 | 44 || harmonic | 0 | 278 || identity | 0 | 0 || inhouse_ai | 0 | 0 || integrations | 0 | 65 || intelligence | 0 | 274 || launch | 0 | 0 || miner | 0 | 0 || monitors | 0 | 158 || observability | 0 | 9 || observer | 24 | 63 || operator | 0 | 0 || organism | 0 | 1 || plumber | 0 | 271 || portals | 0 | 51 || portfolio | 0 | 0 || queen | 0 | 566 || s51 | 1 | 24 || saas | 0 | 0 || scanners | 0 | 0 || search | 0 | 5 || simulation | 0 | 200 || strategies | 0 | 0 || swarm | 15 | 41 || swarm_motion | 0 | 10 || trading | 0 | 0 || unified_margin_trader | 0 | 0 || utils | 0 | 455 || vault | 0 | 195 || wisdom | 0 | 375 |
The extra package tools are helpers. A helper call is not that layer's cognition.
The order for opening the rest of the inventory is `COVERAGE_PLAN.md`. Alignment is the first package in that order.
`body_call` runs one inventoried function or method. `body_surface` reads a module or class and does not construct it. `body_depth` reports the same ratio as this table. `body_registry` names the servers. The operator tool is `body_call_operator`. Live orders stay refused. A checkout file is imported only when its git blob matches pin `8aa6a2d9`. The plan and the call rules are in `docs/mcp/REGISTRY.md`.
Licence: MIT, the same licence as the repository `LICENSE`.
## Two brain paths
`hnc_reality_step` takes `enable_multiverse` and reports that value in the output.
The class default `HarmonicRealityField()` sets `enable_multiverse=True` (multiverse on). This tool's default is that class default.
Do not mix the two committed paths in `huggingface/hnc-field/replay/brain.json`:
| Path | `enable_multiverse` | Coherence in the file || --- | --- | --- || Class default, multiverse on (`multiverse_extension`) | `true` | `0.857719007627168` || Multiverse off (`hnc`) | `false` | `0.9331334813083556` |
Those figures are cited from that file. They are not a track record. Trade readiness is HOLD.
## Which Auris
Four meanings stay separate.
- The conjecture is the five symbolic-life markers in `LambdaEngine`. It is not called.- The nine nodes are `QueenHiveMind.read_auris_nodes` and `AURIS_NODES`. That is `auris_nodes` and `aureon://auris/nodes`.- The persona on `QueenHiveMind` is not scored.- The coherence evaluator is `QueenHiveMind.get_auris_coherence`. That is `auris_coherence`.
Only the nine nodes and `get_auris_coherence` are real functions exposed here. If any of the nine nodes has no reading, `auris_coherence` returns status `no_data`, coherence null, and the missing node names. The Auris-to-Lambda link is HOLD.
`lambda_engine_step` returns status `unavailable` when readings are missing or fewer than two. It does not fill the result with 0.
## Install
From a checkout of this branch:
```bashpython3 -m venv .venv-aureon-publicsource .venv-aureon-public/bin/activatepip install -e mcp```
`pip install -e mcp` installs this package and the pinned `aureon` commit. The install is editable so the server can still see `huggingface/` replay files in the checkout.
## Run
stdio, which is what desktop clients use:
```bashpython -m aureon_public```
Optional streamable HTTP on `127.0.0.1:8077` at path `/mcp`:
```bashpython -m aureon_public --transport streamable-http --host 127.0.0.1 --port 8077```
The HTTP URL is `http://127.0.0.1:8077/mcp`.
## Claude Desktop
Put this in the Claude Desktop MCP config. Use the venv interpreter and the checkout path.
```json{ "mcpServers": { "aureon-public": { "command": "/absolute/path/to/.venv-aureon-public/bin/python", "args": ["-m", "aureon_public"] } }}```
## Cursor
The same stdio block goes in Cursor's MCP settings (`mcp.json`):
```json{ "mcpServers": { "aureon-public": { "command": "/absolute/path/to/.venv-aureon-public/bin/python", "args": ["-m", "aureon_public"] } }}```
## Any other MCP client
Any client that speaks MCP stdio can use the same command. A client that speaks streamable HTTP can use `http://127.0.0.1:8077/mcp` after the HTTP command above. No API key is read. No outside model becomes the reasoning: the client only receives the tool results computed in this process.
## What is not on this server
Orders, exchange keys, `aureon.exchanges`, `aureon.trading`, `unified_margin_trader`, `aureon.bots`, `aureon.bots_intelligence`, `aureon.bridges`, `aureon.scanners`, circulation start, self-code, and self-repair are not tools. The operator Flask routes in `aureon/bio/mcp_transport.py` are a different process and are not widened here.1234567891011"""Public read-only MCP server. Outside models call these tools. They do not become the reasoning."""
__all__ = ["SERVER_INSTRUCTIONS"]
SERVER_INSTRUCTIONS = ( "MCP lets outside models call Aureon's tools. " "No outside model or API becomes Aureon's reasoning. " "The cognition runs in Aureon's own code. " "This server is read-only. It does not place orders, read keys, start circulation, " "self-code, self-repair, or write the repository or state/.")1234from aureon_public.server import main
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387"""Alignment entry points. Calls go through dispatch, so the pin and the fence stay.
Fixtures are the inputs in tests/stress/stress_test_inhouse_ai.py test_harmonic_math.No formula was added. A missing or non-finite input is unavailable."""
from __future__ import annotations
import jsonfrom typing import Any
from aureon_public.body import _unavailable, dispatchfrom aureon_public.quiet import quietfrom aureon_public.tools import _finite
# Inputs copied from tests/stress/stress_test_inhouse_ai.py::test_harmonic_math.FIXTURE_SOURCE = "tests/stress/stress_test_inhouse_ai.py::test_harmonic_math"FIXTURE_NOTE = ( "Fixed fixture from tests/stress/stress_test_inhouse_ai.py::test_harmonic_math. " "Not a live market reading and not a lighthouse reading.")SPLIT_SIGNALS = ["BUY", "BUY", "SELL", "SELL", "NEUTRAL", "NEUTRAL"]AGREE_SIGNALS = ["BUY", "BUY", "BUY", "BUY", "BUY", "BUY"]ALIGNED_PHASES = [0.0, 0.0, 0.0]PILLAR_FREQUENCIES = { "Nexus": 432.0, "Omega": 432.0, "Infinite": 528.0, "Piano": 396.0, "QGITA": 528.0, "Auris": 741.0,}PERFECT_STACK = [ { "pillar": f"P{index}", "signal": "BUY", "confidence": 0.95, "coherence": 0.96, "frequency_hz": 528.0, } for index in range(6)]GEOMETRIC_ONES = [1.0, 1.0, 1.0, 1.0]
def _loads(text: str, kind: type) -> Any | str: try: loaded = json.loads(text) except json.JSONDecodeError: return "arguments are not JSON" if not isinstance(loaded, kind): return "arguments have the wrong shape" return loaded
def _call(module: str, symbol: str, arguments: dict[str, Any]) -> str: return dispatch(module, symbol, arguments, server="public")
def label_result(text: str, source: str, note: str) -> str: """Attach input_source and input_note to a tool result."""
try: body = json.loads(text) except json.JSONDecodeError: return text if not isinstance(body, dict): return text body["input_note"] = note body["input_source"] = source return json.dumps(body, ensure_ascii=False, allow_nan=False, sort_keys=True)
def _annotate(text: str, used_fixture: bool) -> str: """Mark a default-fixture result so scores are not read as a live reading."""
if not used_fixture: return text return label_result(text, FIXTURE_SOURCE, FIXTURE_NOTE)
DEFAULTS_NOTE = "These fields are the dataclass defaults, not a reading."DERIVE_NOTE = ( "528 Hz is FUNDAMENTAL_HZ and BUY is the fixed example branch in derive_phase. " "They are fixed example arguments, not a reading.")
@quietdef alignment_signal_consensus(signals_json: str = "") -> str: """compute_signal_consensus. Provenance: cited.
The default list is the three-way split in test_harmonic_math. That fixture is not a live market reading and not a lighthouse reading. No pillar agent is built.
Args: signals_json: JSON list of signal names. Empty uses the split fixture. Label: cited. """
raw = signals_json.strip() or json.dumps(SPLIT_SIGNALS) parsed = _loads(raw, list) if isinstance(parsed, str): return _unavailable(parsed) if not parsed or not all(isinstance(item, str) for item in parsed): return _unavailable("signals must be a non-empty list of strings") return _annotate( _call( "alignment/harmonic_resonance.py", "compute_signal_consensus", {"signals": parsed}, ), parsed == SPLIT_SIGNALS, )
@quietdef alignment_consonance_read(ratio: float = 1.0) -> str: """consonance_score. Provenance: cited.
This is the inventory entry point, called through the pin check. The helper alignment_consonance is a separate tool and is not this call. The default ratio 1.0 is unison in test_harmonic_math. That fixture is not a live market reading and not a lighthouse reading.
Args: ratio: Frequency ratio. The default 1.0 is unison in test_harmonic_math. Label: cited. """
number = _finite(ratio) if number is None: return _unavailable("ratio is missing") return _annotate( _call("alignment/harmonic_resonance.py", "consonance_score", {"ratio": number}), number == 1.0, )
@quietdef alignment_frequency_harmony(frequencies_json: str = "") -> str: """analyse_frequency_harmony. Provenance: cited.
fundamental_hz is omitted, so the function uses its own FUNDAMENTAL_HZ. The default map is the six pillar frequencies in test_harmonic_math. That fixture is not a live market reading and not a lighthouse reading.
Args: frequencies_json: JSON object of name to Hz. Empty uses that map. Label: cited. """
raw = frequencies_json.strip() or json.dumps(PILLAR_FREQUENCIES) parsed = _loads(raw, dict) if isinstance(parsed, str): return _unavailable(parsed) frequencies: dict[str, float] = {} for key, value in parsed.items(): number = _finite(value) if number is None: return _unavailable(f"{key} is not a frequency") frequencies[str(key)] = number return _annotate( _call( "alignment/harmonic_resonance.py", "analyse_frequency_harmony", {"pillar_frequencies": frequencies}, ), frequencies == PILLAR_FREQUENCIES, )
@quietdef alignment_phase_coherence(phases_json: str = "") -> str: """compute_phase_coherence. Provenance: cited.
The default phases are the aligned triple in test_harmonic_math. That fixture is not a live market reading and not a lighthouse reading.
Args: phases_json: JSON list of radians. Empty uses that triple. Label: cited. """
raw = phases_json.strip() or json.dumps(ALIGNED_PHASES) parsed = _loads(raw, list) if isinstance(parsed, str): return _unavailable(parsed) phases: list[float] = [] for value in parsed: number = _finite(value) if number is None: return _unavailable("phases must be numbers") phases.append(number) return _annotate( _call( "alignment/harmonic_resonance.py", "compute_phase_coherence", {"phases_rad": phases}, ), phases == ALIGNED_PHASES, )
@quietdef alignment_derive_phase(frequency_hz: float = 528.0, t: float = 0.0, signal: str = "BUY") -> str: """derive_phase. Provenance: cited.
528 Hz is FUNDAMENTAL_HZ in harmonic_resonance.py. t is 0 so the drift term is zero. BUY is the fixed example branch in derive_phase. Those defaults are not a reading. BUY, SELL, and any other string are the branches already in derive_phase.
Args: frequency_hz: Pillar frequency in Hz. Label: cited, derive_phase. t: Time in seconds. Label: cited, derive_phase. signal: BUY, SELL, or another string. Label: cited, derive_phase. """
frequency = _finite(frequency_hz) moment = _finite(t) if frequency is None or moment is None: return _unavailable("frequency_hz or t is missing") if not isinstance(signal, str) or not signal.strip(): return _unavailable("signal is missing") text = _call( "alignment/harmonic_resonance.py", "derive_phase", {"frequency_hz": frequency, "t": moment, "signal": signal}, ) if frequency == 528.0 and moment == 0.0 and signal == "BUY": return label_result(text, "aureon.alignment.harmonic_resonance.derive_phase", DERIVE_NOTE) return text
@quietdef alignment_geometric_mean(values_json: str = "") -> str: """geometric_mean. Provenance: cited.
The default is the four ones in test_harmonic_math. That fixture is not a live market reading and not a lighthouse reading.
Args: values_json: JSON list of numbers. Empty uses that list. Label: cited. """
raw = values_json.strip() or json.dumps(GEOMETRIC_ONES) parsed = _loads(raw, list) if isinstance(parsed, str): return _unavailable(parsed) values: list[float] = [] for value in parsed: number = _finite(value) if number is None: return _unavailable("values must be numbers") values.append(number) return _annotate( _call("alignment/harmonic_resonance.py", "geometric_mean", {"values": values}), values == GEOMETRIC_ONES, )
@quietdef alignment_full_analysis(pillar_results_json: str = "", t: float = 0.0) -> str: """full_harmonic_analysis. Provenance: cited.
t is passed, so the function does not read the clock. The default stack is the perfect six-pillar stack in test_harmonic_math, including frequency_hz 528. lighthouse_cleared, dominant_signal, and alignment_score from that fixture are not a live market reading and not a lighthouse reading.
Args: pillar_results_json: JSON list of pillar result objects. Empty uses that stack. Label: cited. t: Time passed to full_harmonic_analysis. Label: cited. """
moment = _finite(t) if moment is None: return _unavailable("t is missing") raw = pillar_results_json.strip() or json.dumps(PERFECT_STACK) parsed = _loads(raw, list) if isinstance(parsed, str): return _unavailable(parsed) if not all(isinstance(item, dict) for item in parsed): return _unavailable("pillar_results must be a list of objects") return _annotate( _call( "alignment/harmonic_resonance.py", "full_harmonic_analysis", {"pillar_results": parsed, "t": moment}, ), moment == 0.0 and parsed == PERFECT_STACK, )
@quietdef alignment_harmonic_to_dict() -> str: """HarmonicAnalysis.to_dict on the dataclass defaults. Provenance: cited.
The class has no constructor body. Defaults are the literals in the class. lighthouse_cleared false and dominant_signal NEUTRAL are those defaults, not a reading. No pillar agent is built.
Args: none: This tool takes no inputs. Label: cited, HarmonicAnalysis.to_dict. """
return label_result( _call("alignment/harmonic_resonance.py", "HarmonicAnalysis.to_dict", {}), "aureon.alignment.harmonic_resonance.HarmonicAnalysis", DEFAULTS_NOTE, )
@quietdef alignment_cycle_to_dict(cycle_id: str = "fixed", timestamp: float = 0.0) -> str: """AlignmentCycleResult.to_dict with a fixed id and timestamp. Provenance: cited.
The dataclass defaults would call uuid and the clock. Those arguments are passed so this call does not. Other fields stay the dataclass defaults and are not a reading.
Args: cycle_id: Passed as the constructor cycle_id. Label: cited. timestamp: Passed as the constructor timestamp. Label: cited. """
moment = _finite(timestamp) if moment is None or not isinstance(cycle_id, str) or not cycle_id: return _unavailable("cycle_id or timestamp is missing") text = _call( "alignment/pillar_alignment.py", "AlignmentCycleResult.to_dict", {"init": {"cycle_id": cycle_id, "timestamp": moment}}, ) if cycle_id == "fixed" and moment == 0.0: return label_result(text, "aureon.alignment.pillar_alignment.AlignmentCycleResult", DEFAULTS_NOTE) return text
@quietdef alignment_directive_to_dict(directive_id: str = "fixed", timestamp: float = 0.0) -> str: """MasterDirective.to_dict with a fixed id and timestamp. Provenance: cited.
The dataclass defaults would call uuid and the clock. Those arguments are passed so this call does not. Other fields stay the dataclass defaults, including dominant_frequency_hz = FUNDAMENTAL_HZ, and are not a reading.
Args: directive_id: Passed as the constructor directive_id. Label: cited. timestamp: Passed as the constructor timestamp. Label: cited. """
moment = _finite(timestamp) if moment is None or not isinstance(directive_id, str) or not directive_id: return _unavailable("directive_id or timestamp is missing") text = _call( "alignment/unified_directive.py", "MasterDirective.to_dict", {"init": {"directive_id": directive_id, "timestamp": moment}}, ) if directive_id == "fixed" and moment == 0.0: return label_result(text, "aureon.alignment.unified_directive.MasterDirective", DEFAULTS_NOTE) return text
@quietdef alignment_pillar_factory() -> str: """get_pillar_alignment. Provenance: cited.
The function's own default config sets auto_load_pillars false, so this call does not load pillar agents. The constructor still runs its thought-bus wire. If that call fails, the result is unavailable. No order is sent.
Args: none: This tool takes no inputs. Label: cited, get_pillar_alignment. """
return _call("alignment/pillar_alignment.py", "get_pillar_alignment", {})
TOOLS: list[Any] = [ alignment_signal_consensus, alignment_consonance_read, alignment_frequency_harmony, alignment_phase_coherence, alignment_derive_phase, alignment_geometric_mean, alignment_full_analysis, alignment_harmonic_to_dict, alignment_cycle_to_dict, alignment_directive_to_dict, alignment_pillar_factory,]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""One stdio session that calls the alignment tools. Writes raw JSON.
Run from measured/aureon_public_alignment_run.sh. Do not hand-edit the output."""
from __future__ import annotations
import argparseimport asyncioimport importlib.metadataimport inspectimport jsonimport osimport sysfrom pathlib import Pathfrom typing import Any
from mcp import ClientSession, StdioServerParametersfrom mcp.client.stdio import stdio_client
from aureon_public import pathsfrom aureon_public.alignment_layer import TOOLSfrom aureon_public.guard_loader import apply_space_guard
def _text_content(result: Any) -> str: parts = [] for block in result.content: text = getattr(block, "text", None) if text is not None: parts.append(text) return "\n".join(parts)
def _defaults(fn: Any) -> dict[str, Any]: signature = inspect.signature(fn) arguments = {} for name, param in signature.parameters.items(): if param.default is inspect.Parameter.empty: continue if param.default == "": continue arguments[name] = param.default return arguments
def _environment() -> dict[str, Any]: apply_space_guard() import aureon
direct = None try: dist = importlib.metadata.distribution("aureon") raw = dist.read_text("direct_url.json") direct = json.loads(raw) if raw else None except Exception as exc: # noqa: BLE001 - the record should say the pin was not readable direct = {"error": type(exc).__name__} from aureon_public.measurement_stamp import measurement_stamp
return { "aureon_direct_url": direct, "aureon_file": aureon.__file__, "python": sys.executable, **measurement_stamp(), }
async def _session(out_path: Path) -> dict[str, Any]: env = { "PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", ""), "PYTHONUNBUFFERED": "1", } params = StdioServerParameters( command=sys.executable, args=["-m", "aureon_public"], env=env, cwd=str(Path.cwd()), ) async with stdio_client(params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() calls = {} for fn in TOOLS: arguments = _defaults(fn) result = await session.call_tool(fn.__name__, arguments) text = _text_content(result) record_call = { "arguments": arguments, "isError": result.isError, "text": text, } try: body = json.loads(text) except json.JSONDecodeError: body = None if isinstance(body, dict) and body.get("input_source"): record_call["input_note"] = body.get("input_note") record_call["input_source"] = body["input_source"] calls[fn.__name__] = record_call record = {"calls": calls, "environment": _environment()} out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") return record
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-alignment-measure") parser.add_argument( "--out", type=Path, default=paths.repo_root() / "measured" / "aureon_public_alignment.json", ) args = parser.parse_args(argv) asyncio.run(_session(args.out))
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405"""Address every inventoried entry point without registering thousands of tools.
`body_call` runs a real function or method. `body_surface` reads a module orclass and does not construct it. Depth is the count of calls, not the countof rows in the plan. A helper label is not used here."""
from __future__ import annotations
import astimport hashlibimport inspectimport jsonimport osimport reimport signalimport subprocessimport sysimport tempfileimport threadingfrom datetime import datefrom pathlib import Pathfrom typing import Any
from aureon_public.guard_loader import PINNED_COMMIT, apply_space_guard, aureon_sourcefrom aureon_public.paths import repo_rootfrom aureon_public.pin_blob import checkout_blob_refusal, load_checkout_modulefrom aureon_public.quiet import quietfrom aureon_public.tools import _dumps
# Stages 1-6 raise this as each stage commit lands. Stage 7 is packaging.ENABLED_THROUGH = 6# Plan stages from coverage_plan.stage_for. Stages above this are refused# before a worker starts, until a later run opens them.OPEN_PLAN_THROUGH = 2
_UNSAFE_NAME = re.compile( r"(run_|start_|stop_|launch_|serve|main$|^demo$|create_app|activate_|connect_|" r"publish_|write_|save_|download_|fetch_|notify_|reset_|discover_|simulate_|" r"audit_|ingest_|record_|wire_|print_|benchmark|forever|continuous|^analyze|demo_)", re.I,)_SKIP_WORD = re.compile( r"price|live_|kraken|order|exchange|network|socket|download|schumann|biometric|trade|wallet|secret|" r"thought_bus|redis|postgres|sqlite|calibration|^evaluate_|^observe$|" r"feed_hub|ws_feed|space_weather|news_signal|coordinator|seer_vision|lyra", re.I,)_UNSAFE_SOURCE = ( "requests", "urlopen", "httpx", "socket", "subprocess", "write_text", "write_bytes", "serve_forever", "SystemExit", "os._exit", "os.system", "sqlite", "execute(", "open(",)
_BLOCKED = { "trading", "exchanges", "bots", "bots_intelligence", "bridges", "scanners", "unified_margin_trader",}
_AURIS = { "QueenHiveMind.read_auris_nodes": "nine nodes", "QueenHiveMind.get_auris_coherence": "coherence evaluator", "evaluate_auris_nodes": "evaluation harness over brain proof, not the nine-node reader and not the conjecture", "get_auris_voice_filter": "harmonic AurisVoiceFilter", "reset_auris_voice_filter": "harmonic AurisVoiceFilter", "AurisVoiceFilter": "harmonic AurisVoiceFilter", "AurisValidator": "validator",}
_ROWS: list[dict[str, Any]] | None = None_INDEX: dict[tuple[str, str], dict[str, Any]] | None = None_INVENTORY_REFUSAL: str | None = None# sha256 of the committed docs/mcp/inventory.json. A different file is not loaded.INVENTORY_SHA256 = "4bc19ea9b5444a7b8a9abbd3fabf635d083bd25bea6c1b2d6eab2605b4f5716b"_LEAKY_PARAMS = {"url", "path", "out", "file", "host"}# Operator-scoped rows are refused unless named here. No portfolio or accounting key reader._OPERATOR_ALLOWLIST = { ("accounting/file_drop.py", "registered_ingestors"), ("portfolio/aureon_billion_goal_tracker.py", "get_days_remaining"),}# These stay off body_call. compose_repository_layers finds sibling checkouts# at parents[3] and execs them outside the pin. build_lane("fintech") imports# the in-house adapter through the accounting package._UNTESTED_STAGE2 = "untested stage-2 entry point is not called"_ENTRY_REFUSAL = { ("organism/repository_layers.py", "compose_repository_layers"): ( "stage 4 entry point is not called" ), ("swarm/capability_grid.py", "build_lane"): "stage 4 entry point is not called", # Reachable through body_call, and not a tested tool. The real argument # is an object the constructor allowlist does not include. ("decoders/book_of_ur.py", "test_phi_resonance_me"): _UNTESTED_STAGE2, ("observer/momentum.py", "set_momentum_tracker"): _UNTESTED_STAGE2, ("observer/predictor.py", "make_predictor"): _UNTESTED_STAGE2, ("observer/wave_predictor.py", "set_wave_predictor"): _UNTESTED_STAGE2, ("observer/wave_predictor.py", "make_predictor"): _UNTESTED_STAGE2, ("observer/live_data_policy.py", "log_blocked_fallback"): ( "fallback log is not emitted for an event that did not happen" ), ("swarm/agent.py", "SwarmAgent.purity"): ( "property is not called; the worker calls methods" ), ("swarm/coherence.py", "ClusterCoherence.warm"): ( "property is not called; the worker calls methods" ), ("swarm/memory_bus.py", "CausalEchoBus.possibilities"): ( "one call cannot park an ensemble and read it" ), ("swarm/auris_node_receipts.py", "issue_auris_node_receipt"): ( "trusted resolver is not built from JSON" ), ("swarm/auris_node_receipts.py", "validate_auris_node_receipt"): ( "receipt is assembled by the test harness; the public result cap would drop its fields" ), ("swarm/auris_node_receipts.py", "validate_hnc_evidence"): ( "receipt is assembled by the test harness; the public result cap would drop its fields" ), ("swarm/auris_node_receipts.py", "validate_provider_moment"): ( "receipt is assembled by the test harness; the public result cap would drop its fields" ), ("swarm/druidic_council.py", "validate_council_receipt"): ( "receipt is assembled by the test harness; the public result cap would drop its fields" ), ("swarm/druidic_council.py", "validate_seat_receipt"): ( "receipt is assembled by the test harness; the public result cap would drop its fields" ),}# A method call constructs its class. An unlisted constructor is not run.# The risk scan still runs. PillarAlignment, UnifiedHarmonicDirective, and the# swarm classes that need nested agent instances stay off this list._CONSTRUCTOR_ALLOWLIST: set[tuple[str, str]] = { ("alignment/harmonic_resonance.py", "HarmonicAnalysis"), ("alignment/pillar_alignment.py", "AlignmentCycleResult"), ("alignment/unified_directive.py", "MasterDirective"), ("generated/research_cinema/harmonic_nexus_score_model.py", "HarmonicNexusScoreInputs"), ("swarm/agent.py", "SwarmAgent"), ("swarm/coherence.py", "ClusterCoherence"), ("swarm/druidic_council.py", "CouncilReceipt"), ("swarm/druidic_council.py", "SeatReceipt"), ("swarm/memory_bus.py", "CausalEchoBus"), ("swarm/queen_gate.py", "Actualization"), ("swarm/steering.py", "SteeringField"),}_NAME_CONTAINS = ("write", "save", "export", "dump", "start", "run")_WORKER_SLOTS = threading.BoundedSemaphore(4)WORKER_WAIT_SECONDS = 10.0WORKER_REAP_SECONDS = 2.0
def enabled_stage() -> int: return ENABLED_THROUGH
def _inventory() -> tuple[list[dict[str, Any]], dict[tuple[str, str], dict[str, Any]]]: global _ROWS, _INDEX, _INVENTORY_REFUSAL if _ROWS is not None and _INDEX is not None: return _ROWS, _INDEX path = repo_root() / "docs" / "mcp" / "inventory.json" data = path.read_bytes() digest = hashlib.sha256(data).hexdigest() if digest != INVENTORY_SHA256: _INVENTORY_REFUSAL = "inventory hash mismatch" _ROWS = [] _INDEX = {} return _ROWS, _INDEX _INVENTORY_REFUSAL = None loaded = json.loads(data) if not isinstance(loaded, list): _INVENTORY_REFUSAL = "inventory hash mismatch" _ROWS = [] _INDEX = {} return _ROWS, _INDEX index: dict[tuple[str, str], dict[str, Any]] = {} for row in loaded: index.setdefault((row["module"], row["symbol"]), row) _ROWS = loaded _INDEX = index return _ROWS, _INDEX
def lookup(module: str, symbol: str) -> dict[str, Any] | None: _, index = _inventory() return index.get((module, symbol))
def file_for(module: str) -> Path: root = repo_root() if module.startswith("unified_margin_trader/"): return root / module return root / "aureon" / module
def dotted_for(module: str) -> str: if module.startswith("unified_margin_trader/"): relative = module else: relative = "aureon/" + module return ".".join(Path(relative).with_suffix("").parts)
def _outside(origin: Path, root: Path) -> bool: resolved = origin.resolve() root_resolved = root.resolve() return resolved != root_resolved and root_resolved not in resolved.parents
def _blocked_dotted_prefix(dotted: str) -> str | None: parts = dotted.split(".") if parts[0] in _BLOCKED: return f"package {parts[0]} is not importable" if parts[0] == "aureon" and len(parts) > 1 and parts[1] in _BLOCKED: return f"package {parts[1]} is not importable" return None
def _plain(value: Any, depth: int = 0) -> Any: if depth > 4: return type(value).__name__ if value is None or isinstance(value, (str, int, float, bool)): if isinstance(value, float) and value != value: return None if isinstance(value, str): return value[:500] return value if isinstance(value, dict): return {str(key): _plain(item, depth + 1) for key, item in list(value.items())[:30]} if isinstance(value, (list, tuple)): return [_plain(item, depth + 1) for item in list(value)[:30]] if hasattr(value, "to_dict") and callable(value.to_dict): try: return _plain(value.to_dict(), depth + 1) except Exception: pass if hasattr(value, "__dict__") and not isinstance(value, type): fields = {key: item for key, item in vars(value).items() if not str(key).startswith("_")} return {"type": type(value).__name__, "fields": _plain(fields, depth + 1)} return {"type": type(value).__name__}
def _result(payload: dict[str, Any]) -> str: payload.setdefault("provenance", "cited") text = _dumps(payload) if len(text) > 8000: payload = { "called": payload.get("called"), "label": payload.get("label"), "provenance": payload.get("provenance", "cited"), "status": payload.get("status"), "truncated": True, } text = _dumps(payload) return text
def _unavailable(reason: str, **extra: Any) -> str: body = {"label": "cited. Not called.", "reason": reason, "status": "unavailable"} body.update(extra) return _result(body)
def _refused(reason: str) -> str: return _unavailable(reason, live_orders="refused")
def _function_source(module: str, symbol: str) -> str: path = file_for(module) if not path.is_file(): return "" try: text = path.read_text(encoding="utf-8", errors="replace") tree = ast.parse(text) except (OSError, SyntaxError): return "" lines = text.splitlines() class_name, _, method_name = symbol.partition(".") nodes: list[ast.AST] = list(tree.body) target = symbol if method_name: target = method_name nodes = [] for node in tree.body: if isinstance(node, ast.ClassDef) and node.name == class_name: nodes = list(node.body) break for node in nodes: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target: end = node.end_lineno or node.lineno return "\n".join(lines[node.lineno - 1 : end]) return ""
def _parameter_names(module: str, symbol: str) -> list[str] | None: """Named parameters from the AST. None when the function cannot be found."""
path = file_for(module) if not path.is_file(): return None try: tree = ast.parse(path.read_text(encoding="utf-8", errors="replace")) except (OSError, SyntaxError): return None class_name, _, method_name = symbol.partition(".") nodes: list[ast.AST] = list(tree.body) target = symbol if method_name: target = method_name nodes = [] for node in tree.body: if isinstance(node, ast.ClassDef) and node.name == class_name: nodes = list(node.body) break for node in nodes: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target: names = [ item.arg for item in (*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs) if item.arg not in {"self", "cls"} ] return names return None
def _leaky_parameter(module: str, symbol: str) -> bool: names = _parameter_names(module, symbol) if names is None: return True for name in names: parts = name.lower().split("_") if any(part in _LEAKY_PARAMS for part in parts): return True return False
def _name_blocked(symbol: str) -> str | None: leaf = symbol.rsplit(".", 1)[-1] if "run_humaneval" in symbol.lower(): return "run_humaneval is not called" if _UNSAFE_NAME.search(leaf) or _SKIP_WORD.search(leaf): return "name is not called on the public server" lowered = leaf.lower() for token in _NAME_CONTAINS: if token in lowered: return f"name contains {token}" return None
def _package_kind(package: str) -> str: import aureon_public.more_layers # noqa: F401 - applies the excluded kinds
from aureon_public.layers import PACKAGES
for row in PACKAGES: if row["package"] == package: return row["kind"] return ""
def _quiet_source(module: str, symbol: str) -> bool: source = _function_source(module, symbol) if not source: return False return not any(token in source for token in _UNSAFE_SOURCE)
def _coerce(fn: Any, kwargs: dict[str, Any]) -> dict[str, Any]: try: signature = inspect.signature(fn) except (TypeError, ValueError): return kwargs coerced = dict(kwargs) for name, value in list(coerced.items()): param = signature.parameters.get(name) if param is None: continue annotation = param.annotation origin = getattr(annotation, "__origin__", None) name_of = annotation if isinstance(annotation, str) else getattr(annotation, "__name__", "") if (annotation is date or name_of == "date" or str(name_of).endswith("date")) and isinstance(value, str): coerced[name] = date.fromisoformat(value) elif (annotation is frozenset or origin is frozenset) and isinstance(value, list): coerced[name] = frozenset(value) return coerced
def _required_missing(fn: Any, kwargs: dict[str, Any]) -> str | None: try: signature = inspect.signature(fn) except (TypeError, ValueError): return None try: signature.bind(**kwargs) except TypeError as exc: return str(exc) return None
def _checkout_load(module: str) -> str | None: """Hash-check the target file. The worker loads parents through the finder.
``find_spec`` is not used. It would import parent packages before the blob check. """
return checkout_blob_refusal(file_for(module), repo_root(), PINNED_COMMIT)
# Filled only when AUREON_PUBLIC_REPORT_MODULES=1 is copied into the worker.# The count is how many worker results included a modules list, including an empty one.reported_worker_modules: list[str] = []reported_worker_module_reports = 0# Last worker sweep block. Set only while this process is measuring.last_sweep_report: dict[str, Any] | None = None# In-process only. The environment and a client cannot set this._sweep_measuring = False
def enable_sweep_measurement() -> None: """Let this process call past the call-sweep gate. Not an environment switch."""
global _sweep_measuring _sweep_measuring = True
def _worker_env() -> dict[str, str]: """Minimal child environment. Parent secrets and extras are not copied across."""
package_root = str(Path(__file__).resolve().parents[1]) env: dict[str, str] = { "PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", ""), "TMPDIR": os.environ.get("TMPDIR", "") or tempfile.gettempdir(), "PYTHONPATH": package_root, "AUREON_AUDIT_MODE": "1", "AUREON_DISABLE_REAL_ORDERS": "1", "AUREON_DISABLE_LIVE_BACKGROUND_STARTUP": "1", "AUREON_SUPPRESS_IMPORT_SIDE_EFFECTS": "1", "AUREON_ENABLE_AUTONOMOUS_CONTROL": "0", "AUREON_ACTIVATE_ON_IMPORT": "0", "AUREON_OBSERVER_MODE": "dry_run", } for key in ("LANG", "LC_ALL", "LC_CTYPE", "PYTHONHASHSEED", "AUREON_PUBLIC_REPORT_MODULES"): value = os.environ.get(key) if value: env[key] = value if _sweep_measuring: env["AUREON_PUBLIC_SWEEP"] = "1" sandbox = os.environ.get("AUREON_PUBLIC_SANDBOX") if sandbox: env["AUREON_PUBLIC_SANDBOX"] = sandbox for key in ( "HOME", "USERPROFILE", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_STATE_HOME", ): value = os.environ.get(key) if value: env[key] = value return env
def _worker_argv() -> list[str]: """Isolated interpreter. The mcp path is argv, not cwd and not PYTHONPATH.
``-I`` implies ``-E``, ``-s``, and ``-P``, so the checkout is not on sys.path and a root-level ``json.py`` or ``aureon_public`` package cannot shadow the worker. """
mcp_root = str(Path(__file__).resolve().parents[1]) code = ( "import sys\n" "sys.path.insert(0, sys.argv[1])\n" "from aureon_public.call_worker import main\n" "main()\n" ) return [sys.executable, "-I", "-c", code, mcp_root]
def _worker_cwd() -> str: """A directory outside the checkout. cwd must not become sys.path[0]."""
return tempfile.gettempdir()
def _acquire_worker() -> bool: return _WORKER_SLOTS.acquire(timeout=WORKER_WAIT_SECONDS)
def _release_worker() -> None: _WORKER_SLOTS.release()
def _call_in_subprocess(module: str, symbol: str, arguments: dict[str, Any], timeout: float) -> tuple[str, Any]: """Run the entry point in a child process. A timeout kills the process group."""
if symbol.lower().endswith(".__init__") or symbol.split(".")[-1].startswith("_"): return "error", "private entry point is not called" checkout_error = _checkout_load(module) if checkout_error: return "error", checkout_error payload = json.dumps( { "dotted": dotted_for(module), "module": module, "symbol": symbol, "arguments": arguments, } ).encode("utf-8") slot_acquired = False try: if not _acquire_worker(): return ( "busy", f"live worker cap 4 not available within {WORKER_WAIT_SECONDS:g}s", ) slot_acquired = True process = subprocess.Popen( _worker_argv(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, cwd=_worker_cwd(), env=_worker_env(), ) try: stdout, _stderr = process.communicate(payload, timeout=timeout) except subprocess.TimeoutExpired: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass try: process.communicate(timeout=WORKER_REAP_SECONDS) except subprocess.TimeoutExpired: pass return "timeout", f"exceeded {timeout:g}s" if process.returncode not in {0, None}: text = stdout.decode("utf-8", errors="replace").strip() if not text: return "error", f"worker exited {process.returncode}" try: body = json.loads(stdout.decode("utf-8")) except json.JSONDecodeError: return "error", "worker result was not JSON" modules = body.get("modules") if isinstance(body, dict) else None if isinstance(modules, list): global reported_worker_module_reports reported_worker_module_reports += 1 reported_worker_modules.extend(str(item) for item in modules) sweep = body.get("sweep") if isinstance(body, dict) else None if isinstance(sweep, dict): global last_sweep_report last_sweep_report = sweep if body.get("ok") is True: return "ok", body.get("result") return "error", str(body.get("error") or "worker failed")[:240] finally: if slot_acquired: _release_worker()
def _constructor_refusal(module: str, class_name: str) -> str | None: from aureon_public.inventory_scan import source_is_risky
if (module, class_name) not in _CONSTRUCTOR_ALLOWLIST: return "constructor is not allowlisted" source = _function_source(module, f"{class_name}.__init__") if source_is_risky(source): return "constructor failed the risk scan" return None
def _operator_allowlist_refusal(row: dict[str, Any]) -> str | None: """Every operator-path row must be named. Fetch and write stay closed."""
key = (str(row["module"]), str(row["symbol"])) if key not in _OPERATOR_ALLOWLIST: return "operator row is not allowlisted" source = _function_source(str(row["module"]), str(row["symbol"])) if re.search(r"api_key|secret|password|credential|private_key", source or "", re.I): return "portfolio or accounting key reader is not allowlisted" if row["package"] in {"portfolio", "accounting"} and re.search( r"api_key|secret|password|credential|private_key", str(row["symbol"]), re.I ): return "portfolio or accounting key reader is not allowlisted" return None
def _import_checked(module: str) -> tuple[Any | None, str | None]: """Load a module and its parents through the pinned loader.
There is no outside-checkout fallback and no ``find_spec`` on the full name. """
apply_space_guard() from aureon_public.layers import _load_phenolic_fingerprint
_load_phenolic_fingerprint() path = file_for(module) dotted = dotted_for(module) blocked = _blocked_dotted_prefix(dotted) if blocked: return None, blocked root = repo_root() loaded, refusal = load_checkout_module(dotted, path, root, PINNED_COMMIT) if refusal: return None, refusal return loaded, None
def _safety_block(row: dict[str, Any], *, allow_fetch: bool, allow_write: bool) -> str | None: text = str(row.get("safety") or "") if "live_orders" in text or row["package"] in _BLOCKED: return "live orders are refused and the blocked import was not performed" if "reads keys" in text or "personal or key" in text or "never returned" in text: return "key or personal material is not read" if text.startswith("process") or "UI start" in text or "loop" in text: return "process and loop entry points are not started" if text.startswith("writes") and not allow_write: return "write entry points are not started" if "write or process start" in text and not allow_write: return "write or process start is refused" if text.startswith("live public fetch") and not allow_fetch: return "live fetch is not part of this call" if "file does not parse" in text: return "file does not parse" return None
_REFUSAL_CACHE: dict[tuple[str, str], str | None] = {}_PLAN_STAGE: dict[str, int] | None = None_STAGE2_TABLE: dict[str, dict[str, Any]] | None = None_STAGE2_MISSING = False
def _plan_stage(package: str) -> int: """Coverage-plan stage for a package. Unknown packages stay closed."""
global _PLAN_STAGE if _PLAN_STAGE is None: from collections import defaultdict
from aureon_public.coverage_plan import safety_category, stage_for
rows, _index = _inventory() categories: dict[str, set[str]] = defaultdict(set) for row in rows: categories[str(row["package"])].add(safety_category(str(row.get("safety") or ""))) _PLAN_STAGE = { name: stage_for(name, marks) for name, marks in categories.items() } return _PLAN_STAGE.get(package, 4)
def _stage2_table() -> dict[str, dict[str, Any]] | None: """Committed socket-blocked import sweep. None when the file is missing."""
global _STAGE2_MISSING, _STAGE2_TABLE if _STAGE2_TABLE is not None or _STAGE2_MISSING: return _STAGE2_TABLE path = repo_root() / "measured" / "aureon_public_stage2_imports.json" try: loaded = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): _STAGE2_MISSING = True return None table: dict[str, dict[str, Any]] = {} if isinstance(loaded, dict): for row in loaded.get("modules") or []: if isinstance(row, dict) and row.get("module"): table[str(row["module"])] = row _STAGE2_TABLE = table return table
def _stage2_import_refusal(module: str) -> str | None: table = _stage2_table() if table is None: return "import sweep record is missing" row = table.get(module) if row is None: return "module is not in the import sweep" if row.get("refused"): return str(row.get("refusal") or "module import loads an adapter or http client") return None
_CALL_SWEEP: dict[tuple[str, str], dict[str, Any]] | None = None_CALL_SWEEP_MISSING = False
def _call_sweep_table() -> dict[tuple[str, str], dict[str, Any]] | None: """Per-entry-point call sweep. None when the file is missing."""
global _CALL_SWEEP, _CALL_SWEEP_MISSING if _CALL_SWEEP is not None or _CALL_SWEEP_MISSING: return _CALL_SWEEP path = repo_root() / "measured" / "aureon_public_call_sweep.json" try: loaded = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): _CALL_SWEEP_MISSING = True return None table: dict[tuple[str, str], dict[str, Any]] = {} if isinstance(loaded, dict): for row in loaded.get("entries") or []: if isinstance(row, dict) and row.get("module") and row.get("symbol"): table[(str(row["module"]), str(row["symbol"]))] = row _CALL_SWEEP = table return table
def _call_sweep_refusal(module: str, symbol: str) -> str | None: """Refuse a call the sweep saw open a socket or load the banned chain.
Only ``enable_sweep_measurement`` in this process skips the gate. An environment variable cannot. """
if _sweep_measuring: return None table = _call_sweep_table() if table is None: return "call sweep record is missing" row = table.get((module, symbol)) if row is None: return "entry point is not in the call sweep" if row.get("refused"): return str(row.get("refusal") or "call loads a banned chain or opens a connection") return None
def public_entry_refusal(row: dict[str, Any]) -> str | None: """Why the public server will not run this row. None when it may run."""
key = (str(row.get("module") or ""), str(row.get("symbol") or "")) if key in _REFUSAL_CACHE: return _REFUSAL_CACHE[key] reason = _public_entry_refusal(row) _REFUSAL_CACHE[key] = reason return reason
def _public_entry_refusal(row: dict[str, Any]) -> str | None: if row["server"] != "public": return "operator entry point is not on aureon-public" if row["package"] in _BLOCKED: return "blocked package is not imported on aureon-public" kind = _package_kind(str(row["package"])) if kind in {"operator", "excluded"}: return f"package {row['package']} is {kind}" plan_stage = _plan_stage(str(row["package"])) if plan_stage > OPEN_PLAN_THROUGH: return f"plan stage {plan_stage} is not open" named = _ENTRY_REFUSAL.get((str(row["module"]), str(row["symbol"]))) if named: return named if plan_stage == 2: sweep = _stage2_import_refusal(str(row["module"])) if sweep: return sweep if int(row.get("stage") or 0) > ENABLED_THROUGH: return f"stage {row['stage']} is not open" if row["kind"] not in _ENTRY_KINDS: return "use body_surface for modules and classes" block = _safety_block(row, allow_fetch=False, allow_write=False) if block: return block blocked_name = _name_blocked(str(row["symbol"])) if blocked_name: return blocked_name if _leaky_parameter(str(row["module"]), str(row["symbol"])): return "parameter can carry a url, path, file, or host" if row["kind"] == "method": class_name = str(row["symbol"]).rsplit(".", 1)[0] constructor = _constructor_refusal(str(row["module"]), class_name) if constructor: return constructor if not _quiet_source(str(row["module"]), str(row["symbol"])): return "source is not a quiet read" sweep = _call_sweep_refusal(str(row["module"]), str(row["symbol"])) if sweep: return sweep return None
def _auris_field(symbol: str) -> dict[str, str]: meaning = _AURIS.get(symbol) if meaning is None and "auris" not in symbol.lower(): return {} return { "auris_meaning": meaning or "unspecified Auris name; not scored as the conjecture", "auris_note": ( "Four meanings stay separate. This call is only the meaning named above. " "The LambdaEngine conjecture is not called." ), }
def _invoke( row: dict[str, Any], arguments: dict[str, Any], timeout: float, *, allow_fetch: bool, allow_write: bool,) -> str: block = _safety_block(row, allow_fetch=allow_fetch, allow_write=allow_write) if block: if "live orders" in block: return _refused(block) return _unavailable(block) if row["kind"] in {"module", "class"}: return _unavailable("use body_surface for modules and classes") if int(row.get("stage") or 0) > ENABLED_THROUGH: return _unavailable(f"stage {row['stage']} is not open") if "." in str(row["symbol"]): class_name = str(row["symbol"]).rsplit(".", 1)[0] constructor = _constructor_refusal(str(row["module"]), class_name) if constructor: return _unavailable(constructor) label = f"cited. {row['module']} {row['symbol']} ran." extra = _auris_field(row["symbol"]) state, value = _call_in_subprocess(str(row["module"]), str(row["symbol"]), arguments, timeout) if state != "ok": return _unavailable(str(value)) return _result( { "called": True, "label": label, "result": value, "status": "cited", **extra, } )
def dispatch( module: str, symbol: str, arguments: dict[str, Any] | None = None, *, server: str, timeout: float = 8.0,) -> str: """Run one inventoried entry point, or refuse it."""
_inventory() if _INVENTORY_REFUSAL: return _unavailable(_INVENTORY_REFUSAL) row = lookup(module, symbol) if row is None: return _unavailable("symbol is not in the inventory") if server == "operator" and os.environ.get("AUREON_OPERATOR_MCP") != "1": return _unavailable("AUREON_OPERATOR_MCP=1 is required") if server == "operator": allow = _operator_allowlist_refusal(row) if allow: return _unavailable(allow, live_orders="refused") return _invoke(row, arguments or {}, timeout, allow_fetch=False, allow_write=False) if server == "public": reason = public_entry_refusal(row) if reason: if ( "live orders" in reason or reason.startswith("blocked package") or reason.startswith("operator entry point") ): return _refused(reason) return _unavailable(reason) return _invoke(row, arguments or {}, timeout, allow_fetch=False, allow_write=False) return _unavailable("unknown server")
def _parse_arguments(arguments_json: str) -> dict[str, Any] | str: text = (arguments_json or "").strip() if not text: return {} try: loaded = json.loads(text) except json.JSONDecodeError: return "arguments_json is not JSON" if not isinstance(loaded, dict): return "arguments_json must be an object" return loaded
@quietdef body_call(module: str, symbol: str, arguments_json: str = "") -> str: """Call one public entry point from the inventory. Provenance: cited.
This runs the named function. It is not a helper. Modules and classes are refused here. Operator, key, write, loop, and blocked packages are not called. A checkout file is imported only when its git blob matches pin 8aa6a2d9.
Args: module: Inventory module path, such as harmonic/rainbow_reference.py. Label: cited. symbol: Function or Class.method. Label: cited. arguments_json: JSON object of keyword arguments. Empty means none. Label: cited. """
parsed = _parse_arguments(arguments_json) if isinstance(parsed, str): return _unavailable(parsed) return dispatch(module, symbol, parsed, server="public")
@quietdef body_call_operator(module: str, symbol: str, arguments_json: str = "") -> str: """Call one operator entry point, or refuse a live order. Provenance: cited.
Live orders are refused and the blocked trading imports are not performed. Keys are not read or returned. AUREON_OPERATOR_MCP=1 is required.
Args: module: Inventory module path. Label: cited. symbol: Function or Class.method. Label: cited. arguments_json: JSON object of keyword arguments. Label: cited. """
parsed = _parse_arguments(arguments_json) if isinstance(parsed, str): return _unavailable(parsed) return dispatch(module, symbol, parsed, server="operator")
@quietdef body_surface(module: str, symbol: str) -> str: """Read one module or class surface from the inventory. Provenance: cited.
Nothing is imported and nothing is constructed. Functions are not called.
Args: module: Inventory module path. Label: cited. symbol: Module stem or class name. Label: cited. """
row = lookup(module, symbol) if row is None: return _unavailable("symbol is not in the inventory") if int(row.get("stage") or 0) > ENABLED_THROUGH: return _unavailable(f"stage {row['stage']} is not open") if row["server"] != "public": return _unavailable("operator surface is not on aureon-public") rows, _ = _inventory() methods = [ item["symbol"] for item in rows if item["module"] == module and item["kind"] == "method" and item["symbol"].startswith(symbol + ".") ] return _result( { "called": False, "form": row["form"], "kind": row["kind"], "label": "cited. Surface only. The entry point was not called.", "methods": methods[:40], "safety": row["safety"], "server": row["server"], "stage": row["stage"], "status": "cited", "symbol": symbol, } )
_ENTRY_KINDS = {"function", "method"}
def package_depth(stage: int | None = None) -> dict[str, dict[str, int]]: """Reachable public functions and methods, out of the pinned inventory.
The denominator is every public function and method. The numerator is how many of those the public server will still run. A listed row is not reachable. """
rows, _ = _inventory() selected = [row for row in rows if stage is None or int(row["stage"]) == stage] seen: dict[str, set[tuple[str, str]]] = {} reachable: dict[str, set[tuple[str, str]]] = {} names: set[str] = set() for row in selected: names.add(str(row["package"])) if row["server"] != "public" or row["kind"] not in _ENTRY_KINDS: continue key = (str(row["module"]), str(row["symbol"])) bucket = seen.setdefault(str(row["package"]), set()) if key in bucket: continue bucket.add(key) if public_entry_refusal(row) is None: reachable.setdefault(str(row["package"]), set()).add(key) return { package: { "reachable": len(reachable.get(package, set())), "public_entry_points": len(seen.get(package, set())), } for package in sorted(names) }
def render_readme_depth() -> str: """The README depth section. Tests require the file to contain this text."""
lines = [ "A layer counts as full depth only where its real entry points are called.", "Each figure is reachable public functions and methods out of the public functions and methods in the pinned `docs/mcp/inventory.json`.", "", "| Package | Reachable | Public entry points |", "| --- | ---: | ---: |", ] for package, row in package_depth().items(): lines.append(f"| {package} | {row['reachable']} | {row['public_entry_points']} |") return "\n".join(lines)
def depth_report() -> dict[str, Any]: """Per-package counts. ``called`` is filled from sweep files when present."""
rows, _ = _inventory() packages: dict[str, dict[str, int]] = {} for row in rows: bucket = packages.setdefault( row["package"], {"called": 0, "listed": 0, "open": 0, "operator": 0, "public": 0}, ) bucket["listed"] += 1 if row["server"] == "public": bucket["public"] += 1 else: bucket["operator"] += 1 if int(row["stage"]) <= ENABLED_THROUGH: bucket["open"] += 1 entry_points = package_depth() for package, row in entry_points.items(): bucket = packages.setdefault( package, {"called": 0, "listed": 0, "open": 0, "operator": 0, "public": 0}, ) bucket["called"] = row["reachable"] bucket["reachable"] = row["reachable"] bucket["public_entry_points"] = row["public_entry_points"] return { "enabled_through": ENABLED_THROUGH, "entry_points": entry_points, "label": ( "cited. Depth is reachable public functions and methods out of the public " "functions and methods in the pinned inventory. A listed row is not reachable." ), "packages": packages, "provenance": "cited", "servers": { "operator": sum(1 for row in rows if row["server"] == "operator"), "public": sum(1 for row in rows if row["server"] == "public"), }, "status": "cited", "symbols": len(rows), }
@quietdef body_registry() -> str: """Name the public and operator servers and the inventory they address. Provenance: cited.
This is the registry. It does not call package entry points. Live orders stay refused. A checkout file is still blob-checked before a later call imports it.
Args: none: This tool takes no inputs. Label: cited, the registry. """
return _result( { "blocked_imports": sorted(_BLOCKED), "enabled_through": ENABLED_THROUGH, "inventory": "docs/mcp/FULL_BODY_PLAN.md", "label": "cited. Registry only. No package entry point ran.", "live_orders": "refused", "operator": { "flag": "AUREON_OPERATOR_MCP=1", "tool": "body_call_operator", "transport": "stdio", }, "pin": PINNED_COMMIT, "public_tools": ["body_call", "body_depth", "body_registry", "body_surface"], "spaces": [ "huggingface/hnc-field/app.py", "huggingface/auris-coherence/app.py", "huggingface/qgita-snr/app.py", "huggingface/organism-replay/app.py", ], "status": "cited", } )
@quietdef body_depth() -> str: """Per-package depth for the stages that are open. Provenance: cited.
``called`` counts entry points that a measured sweep actually ran. Listing a symbol is not depth. Helper tools are not counted here.
Args: none: This tool takes no inputs. Label: cited, the depth table. """
report = depth_report() report["aureon_source_note"] = aureon_source().get("kind") return _result(report)
def probes_for(stage: int) -> list[dict[str, Any]]: """Real entry points the measured run calls for one stage."""
table: dict[int, list[dict[str, Any]]] = { 1: [ {"module": "harmonic/rainbow_reference.py", "symbol": "solfeggio_ladder"}, {"module": "harmonic/rainbow_reference.py", "symbol": "love_centrality"}, { "module": "harmonic/aureon_harmonic_reality.py", "symbol": "HarmonicSubstrate.evaluate", "arguments": {"t": 0.0}, }, { "module": "harmonic/aureon_harmonic_reality.py", "symbol": "CausalEcho.evaluate", "arguments": {"current_lambda": 0.0}, }, {"module": "core/hnc_field.py", "symbol": "blend_field"}, {"module": "core/hnc_params.py", "symbol": "load_params"}, {"module": "wisdom/aureon_qgita_framework.py", "symbol": "get_qgita_analyzer"}, { "module": "utils/aureon_queen_hive_mind.py", "symbol": "QueenHiveMind.read_auris_nodes", }, ], 2: [ { "module": "alignment/harmonic_resonance.py", "symbol": "consonance_score", "arguments": {"ratio": 1.0}, }, {"module": "cognition/logic_flow.py", "symbol": "compute_logic_flow"}, { "module": "queen/temporal_ground.py", "symbol": "compute_zpe_ground", "arguments": {"lambda_t": 0.0}, }, { "module": "swarm/druidic_council.py", "symbol": "voice_for_gamma", "arguments": {"gamma": 0.5}, }, { "module": "swarm_motion/love_stream.py", "symbol": "StandingWaveLoveStream.evaluate", }, { "module": "gates/switchboard.py", "symbol": "is_human_held", "arguments": {"action": "draft"}, }, { "module": "gates/panel.py", "symbol": "ungrounded_nodes", "arguments": {"grounded_slices": []}, }, { "module": "governance/celtic_voice_bank.py", "symbol": "seasonal_gate_for_date", "arguments": {"value": "2026-10-29"}, }, {"module": "observer/live_data_policy.py", "symbol": "simulation_fallback_allowed"}, ], 3: [ { "module": "bio/audio_signal_adapter.py", "symbol": "synthetic_audio", "arguments": {"kind": "noise", "n": 16}, }, { "module": "bio/calibration_curve.py", "symbol": "compute_calibration", "arguments": {"trials": 2, "nulls": 1}, }, {"module": "organism/repository_layers.py", "symbol": "compose_repository_layers"}, {"module": "core/aureon_organism_spine.py", "symbol": "build_organism_manifest"}, { "module": "vault/voice/document_artifact_skill.py", "symbol": "count_words", "arguments": {"text": "one two three"}, }, { "module": "evaluation/auris_node_eval.py", "symbol": "evaluate_auris_nodes", "timeout": 20, }, ], 4: [ { "module": "data_feeds/unified_ws_feed.py", "symbol": "parse_binance_tick", "arguments": { "data": {"s": "BTCUSDT", "b": "1", "a": "2", "c": "1.5", "v": "3", "P": "0", "E": 0} }, }, { "module": "decoders/grail_convergence.py", "symbol": "haversine", "arguments": {"lat1": 51.5, "lon1": -0.12, "lat2": 48.86, "lon2": 2.35}, }, { "module": "search/online_research_cinema.py", "symbol": "summarize_text", "arguments": {"text": "The field is a reading. The reading is not an order.", "topic": "field"}, }, { "module": "portals/ifs.py", "symbol": "html_to_text", "arguments": {"html": "<p>Hello field</p>"}, }, { "module": "analytics/backtest_sentiment_oracle.py", "symbol": "derive_fear_greed", "arguments": { "closes": [1, 1.1, 1.2, 1.1, 1.3, 1.4, 1.2, 1.5], "volumes": [1, 1, 1, 1, 1, 1, 1, 1], "idx": 7, }, }, { "module": "atn/aureon_atn_backtest.py", "symbol": "compute_impacts", "arguments": {"events": [], "candles": [], "symbol": "BTC"}, }, { "module": "monitors/margin_eta_predictor.py", "symbol": "calc_breakeven", "arguments": {"entry": 100.0}, }, { "module": "monitors/margin_eta_predictor.py", "symbol": "normalise_pair", "arguments": {"pair": "btcusd"}, }, ], 5: [ {"module": "accounting/file_drop.py", "symbol": "registered_ingestors", "server": "operator"}, { "module": "portfolio/aureon_billion_goal_tracker.py", "symbol": "get_days_remaining", "server": "operator", }, {"module": "trading/__init__.py", "symbol": "__init__", "server": "operator"}, {"module": "exchanges/__init__.py", "symbol": "__init__", "server": "operator"}, {"module": "bots/__init__.py", "symbol": "__init__", "server": "operator"}, {"module": "bots_intelligence/__init__.py", "symbol": "__init__", "server": "operator"}, {"module": "bridges/__init__.py", "symbol": "__init__", "server": "operator"}, {"module": "scanners/__init__.py", "symbol": "__init__", "server": "operator"}, { "module": "unified_margin_trader/_margin_monitor.py", "symbol": "_margin_monitor", "server": "operator", }, ], 6: [ { "module": "approval/compose.py", "symbol": "subject_line", "arguments": {"action": "status"}, }, { "module": "briefing/schemas.py", "symbol": "severity_rank", "arguments": {"severity": "high"}, }, { "module": "grants/daemon.py", "symbol": "breath_interval", "arguments": {"urgency": None}, }, { "module": "integrations/ollama/hnc_phi_swarm.py", "symbol": "build_phi_swarm_plan", "arguments": {"flow": {"flow": "observe"}, "catalog_size": 2, "max_total_calls": 4}, }, { "module": "intelligence/aureon_advanced_intelligence.py", "symbol": "calculate_harmonic_resonance", "arguments": {"freq1": 100.0, "freq2": 200.0}, }, { "module": "plumber/crypto.py", "symbol": "sha256_hex", "arguments": {"value": "aureon-public"}, }, { "module": "s51/aureon_51_compound.py", "symbol": "summarize_compounding", "arguments": {"receipts": []}, }, { "module": "simulation/aureon_world_simulator.py", "symbol": "hz_to_rgb", "arguments": {"hz": 528.0}, }, { "module": "generated/research_cinema/harmonic_nexus_score_model.py", "symbol": "build_default_inputs", }, ], } return table.get(stage, [])
def sweep_zero_arg(stage: int, *, timeout: float = 8.0) -> list[dict[str, Any]]: """Call public zero-argument functions for one open stage.
Fetches, writes, keys, loops, and blocked packages are skipped. """
if stage > ENABLED_THROUGH: return [] rows, _ = _inventory() calls: list[dict[str, Any]] = [] seen: set[tuple[str, str]] = set() for probe in probes_for(stage): key = (probe["module"], probe["symbol"]) seen.add(key) target = str(probe.get("server") or "public") raw = dispatch( probe["module"], probe["symbol"], probe.get("arguments") or {}, server=target, timeout=float(probe.get("timeout") or timeout), ) calls.append(_summarize(probe["module"], probe["symbol"], raw, probe=True)) for row in rows: if int(row["stage"]) != stage or row["server"] != "public": continue if row["kind"] != "function" or int(row.get("required") or 0) != 0 or row.get("async"): continue if not str(row.get("safety") or "").startswith("runs from inputs"): continue if stage >= 6: continue if stage >= 2: if row["package"] == "queen": continue if _UNSAFE_NAME.search(row["symbol"]) or _SKIP_WORD.search(row["symbol"]): continue if not _quiet_source(row["module"], row["symbol"]): continue key = (row["module"], row["symbol"]) if key in seen: continue seen.add(key) raw = dispatch(row["module"], row["symbol"], {}, server="public", timeout=timeout) calls.append(_summarize(row["module"], row["symbol"], raw, probe=False)) return calls
def _summarize(module: str, symbol: str, raw: str, *, probe: bool) -> dict[str, Any]: try: body = json.loads(raw) except json.JSONDecodeError: body = {"status": "unavailable", "reason": "result was not JSON"} package = module.split("/", 1)[0] if module.startswith("unified_margin_trader/"): package = "unified_margin_trader" elif not module.startswith("unified_margin_trader"): # inventory modules are relative to aureon/, so the first part is the package # except core/utils/wisdom paths. package is the first directory. package = module.split("/", 1)[0] return { "called": body.get("called") is True and body.get("status") == "cited", "module": module, "package": package, "probe": probe, "reason": body.get("reason"), "status": body.get("status"), "symbol": symbol, }12345678910111213141516171819202122232425262728293031323334353637383940414243"""Record real body_call results for one open stage. Does not place orders."""
from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
from aureon_public.body import enabled_stage, package_depth, sweep_zero_argfrom aureon_public.paths import repo_root
def write_stage(stage: int, timeout: float) -> Path: if stage > enabled_stage(): raise SystemExit(f"stage {stage} is not open (enabled through {enabled_stage()})") calls = sweep_zero_arg(stage, timeout=timeout) out = repo_root() / "measured" / f"body_stage{stage}.json" out.parent.mkdir(parents=True, exist_ok=True) called = sum(1 for item in calls if item.get("called") is True) record = { "called": called, "calls": calls, "enabled_through": enabled_stage(), "stage": stage, "tried": len(calls), } out.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") record["entry_points"] = package_depth(stage) out.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") return out
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-body-sweep") parser.add_argument("--stage", type=int, required=True) parser.add_argument("--timeout", type=float, default=8.0) args = parser.parse_args(argv) path = write_stage(args.stage, args.timeout) print(path)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359"""Call every body_call-reachable entry point.
Each call uses the public worker. Sockets are blocked and logged in thatworker. Fake NEXUS and Sero checkouts sit beside the repo. Stage-2 entrypoints are also called with the real arguments in stage2_arguments.SwarmAgent.update is also called with the hive fixture fromtests/test_swarm_hive.py. An entry point is refused when any of those callsopens a connection, starts a process, writes outside the sandbox, or loadsqueen, miner, swarm_motion, inhouse_ai, ollama_config, or an HTTP client.
bash measured/aureon_public_call_sweep.sh"""
from __future__ import annotations
import argparseimport jsonimport osimport subprocessimport sysfrom pathlib import Pathfrom typing import Any
def _tested_stage1_tools() -> set[tuple[str, str]]: return { ("alignment/harmonic_resonance.py", "compute_signal_consensus"), ("alignment/harmonic_resonance.py", "consonance_score"), ("alignment/harmonic_resonance.py", "analyse_frequency_harmony"), ("alignment/harmonic_resonance.py", "compute_phase_coherence"), ("alignment/harmonic_resonance.py", "derive_phase"), ("alignment/harmonic_resonance.py", "geometric_mean"), ("alignment/harmonic_resonance.py", "full_harmonic_analysis"), ("alignment/harmonic_resonance.py", "HarmonicAnalysis.to_dict"), ("alignment/pillar_alignment.py", "AlignmentCycleResult.to_dict"), ("alignment/pillar_alignment.py", "get_pillar_alignment"), ("alignment/unified_directive.py", "MasterDirective.to_dict"), ("generated/research_cinema/harmonic_nexus_score_model.py", "build_default_inputs"), ("generated/research_cinema/harmonic_nexus_score_model.py", "HarmonicNexusScoreInputs.normalized"), ("generated/research_cinema/harmonic_nexus_score_model.py", "harmonic_nexus_score"), ("generated/research_cinema/harmonic_nexus_score_model.py", "score_breakdown"), ("swarm/druidic_council.py", "voice_for_gamma"), ("swarm/fleadh.py", "steer_flow"), ("swarm/druidic_council.py", "build_seat_receipt"), ("swarm/agent.py", "SwarmAgent.substrate"), ("swarm/agent.py", "SwarmAgent.to_dict"), ("swarm/agent.py", "SwarmAgent.propose"), ("swarm/coherence.py", "ClusterCoherence.gamma"), ("swarm/coherence.py", "ClusterCoherence.to_dict"), ("swarm/memory_bus.py", "CausalEchoBus.echo"), ("swarm/memory_bus.py", "CausalEchoBus.to_dict"), ("swarm/steering.py", "SteeringField.steer"), ("swarm/druidic_council.py", "SeatReceipt.to_dict"), ("swarm/druidic_council.py", "CouncilReceipt.to_dict"), ("swarm/queen_gate.py", "Actualization.to_dict"), ("swarm/agent.py", "SwarmAgent.update"), }
def reachable_entries() -> list[dict[str, Any]]: """Entry points body_call will run while the call-sweep gate is open."""
import aureon_public.body as body_module
body_module.enable_sweep_measurement() from aureon_public.body import _inventory, _plan_stage, public_entry_refusal
seen: set[tuple[str, str]] = set() found = [] rows, _index = _inventory() for row in rows: if row["server"] != "public" or row["kind"] not in {"function", "method"}: continue key = (str(row["module"]), str(row["symbol"])) if key in seen: continue seen.add(key) if public_entry_refusal(row) is not None: continue found.append( { "module": key[0], "package": str(row["package"]), "plan_stage": _plan_stage(str(row["package"])), "symbol": key[1], } ) return found
def hazard_reason(payload: dict[str, Any]) -> str | None: """The refusal sentence for one call. None when the call stayed inside the rules."""
bad = payload.get("bad") or [] sockets = payload.get("socket") or [] processes = payload.get("process") or [] writes = payload.get("writes") or [] if bad or sockets: return "call loads a banned chain or opens a connection" if processes: return "call starts a process" if writes: return "call writes outside the sandbox" return None
def child_main(module: str, symbol: str, arguments_json: str = "") -> None: import aureon_public.body as body_module from aureon_public.sweep_guard import declare_sandbox
declare_sandbox() body_module.enable_sweep_measurement() text = body_module.body_call(module, symbol, arguments_json) try: body = json.loads(text) except json.JSONDecodeError: body = {"status": "unavailable", "reason": "result was not JSON"} report = body_module.last_sweep_report or {} json.dump( { "bad": list(report.get("modules") or []), "called": body.get("called") is True, "process": list(report.get("processes") or []), "reason": body.get("reason"), "sandbox_writes": list(report.get("sandbox_writes") or []), "socket": list(report.get("sockets") or []), "status": body.get("status"), "writes": list(report.get("writes") or []), }, sys.stdout, )
def _one(module: str, symbol: str, timeout: float, arguments_json: str = "") -> dict[str, Any]: command = [ sys.executable, "-m", "aureon_public.call_sweep", "--module", module, "--symbol", symbol, ] if arguments_json: command.extend(["--arguments", arguments_json]) try: completed = subprocess.run( command, cwd=os.environ.get("TMPDIR") or "/tmp", capture_output=True, text=True, timeout=timeout, check=False, env={key: value for key, value in os.environ.items() if key != "AUREON_PUBLIC_SWEEP"}, ) except subprocess.TimeoutExpired: return { "bad": [], "called": False, "error": "sweep exceeded the timeout", "process": [], "socket": [], "status": "unavailable", "writes": [], } if not completed.stdout.strip(): return { "bad": [], "called": False, "error": f"sweep exited {completed.returncode}", "process": [], "socket": [], "status": "unavailable", "writes": [], } try: payload = json.loads(completed.stdout) except json.JSONDecodeError: return { "bad": [], "called": False, "error": "sweep result was not JSON", "process": [], "socket": [], "status": "unavailable", "writes": [], } return payload if isinstance(payload, dict) else {}
def _first_hazard(hazards: list[str]) -> str | None: order = ( "call loads a banned chain or opens a connection", "call starts a process", "call writes outside the sandbox", "call did not finish", ) for sentence in order: if sentence in hazards: return sentence return None
def _stage1_extra_attempts(module: str, symbol: str) -> list[dict[str, Any]]: """Real stage-1 arguments copied from tests/test_swarm_hive.py."""
if (module, symbol) != ("swarm/agent.py", "SwarmAgent.update"): return [] return [ { "arguments": { "cluster_states": [], "context": [0.4, 0.2, -0.1, 0.3, 0.0, 0.1, -0.2, 0.05], "echo": None, "init": { "actions": ["hold", "advance", "retreat"], "agent_id": "a1", "role": "research", }, }, "label": "hive_first_update", "note": "The first update call in test_agent_keeps_a_normalized_soft_simplex. Empty cluster and no echo.", "source": "tests/test_swarm_hive.py", } ]
def build_record(timeout: float) -> dict[str, Any]: from aureon_public.guard_loader import aureon_source from aureon_public.measurement_stamp import measurement_stamp from aureon_public.sweep_layout import layout_record
from aureon_public.stage2_arguments import attempts_for
source = aureon_source() stamp = measurement_stamp() tested = _tested_stage1_tools() entries = [] for row in reachable_entries(): print(f"{row['module']} {row['symbol']}", file=sys.stderr) planned = [ { "arguments": {}, "label": "no_arguments", "note": "No arguments.", "source": None, } ] if row["plan_stage"] == 2: planned.extend(attempts_for(row["module"], row["symbol"])) planned.extend(_stage1_extra_attempts(row["module"], row["symbol"])) recorded = [] hazards: list[str] = [] for attempt in planned: if attempt.get("fixture"): arguments_json = json.dumps({"__sweep_fixture__": attempt["fixture"]}) shown: dict[str, Any] = {"__sweep_fixture__": attempt["fixture"]} else: arguments = attempt.get("arguments") if isinstance(attempt.get("arguments"), dict) else {} arguments_json = json.dumps(arguments) if arguments else "" shown = arguments if isinstance(arguments, dict) else {} payload = _one(row["module"], row["symbol"], timeout, arguments_json) reason = hazard_reason(payload) if reason: hazards.append(reason) elif row["plan_stage"] == 2 and payload.get("error"): hazards.append("call did not finish") reason = "call did not finish" recorded.append( { "arguments": shown, "bad": [str(item) for item in payload.get("bad") or []], "called": payload.get("called") is True, "error": payload.get("error"), "label": attempt.get("label"), "note": attempt.get("note"), "process": [str(item) for item in payload.get("process") or []], "reason": payload.get("reason"), "refusal": reason, "sandbox_writes": [str(item) for item in payload.get("sandbox_writes") or []], "socket": [str(item) for item in payload.get("socket") or []], "source": attempt.get("source"), "status": payload.get("status"), "writes": [str(item) for item in payload.get("writes") or []], } ) first = recorded[0] refusal = _first_hazard(hazards) key = (row["module"], row["symbol"]) entries.append( { "attempts": recorded, "bad": first["bad"], "called": first["called"], "error": first["error"], "module": row["module"], "package": row["package"], "plan_stage": row["plan_stage"], "process": first["process"], "reason": first["reason"], "refusal": refusal, "refused": refusal is not None, "sandbox_writes": sorted( {item for attempt in recorded for item in attempt["sandbox_writes"]} ), "socket": first["socket"], "status": first["status"], "symbol": row["symbol"], "tested_stage1_tool": key in tested, "writes": first["writes"], } ) from aureon_public.sweep_layout import beside
home = beside() / "home" return { "aureon_source": source, "entries": entries, "layout": layout_record(), "user_dirs": { "HOME": str(home), "USERPROFILE": str(home), "XDG_CACHE_HOME": str(home / ".cache"), "XDG_CONFIG_HOME": str(home / ".config"), "XDG_DATA_HOME": str(home / ".local" / "share"), "XDG_RUNTIME_DIR": str(beside() / "runtime"), "XDG_STATE_HOME": str(home / ".local" / "state"), }, "processes": "blocked", "sockets": "blocked", "writes": "outside sandbox blocked", **stamp, }
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-call-sweep") parser.add_argument("--module") parser.add_argument("--symbol") parser.add_argument("--arguments", default="") parser.add_argument("--out", type=Path) parser.add_argument("--timeout", type=float, default=45.0) args = parser.parse_args(argv) if args.module or args.symbol: if not args.module or not args.symbol: raise SystemExit("module and symbol are both required") child_main(args.module, args.symbol, args.arguments) return record = build_record(args.timeout) text = json.dumps(record, indent=2, sort_keys=True) + "\n" if args.out is None: sys.stdout.write(text) return args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(text, encoding="utf-8")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243"""Run one inventoried call in this process. The parent kills the process group on timeout."""
from __future__ import annotations
import enumimport inspectimport jsonimport osimport sysfrom datetime import datefrom pathlib import Pathfrom typing import Any
def _plain(value: Any, depth: int = 0) -> Any: if depth > 4: return type(value).__name__ if value is None or isinstance(value, (str, int, float, bool)): if isinstance(value, float) and value != value: return None if isinstance(value, str): return value[:500] return value if isinstance(value, enum.Enum): return _plain(value.value, depth + 1) if isinstance(value, dict): return {str(key): _plain(item, depth + 1) for key, item in list(value.items())[:30]} if isinstance(value, (list, tuple)): return [_plain(item, depth + 1) for item in list(value)[:30]] if hasattr(value, "to_dict") and callable(value.to_dict): try: return _plain(value.to_dict(), depth + 1) except Exception: pass if hasattr(value, "__dict__") and not isinstance(value, type): fields = {key: item for key, item in vars(value).items() if not str(key).startswith("_")} return {"type": type(value).__name__, "fields": _plain(fields, depth + 1)} return {"type": type(value).__name__}
def _inventory_path(cls: type) -> str: """Inventory module path for a class. ``aureon.`` is the package prefix."""
module = cls.__module__ if module.startswith("aureon."): module = module[len("aureon.") :] return module.replace(".", "/") + ".py"
def _post_init_defined(cls: type) -> bool: """True when ``__post_init__`` is defined anywhere on the class MRO."""
return any("__post_init__" in base.__dict__ for base in cls.__mro__)
def _dataclass_from_dict(fn: Any, annotation: Any, value: Any) -> Any | None: """Build an allowlisted dataclass from a JSON object.
The class is resolved from the annotation, including a name in the function's globals, then checked by its own module. A class from another package is not built unless that class is on ``_CONSTRUCTOR_ALLOWLIST``.
A generated dataclass ``__init__`` has code filename ``<string>`` and still calls ``__post_init__``. Any class that defines ``__post_init__`` on its MRO is refused and is not constructed. """
if not isinstance(value, dict): return None cls = annotation if isinstance(annotation, str): cls = fn.__globals__.get(annotation) or fn.__globals__.get(annotation.split(".")[-1]) if not isinstance(cls, type) or not hasattr(cls, "__dataclass_fields__"): return None code = getattr(getattr(cls, "__init__", None), "__code__", None) if code is None or code.co_filename != "<string>": return None from aureon_public.body import _CONSTRUCTOR_ALLOWLIST
if (_inventory_path(cls), cls.__name__) not in _CONSTRUCTOR_ALLOWLIST: return None if _post_init_defined(cls): return None if not set(value).issubset(cls.__dataclass_fields__): return None return cls(**value)
def _coerce(fn: Any, kwargs: dict[str, Any]) -> dict[str, Any]: try: signature = inspect.signature(fn) except (TypeError, ValueError): return kwargs coerced = dict(kwargs) for name, value in list(coerced.items()): param = signature.parameters.get(name) if param is None: continue annotation = param.annotation origin = getattr(annotation, "__origin__", None) name_of = annotation if isinstance(annotation, str) else getattr(annotation, "__name__", "") if (annotation is date or name_of == "date" or str(name_of).endswith("date")) and isinstance(value, str): coerced[name] = date.fromisoformat(value) elif (annotation is frozenset or origin is frozenset) and isinstance(value, list): coerced[name] = frozenset(value) else: built = _dataclass_from_dict(fn, annotation, value) if built is not None: coerced[name] = built return coerced
def _drop_checkout_root() -> None: """The Space guard puts the checkout on sys.path. The worker must not keep it."""
from aureon_public.paths import repo_root
root = repo_root().resolve() kept: list[str] = [] for entry in sys.path: if not entry: continue try: if Path(entry).resolve() == root: continue except OSError: kept.append(entry) continue kept.append(entry) sys.path[:] = kept
def _load(dotted: str, module_rel: str) -> Any: del module_rel if dotted != "aureon" and not dotted.startswith("aureon."): raise RuntimeError("only an aureon module can be loaded") from aureon_public.guard_loader import apply_space_guard from aureon_public.pin_blob import ( import_through_finder, install_pinned_aureon_finder, refuse_preseeded_aureon, )
install_pinned_aureon_finder() apply_space_guard() _drop_checkout_root() refuse_preseeded_aureon() return import_through_finder(dotted)
def _call(dotted: str, symbol: str, arguments: dict[str, Any], module_rel: str) -> Any: imported = _load(dotted, module_rel) if os.environ.get("AUREON_PUBLIC_SWEEP") == "1" and isinstance(arguments.get("__sweep_fixture__"), str): from aureon_public.stage2_arguments import resolve_fixture
arguments = resolve_fixture(str(arguments["__sweep_fixture__"])) if "." not in symbol: fn = getattr(imported, symbol) return fn(**_coerce(fn, arguments)) class_name, method_name = symbol.rsplit(".", 1) cls = getattr(imported, class_name) init_args = arguments.get("init") if isinstance(arguments.get("init"), dict) else {} method_args = {key: value for key, value in arguments.items() if key != "init"} signature = inspect.signature(cls.__init__) parameters = [name for name in signature.parameters if name != "self"] init_args = {key: value for key, value in init_args.items() if key in parameters} instance = cls(**_coerce(cls.__init__, init_args)) method = getattr(instance, method_name) return method(**_coerce(method, method_args))
def _install_sweep_guard() -> None: """Block sockets, process starts, and writes outside the sandbox.
Used only while the call sweep is measuring. The server refuses to start when AUREON_PUBLIC_SWEEP is set. """
if os.environ.get("AUREON_PUBLIC_SWEEP") != "1": return from aureon_public.sweep_guard import install_sweep_guard
install_sweep_guard()
def _sweep_modules() -> list[str]: from aureon_public.stage2_import_sweep import is_http_client
banned = [] for name in sys.modules: if any(marker in name for marker in ("inhouse_ai", "ollama_config")): banned.append(name) continue if name in {"aureon.queen", "aureon.miner", "aureon.swarm_motion"} or name.startswith( ("aureon.queen.", "aureon.miner.", "aureon.swarm_motion.") ): banned.append(name) continue if is_http_client(name): banned.append(name) return sorted(banned)
def main() -> None: _install_sweep_guard() real_stdout = sys.stdout sys.stdout = sys.stderr try: job = json.loads(sys.stdin.read() or "{}") result = _call( str(job["dotted"]), str(job["symbol"]), dict(job.get("arguments") or {}), str(job["module"]), ) payload = {"ok": True, "result": _plain(result)} except SystemExit: payload = {"ok": False, "error": "SystemExit"} except Exception as exc: payload = {"ok": False, "error": f"{type(exc).__name__}: {exc}"[:240]} if os.environ.get("AUREON_PUBLIC_REPORT_MODULES") == "1": payload["modules"] = sorted( name for name in sys.modules if "inhouse_ai" in name or "ollama_config" in name ) if os.environ.get("AUREON_PUBLIC_SWEEP") == "1": from aureon_public.sweep_guard import snapshot
snap = snapshot() payload["sweep"] = { "modules": _sweep_modules(), "processes": snap["processes"], "sandbox_writes": snap["sandbox_writes"], "sockets": snap["sockets"], "writes": snap["writes"], } sys.stdout = real_stdout real_stdout.write(json.dumps(payload))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506"""Write mcp/aureon_public/COVERAGE_PLAN.md from the pinned inventory.
Every count comes from docs/mcp/inventory.json and public_entry_refusal.The file is refused when its sha256 is not INVENTORY_SHA256.
env -u PYTHONPATH PYTHONPATH=mcp python3.12 -m aureon_public.coverage_plan --check env -u PYTHONPATH PYTHONPATH=mcp python3.12 -m aureon_public.coverage_plan --write"""
from __future__ import annotations
import argparseimport jsonfrom collections import defaultdictfrom pathlib import Path
from aureon_public.body import ( _BLOCKED, _CONSTRUCTOR_ALLOWLIST, INVENTORY_SHA256, _inventory, package_depth, public_entry_refusal,)from aureon_public.paths import repo_root
PLAN_PATH = Path("mcp") / "aureon_public" / "COVERAGE_PLAN.md"FENCE = set(_BLOCKED) | {"unified_margin_trader"}
STAGE_TITLE = { 1: "Deterministic read-only", 2: "Read-only with a process or write mark", 3: "Operator-scoped, no key, order, or fetch mark", 4: "Keys, orders, network, and the refused-imports fence",}
def safety_category(text: str) -> str: """One category for an inventory safety sentence. The words are the scanner's."""
if text.startswith("personal or key") or "reads keys" in text: return "key" if "order" in text or "live_orders" in text: return "order" if text.startswith("live public fetch"): return "fetch" if text.startswith("process") or "UI start" in text or "loop" in text: return "process" if "write" in text and "no repo write" not in text: return "write" if "risky token" in text: return "risky" if "operator-scoped" in text or "no public import" in text: return "operator" if text.startswith("runs from inputs"): return "pure" if "module surface" in text: return "surface" if "file does not parse" in text: return "parse" return "other"
def stage_for(package: str, categories: set[str]) -> int: """Earlier stages are the safer reads. Stage 4 stays behind the fence."""
# compose_repository_layers loads core.organism_composition, which imports # aureon.inhouse_ai.llm_adapter, agent_runner, orchestrator, # aureon.ollama_config, and aureon.autonomous.aureon_internal_coding_workforce. # inhouse_ai is excluded. That chain is not a stage-1 read. if package == "organism": return 4 if package in FENCE or "order" in categories or "key" in categories or "fetch" in categories: return 4 if "process" in categories or "write" in categories: return 2 if "operator" in categories and "pure" not in categories: return 3 return 1
def _rows() -> tuple[list[dict], dict[str, dict[str, int]]]: loaded, _index = _inventory() if not loaded: raise SystemExit("inventory did not load") return loaded, package_depth()
def tested_keys() -> set[tuple[str, str]]: """Entry points a public tool calls and a test exercises."""
from aureon_public.call_sweep import _tested_stage1_tools from aureon_public.stage2_layer import TESTED
return set(_tested_stage1_tools()) | set(TESTED)
def _tested_counts(loaded: list[dict]) -> dict[str, int]: """Reachable public entry points that a tool calls. A refused point is not tested."""
wanted = tested_keys() counts: dict[str, int] = defaultdict(int) seen: set[tuple[str, str]] = set() for row in loaded: if row["server"] != "public" or row["kind"] not in {"function", "method"}: continue key = (str(row["module"]), str(row["symbol"])) if key in seen or key not in wanted: continue seen.add(key) if public_entry_refusal(row) is None: counts[str(row["package"])] += 1 return counts
def plan_rows() -> list[dict]: """One row per package. Counts are the pinned inventory and the current guard."""
loaded, depth = _rows() by_package: dict[str, list[dict]] = defaultdict(list) for row in loaded: by_package[row["package"]].append(row) opened = _opened_by_allowlist(loaded) tested = _tested_counts(loaded) rows = [] for package in sorted(by_package): items = by_package[package] categories = {safety_category(str(item.get("safety") or "")) for item in items} stage = stage_for(package, categories) counted = depth[package] rows.append( { "categories": sorted(categories), "fence": package in FENCE or "order" in categories, "listed": len(items), "opened_by_allowlist": opened.get(package, 0), "package": package, "public_entry_points": counted["public_entry_points"], "reachable": counted["reachable"], "refused": counted["public_entry_points"] - counted["reachable"], "stage": stage, "tested": tested.get(package, 0), } ) rows.sort(key=lambda row: (row["stage"], row["package"])) return rows
def _opened_by_allowlist(loaded: list[dict]) -> dict[str, int]: """Reachable methods whose class is allowlisted. Those were refused before the list."""
counts: dict[str, int] = defaultdict(int) seen: set[tuple[str, str]] = set() for row in loaded: if row["kind"] != "method" or row["server"] != "public": continue key = (str(row["module"]), str(row["symbol"])) if key in seen: continue seen.add(key) class_name = str(row["symbol"]).rsplit(".", 1)[0] if (str(row["module"]), class_name) not in _CONSTRUCTOR_ALLOWLIST: continue if public_entry_refusal(row) is None: counts[str(row["package"])] += 1 return counts
def _excluded_packages() -> list[str]: from aureon_public.more_layers import UPDATES
return sorted(package for package, kind, _reason in UPDATES if kind == "excluded")
def _read_json(name: str) -> dict: path = repo_root() / "measured" / name try: loaded = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return {} return loaded if isinstance(loaded, dict) else {}
def _stage2_lines() -> list[str]: """What this run opened, refused, and left without a tool."""
from aureon_public.stage2_arguments import NOT_A_TOOL
imports = _read_json("aureon_public_stage2_imports.json") calls = _read_json("aureon_public_call_sweep.json") lines = [ "Stage 2 tools call through `dispatch`. The inputs are the tests and committed files named on each tool. `atn` stays excluded because its modules load an HTTP client. `conversion` has no public function or method and stays excluded. The constructor allowlist, the `__post_init__` refusal, the `AUREON_PUBLIC_SWEEP` start refusal, and the pin check are unchanged.", "Import refusals:", ] modules = [row for row in imports.get("modules") or [] if isinstance(row, dict) and row.get("refused")] if not modules: lines.append("- none recorded") for row in sorted(modules, key=lambda item: str(item.get("module"))): lines.append( f"- `{row.get('module')}`: {row.get('refusal') or 'module import loads an adapter or http client'}" ) lines.append("Import errors that are not refusals:") errors = [ row for row in imports.get("modules") or [] if isinstance(row, dict) and row.get("error") and not row.get("refused") ] if not errors: lines.append("- none recorded") for row in sorted(errors, key=lambda item: str(item.get("module"))): lines.append(f"- `{row.get('module')}`: {row.get('error')}") lines.append("Call refusals from the sweep:") entries = [ row for row in calls.get("entries") or [] if isinstance(row, dict) and row.get("refused") ] if not entries: lines.append("- none recorded") for row in sorted(entries, key=lambda item: (str(item.get("module")), str(item.get("symbol")))): extra = [] for attempt in row.get("attempts") or []: if isinstance(attempt, dict) and attempt.get("process"): extra.append("The same call started a process. The sweep blocked it.") if isinstance(attempt, dict) and attempt.get("writes"): extra.append("The same call wrote outside the sandbox. The sweep blocked it.") suffix = (". " + " ".join(dict.fromkeys(extra))) if extra else "" lines.append( f"- `{row.get('module')}` `{row.get('symbol')}`: {row.get('refusal') or 'call loads a banned chain or opens a connection'}{suffix}" ) from aureon_public.body import _ENTRY_REFUSAL, _UNTESTED_STAGE2, lookup, public_entry_refusal
lines.append( "These five were reachable and had no tool. `body_call` and `dispatch` refuse them. The constructor allowlist is unchanged." ) for key in sorted(item for item, reason in _ENTRY_REFUSAL.items() if reason == _UNTESTED_STAGE2): lines.append(f"- `{key[0]}` `{key[1]}`: {_UNTESTED_STAGE2}. {NOT_A_TOOL[key]}") still = [] for key in sorted(NOT_A_TOOL): row = lookup(key[0], key[1]) if row is not None and public_entry_refusal(row) is None: still.append(key) if still: lines.append("These stage-2 entry points are still reachable and are not tools:") for key in still: lines.append(f"- `{key[0]}` `{key[1]}`. {NOT_A_TOOL[key]}") return lines
def _public_keys() -> dict[int, list[tuple[str, str]]]: """Reachable public entry points, by coverage-plan stage."""
from aureon_public.body import _inventory, _plan_stage, public_entry_refusal
seen: set[tuple[str, str]] = set() found: dict[int, list[tuple[str, str]]] = defaultdict(list) rows, _index = _inventory() for row in rows: if row["server"] != "public" or row["kind"] not in {"function", "method"}: continue key = (str(row["module"]), str(row["symbol"])) if key in seen: continue seen.add(key) if public_entry_refusal(row) is not None: continue found[_plan_stage(str(row["package"]))].append(key) for keys in found.values(): keys.sort() return found
def _reconciliation_lines() -> list[str]: """How reachable and tested moved from main c1ae468d to this tree.
Main recorded 85 reachable: stage 1 was 39 and stage 2 was 46. Stage 1 tested 29 entry points and stage 2 tested none. A tool does not create a new reachable row. """
from aureon_public.body import _ENTRY_REFUSAL, _UNTESTED_STAGE2 from aureon_public.call_sweep import _tested_stage1_tools from aureon_public.stage2_layer import TESTED
reachable = _public_keys() stage1_tested = sorted(_tested_stage1_tools()) stage2_tested = sorted(TESTED) stage1_now = set(reachable.get(1, [])) stage2_now = set(reachable.get(2, [])) dropped = [key for key in stage1_tested if key not in stage1_now] untested_stage1 = [key for key in reachable.get(1, []) if key not in set(stage1_tested)] lines = [ "## Count reconciliation", "", "Main `c1ae468d` recorded reachable 85. Stage 1 was 39 (alignment 11, generated 4, swarm 24). Stage 2 was 46 (atn 0, cognition 1, conversion 0, decoders 5, evaluation 7, gates 3, observer 29, s51 1). 39 + 46 = 85. Tested on that main was the 29 stage-1 tool entry points below. Stage 2 tested was 0. Registering a tool does not add a reachable row. The tool calls an entry point that was already reachable.", f"Stage 1 reachable now: {len(stage1_now)}. Stage 2 reachable now: {len(stage2_now)}. {len(stage1_now)} + {len(stage2_now)} = {len(stage1_now) + len(stage2_now)}.", f"Stage 1 tested now: {len(stage1_tested)}. Stage 2 tested now: {len(stage2_tested)}. {len(stage1_tested)} + {len(stage2_tested)} = {len(stage1_tested) + len(stage2_tested)}.", "Every stage-1 entry point that was tested on main is still tested. None dropped out:", ] if dropped: lines.append("Stage-1 tested entry points that are no longer reachable:") for module, symbol in dropped: lines.append(f"- `{module}` `{symbol}`") else: lines.append("No stage-1 tested entry point dropped out.") for module, symbol in stage1_tested: lines.append(f"- `{module}` `{symbol}`") if untested_stage1: lines.append("Stage 1 reachable entry points that are still not tested:") for module, symbol in untested_stage1: lines.append(f"- `{module}` `{symbol}`") else: lines.append("Stage 1 has no reachable entry point left untested.") lines.append( "Stage 2 reachable fell by 7, from 46 to 39, on the stage-2 run. The call sweep refused `self_coder_report`. Five reachable entry points had no tool. `log_blocked_fallback` would write a fallback log for an event that did not happen, so `body_call` refuses it. This follow-up then closes the 10 stage-1 points that were reachable and not tested. Nine are refused. `SwarmAgent.update` is tested on the hive fixture." ) calls = _read_json("aureon_public_call_sweep.json") self_coder = next( ( row for row in calls.get("entries") or [] if isinstance(row, dict) and row.get("module") == "evaluation/measured_proof.py" and row.get("symbol") == "self_coder_report" ), None, ) if isinstance(self_coder, dict): lines.append( f"- `evaluation/measured_proof.py` `self_coder_report`: {self_coder.get('refusal') or 'refused by the call sweep'}." ) else: lines.append( "- `evaluation/measured_proof.py` `self_coder_report`: refused by the call sweep. The record names the reason." ) for key in sorted(item for item, reason in _ENTRY_REFUSAL.items() if reason == _UNTESTED_STAGE2): lines.append(f"- `{key[0]}` `{key[1]}`: {_UNTESTED_STAGE2}.") lines.append( "- `observer/live_data_policy.py` `log_blocked_fallback`: " "fallback log is not emitted for an event that did not happen." ) for key, reason in sorted(_ENTRY_REFUSAL.items()): if str(key[0]).startswith("swarm/"): lines.append(f"- `{key[0]}` `{key[1]}`: {reason}.") total = len(stage1_now) + len(stage2_now) tested_total = len(stage1_tested) + len(stage2_tested) if ( len(stage1_now) != 30 or len(stage2_now) != 39 or len(stage1_tested) != 30 or len(stage2_tested) != 39 or dropped or untested_stage1 or total != 69 or tested_total != 69 ): raise RuntimeError( "count reconciliation drifted: " f"stage1 {len(stage1_now)} tested {len(stage1_tested)}; " f"stage2 {len(stage2_now)} tested {len(stage2_tested)}; " f"dropped {dropped}" ) lines.append( "Main `cf43882e` recorded reachable 78 and tested 68. This follow-up refuses nine stage-1 entry points and tests `SwarmAgent.update`. Reachable and tested are both 69. 30 + 39 = 69." ) return lines
def render() -> str: rows = plan_rows() listed = sum(row["listed"] for row in rows) public = sum(row["public_entry_points"] for row in rows) reachable = sum(row["reachable"] for row in rows) tested = sum(row["tested"] for row in rows) refused = sum(row["refused"] for row in rows) opened = sum(row["opened_by_allowlist"] for row in rows) excluded = _excluded_packages() first = next(row["package"] for row in rows if row["stage"] == 1) lines = [ "# Public MCP coverage plan", "", "Counts are the pinned `docs/mcp/inventory.json`. A public entry point is a public function or method. Reachable means `public_entry_refusal` returns None, so `body_call` will run it. A listed module or class is not an entry point. The sha256 below is `INVENTORY_SHA256`. A different inventory file is not loaded.", "", f"Inventory sha256: `{INVENTORY_SHA256}`", "", "Reproduce:", "", "```bash", "env -u PYTHONPATH PYTHONPATH=mcp python3.12 -m aureon_public.coverage_plan --check", "bash measured/aureon_public_stage1_run.sh", "bash measured/aureon_public_stage2_sweep.sh", "bash measured/aureon_public_call_sweep.sh", "bash measured/aureon_public_protocol_run.sh", "bash measured/aureon_public_space_run.sh", "env -u PYTHONPATH /tmp/aureon-public-venv/bin/python -m pytest tests/test_aureon_public_mcp.py tests/test_aureon_body.py tests/bio/test_mcp_interior_attribution.py tests/bio/test_mcp_membrane.py tests/bio/test_mcp_transport.py tests/test_aureon_public_alignment.py tests/test_aureon_public_stage1.py tests/test_aureon_public_stage2.py tests/test_aureon_public_protocol.py tests/test_aureon_public_space.py --tb=line", "```", "", "That pytest command is the gate. It runs in `/tmp/aureon-public-venv`, the venv `measured/aureon_public_stage1_run.sh` creates (`VENV` overrides the path). The file list is `tests/test_aureon_public_mcp.py`, `tests/test_aureon_body.py`, `tests/bio/test_mcp_interior_attribution.py`, `tests/bio/test_mcp_membrane.py`, `tests/bio/test_mcp_transport.py`, `tests/test_aureon_public_alignment.py`, `tests/test_aureon_public_stage1.py`, `tests/test_aureon_public_stage2.py`, `tests/test_aureon_public_protocol.py`, and `tests/test_aureon_public_space.py`. `tests/test_async_socket_isolation.py` is not in the gate list. It imports `pytest_socket`, and `mcp/aureon_public/test-requirements.txt` does not install that plugin.", "", "`--write` rewrites this file from the same function. `measured/aureon_public_stage1_run.sh` installs `mcp/aureon_public/requirements.txt` and `mcp/aureon_public/test-requirements.txt`, then rewrites both `measured/aureon_public_alignment.json` and `measured/aureon_public_stage1.json`. It writes those two files under a temp directory first and copies them into `measured/` only after both stamps have finished. `measurement_stamp` raises `RuntimeError` when `git status --porcelain` is not empty, so the second stamp must not see the first file. `test-requirements.txt` is the test install: pytest, pytest-timeout, flask, pandas, and scipy. It is not the public server runtime. `measured/aureon_public_stage2_sweep.sh` and `measured/aureon_public_call_sweep.sh` copy the checkout with `cp -a` under an ordinary temp parent, place fake `NEXUS-LIVE-FEED-` and `Aureon-Trading--Project-Sero` checkouts beside that copy, block sockets, and rewrite their measured records. Each sweep record names the pin, the `aureon/` tree hash beside that pin, the `aureon_source` kind, and that temp parent. `measured/aureon_public_protocol_run.sh` starts this server over stdio and over Streamable HTTP bound to `127.0.0.1`, with `AUREON_PUBLIC_REQUIRE_PIN=1`. An MCP SDK 1.30.0 client calls `tools/list`, `resources/list`, `prompts/list`, and one `tools/call` (`alignment_consonance_read` with ratio 1.0). The raw pages are `measured/aureon_public_protocol.json`. `measured/aureon_public_space_run.sh` starts `python -m aureon_public.space` with `AUREON_PUBLIC_API_KEY` set and records the same client calling `tools/list` and `tools/call` on `127.0.0.1`. The raw pages are `measured/aureon_public_space.json`. These measured records name `code_commit`, the parent of the commit that contains the record file. A record cannot name the commit that adds the file.", "", f"Listed symbols: {listed}. Public entry points: {public}. Reachable now: {reachable}. Tested: {tested}. Refused: {refused}. The plan on main recorded 879 reachable. An earlier draft head of the stage-1 PR recorded 89 reachable, before the call sweep. Methods open because a constructor is allowlisted: {opened}. The refused-imports fence is unchanged.", "Reachable means `public_entry_refusal` returns None. Tested means a public tool calls that entry point and `tests/test_aureon_public_stage1.py` or `tests/test_aureon_public_stage2.py` exercises the tool. Refused means a public entry point the server will not run. Plan stages 3 and 4 stay closed. The call sweep calls every entry point that was still reachable, with no arguments, and calls each stage-2 entry point again with the real arguments in `stage2_arguments.py`. `SwarmAgent.update` is also called with the hive fixture named below. It refuses one that opens a connection, starts a process, writes outside the sandbox, or loads queen, miner, swarm_motion, inhouse_ai, ollama_config, or an HTTP client. `get_unified_directive` is refused that way. It does not build the queen and miner bridges.", "", "## Stage order", "", "The stage is the inventory safety text, not a new scan.", "", "1. Deterministic read-only. No key, order, live-fetch, process, or write sentence, and the package is not operator-only.", "2. A process or write sentence, and still no key, order, or live-fetch sentence.", "3. Operator-scoped, with no pure public row and no key, order, or live-fetch sentence.", "4. Last. Any key, order, or live-fetch sentence, plus the refused-imports fence. The fence is `_BLOCKED` and `unified_margin_trader`. This run does not add to it and does not import it.", "", f"Packages still excluded by `more_layers`: {', '.join(excluded)}. `generated` left that list because its score model is deterministic and does not fetch. The other exclusions stay.", "", f"Within a stage, packages are alphabetical. The first package is `{first}`.", "Stage 1 is the deterministic read-only packages. This run opens generated and swarm, after alignment. Organism is stage 4 because its join loads the in-house adapter chain.", "Stage 2 is open. A stage-2 module whose import loads an adapter or an HTTP client, starts a process, or writes outside the sandbox is refused. A stage-2 entry point is refused when the no-argument call or a real-argument call does any of those, or does not finish. `atn` stays excluded. `conversion` has no public function or method and stays excluded.", "", "## Counts", "", "| Stage | Package | Listed | Public entry points | Reachable now | Tested | Refused |", "| ---: | --- | ---: | ---: | ---: | ---: | ---: |", ] for row in rows: lines.append( f"| {row['stage']} | {row['package']} | {row['listed']} | {row['public_entry_points']} | {row['reachable']} | {row['tested']} | {row['refused']} |" ) lines.extend( [ "", "## Fence", "", "These packages are stage 4 because they are on the refused-imports fence or an inventory row says order. `body_call` returns `live_orders: refused` and does not import them.", "", ] ) for name in sorted(FENCE): lines.append(f"- `{name}`") by_name = {row["package"]: row for row in rows} queen_stage = by_name["queen"]["stage"] miner_stage = by_name["miner"]["stage"] both_open = max(queen_stage, miner_stage) lines.extend( [ "", f"## Stage {both_open}", "", f"`alignment/unified_directive.py` `get_unified_directive` is not a stage-1 tool. Queen is stage {queen_stage}. Miner is stage {miner_stage}. `body_call` refuses it now. The no-argument call is in the call sweep.", "", "Calling `get_unified_directive` constructs `UnifiedHarmonicDirective` with auto-wire on. That constructs `QueenAIBridge` and `MinerAIBridge`. Each bridge loads `AureonBrainAdapter` as the reasoning backend when the Ollama switchboard is missing or unhealthy, and each bridge wires itself to a `ThoughtBus`. The call imports `aureon.queen`, `aureon.miner`, and `aureon.swarm_motion`, and it attempted a connection to `127.0.0.1:11434`. The sweep blocked that socket.", "", "## This run", "", "`alignment` stays the first stage-1 package. `get_pillar_alignment` stays, with `auto_load_pillars` false. `get_unified_directive` is not a stage-1 tool. This run opens `generated` and `swarm`. `organism` is not opened.", "Generated was on the more_layers exclusion list. It is open because `aureon/generated/research_cinema/harmonic_nexus_score_model.py` imports only dataclasses and its module docstring calls it a deterministic helper, not trading authority. The four entry points are `build_default_inputs`, `HarmonicNexusScoreInputs.normalized`, `harmonic_nexus_score`, and `score_breakdown`. `tests/generated/test_harmonic_nexus_score_model.py` shows all-ones inputs score 100.0. That 100 is the weighted sum in that file. It does not score any Aureon or HNC claim and cannot be quoted as evidence.", "`body_call` refuses `organism/repository_layers.py` `compose_repository_layers`. With the checkout beside `NEXUS-LIVE-FEED-` and `Aureon-Trading--Project-Sero`, that call uses `Path(__file__).parents[3]`, independent of `AUREON_REPOS_ROOT`, and execs those sibling modules outside the pin. One call also loads `core.organism_composition`, and through that `aureon.inhouse_ai.llm_adapter`, `agent_runner`, `orchestrator`, `aureon.ollama_config`, and `aureon.autonomous.aureon_internal_coding_workforce`. `inhouse_ai` stays excluded. Organism reachable is 0.", "`body_call` refuses `swarm/capability_grid.py` `build_lane`. `build_lane(\"fintech\")` imports `aureon.accounting`, and that package init reaches `aureon.autonomous.aureon_internal_coding_workforce`, which imports `aureon.inhouse_ai` and `aureon.ollama_config`. Swarm reachable is 15.", "The swarm tools use fixtures from the swarm tests or fixed example arguments. `SwarmAgent.update` uses the first call in `tests/test_swarm_hive.py` `test_agent_keeps_a_normalized_soft_simplex`: agent `a1`, role `research`, actions hold, advance, and retreat, CONTEXT `[0.4, 0.2, -0.1, 0.3, 0.0, 0.1, -0.2, 0.05]`, an empty cluster, and no echo. The function returns None. Classes that need nested agent instances stay off the constructor allowlist: Cluster, Company, Zone, FleadhCompany, VisitorAgent, and WorkerAgent. Name-blocked `run_` entry points stay refused. `SwarmAgent.purity` and `ClusterCoherence.warm` are properties. The worker calls methods, so `body_call` and `dispatch` refuse them. `CausalEchoBus.possibilities` is refused because one call cannot park an ensemble and then read it. `issue_auris_node_receipt` needs a `TrustedAurisNodeResolver` that is not built from JSON. `validate_auris_node_receipt`, `validate_hnc_evidence`, `validate_provider_moment`, `validate_council_receipt`, and `validate_seat_receipt` are refused: the receipt is assembled by the test harness, and the public result cap would drop its fields.", *_stage2_lines(), *_reconciliation_lines(), "", "The pin stays `8aa6a2d971cc529484e2a5e261e28afafab4e4f4`. The alignment modules at this checkout match that pin, so the tools do not need a newer commit. `GUARD_BLOB` and `INVENTORY_SHA256` are unchanged.", "", "## MCP SDK", "", "This server imports `FastMCP` from `mcp.server.fastmcp` and passes `host`, `port`, and `streamable_http_path` to that constructor. The requirement is `mcp==1.30.0,<2` in `mcp/aureon_public/requirements.txt` and `mcp/pyproject.toml`. That specifier matches 1.30.0 and excludes every 2.x release. Migration to SDK v2 is a later decision.", "", "The claim that official Python SDK v2 renamed `FastMCP` to `MCPServer` was checked against the published package and the v2 source. The claim is true.", "", "- PyPI project `mcp`: `info.version` is 2.3.0. The newest 1.x release is 1.30.0. https://pypi.org/pypi/mcp/json", "- Release v2.0.0, published 28 July 2026, says `FastMCP` is now `MCPServer`, v1.x is maintenance-only on branch `v1.x`, and a project that is not migrating should keep a `<2` upper bound, for example `mcp>=1.28,<2`. https://github.com/modelcontextprotocol/python-sdk/releases/tag/v2.0.0", "- Migration guide, section `FastMCP` renamed to `MCPServer`: `from mcp.server.fastmcp import FastMCP` becomes `from mcp.server.mcpserver import MCPServer`. https://py.sdk.modelcontextprotocol.io/v2/migration/", "- Tag v2.0.0 and tag v2.3.0 `src/mcp/server/__init__.py` export `MCPServer` from `.mcpserver`. https://github.com/modelcontextprotocol/python-sdk/blob/v2.3.0/src/mcp/server/__init__.py", "- Tag v2.3.0 `src/mcp/server/mcpserver/server.py` defines `class MCPServer`. `MCPServer.__init__` takes no `host`, `port`, or `streamable_http_path`. Those arguments are on `run(transport=\"streamable-http\")`. The default name when none is passed is `mcp-server`. `instructions` is no longer the second positional parameter. https://github.com/modelcontextprotocol/python-sdk/blob/v2.3.0/src/mcp/server/mcpserver/server.py", "- `src/mcp/server/fastmcp/__init__.py` on tag v2.3.0 is not published. The raw URL returns HTTP 404. https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/v2.3.0/src/mcp/server/fastmcp/__init__.py", "- v1 documentation stays at https://py.sdk.modelcontextprotocol.io/v1/", "", "The same v2.0.0 notes also replace `ClientSession` plus the transport clients with `Client`, and the v2.3.0 constructor no longer accepts `host`, `port`, or `streamable_http_path`. This server still passes those three to `FastMCP`, and the measured client still uses `ClientSession`. Staying on 1.30.0 keeps that call shape.", "", "The protocol proof is the stdio session and the Streamable HTTP session bound to `127.0.0.1`. The Space scaffold is `mcp/aureon_public/Dockerfile` and `python -m aureon_public.space`. It is not deployed. `AUREON_PUBLIC_API_KEY` enforces a bearer token. `AUREON_PUBLIC_OPEN=1` serves the read-only surface with no key. With neither, Streamable HTTP binds to `127.0.0.1` only. Stages 3 and 4 stay closed.", "", ] ) return "\n".join(lines) + "\n"
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-coverage-plan") parser.add_argument("--write", action="store_true") parser.add_argument("--check", action="store_true") args = parser.parse_args(argv) text = render() path = repo_root() / PLAN_PATH if args.check: current = path.read_text(encoding="utf-8") if path.is_file() else "" if current != text: raise SystemExit("COVERAGE_PLAN.md does not match the inventory") return if args.write or not args.check: path.write_text(text, encoding="utf-8") print(path)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Apply huggingface/hnc-field/guard.py without keeping its directory change.
The Space module chdirs into the Space and may put the checkout on sys.path.This loader reuses that module, restores the working directory, and prefers aninstalled aureon distribution over the checkout when one is importable.
When that install is missing, imports fall back to the checkout. Callers mustread aureon_source() rather than assume the documented pin."""
from __future__ import annotations
import importlib.utilimport jsonimport osimport subprocessimport sysfrom pathlib import Path
from aureon_public.paths import repo_root, space_guard
_DONE = FalsePINNED_COMMIT = "8aa6a2d971cc529484e2a5e261e28afafab4e4f4"# git blob of the committed huggingface/hnc-field/guard.py.# The check is these bytes. It is not a path lookup inside PINNED_COMMIT.GUARD_BLOB = "b59a6ed8b82b98988e57c6897faba3eb9b98948d"GUARD_MISMATCH = "checkout guard.py differs from pin 8aa6a2d9"
def _same(path: str, root: Path) -> bool: candidate = path or os.getcwd() try: return Path(candidate).resolve() == root.resolve() except OSError: return False
def apply_space_guard() -> None: """Install the Space environment and the trading-import blocker."""
global _DONE if _DONE: return root = repo_root() guard_path = space_guard() cwd = Path.cwd() real_chdir = os.chdir os.chdir = lambda *_args, **_kwargs: None # type: ignore[method-assign] try: from aureon_public.pin_blob import _SameBytesLoader, git_blob_sha1
try: data = guard_path.read_bytes() except OSError as exc: raise ImportError(f"{guard_path.name} is not in this checkout") from exc if git_blob_sha1(data) != GUARD_BLOB: raise ImportError(GUARD_MISMATCH) from aureon_public.pin_blob import install_pinned_aureon_finder
install_pinned_aureon_finder(root) loader = _SameBytesLoader(data, str(guard_path)) spec = importlib.util.spec_from_loader( "aureon_hf_space_guard", loader, origin=str(guard_path), ) if spec is None: raise ImportError(f"cannot load {guard_path}") spec.has_location = True module = importlib.util.module_from_spec(spec) module.__file__ = str(guard_path) sys.modules["aureon_hf_space_guard"] = module loader.exec_module(module) finally: os.chdir = real_chdir if Path.cwd() != cwd: real_chdir(cwd) os.environ.pop("AUREON_MCP_TRANSIT_KEY", None) _prefer_installed_aureon(root) _DONE = True
def _prefer_installed_aureon(root: Path) -> None: """Use the pinned install when it is present. Otherwise keep the checkout.
The pinned finder is already on ``sys.meta_path``. It answers from the checkout without reading ``sys.path``, so this probe takes it off the path for the lookup. A direct_url.json that names the pin is what keeps the trimmed path. The blob check still decides which bytes run. """
from aureon_public.pin_blob import PinnedAureonFinder
saved = list(sys.path) trimmed = [entry for entry in saved if not _same(entry, root)] sys.path[:] = trimmed removed = [finder for finder in sys.meta_path if isinstance(finder, PinnedAureonFinder)] for finder in removed: sys.meta_path.remove(finder) try: found = importlib.util.find_spec("aureon") finally: for finder in reversed(removed): sys.meta_path.insert(0, finder) sys.path[:] = saved origin = getattr(found, "origin", None) if found is not None else None if not origin: return origin_path = Path(origin) if _outside_checkout(origin_path, root) and _direct_url_commit(origin_path) == PINNED_COMMIT: sys.path[:] = trimmed
def _outside_checkout(origin: Path, root: Path) -> bool: resolved = origin.resolve() root_resolved = root.resolve() return resolved != root_resolved and root_resolved not in resolved.parents
def _direct_url_commit(origin: Path) -> str | None: """Commit recorded beside an installed aureon, if direct_url.json has one."""
site = origin.resolve().parent.parent for dist in sorted(site.glob("aureon-*.dist-info")): direct = dist / "direct_url.json" if not direct.is_file(): continue try: payload = json.loads(direct.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): continue vcs = payload.get("vcs_info") if isinstance(payload, dict) else None commit = vcs.get("commit_id") if isinstance(vcs, dict) else None if isinstance(commit, str) and commit.strip(): return commit.strip() return None
def _git_commit(root: Path) -> str: try: result = subprocess.run( ["git", "rev-parse", "HEAD"], cwd=root, check=True, capture_output=True, text=True, ) except (OSError, subprocess.CalledProcessError): return "unknown" commit = result.stdout.strip() if len(commit) == 40 and all(character in "0123456789abcdef" for character in commit): return commit return "unknown"
def describe_aureon_source(origin: Path | None, root: Path) -> dict[str, str]: """Say which tree answered. Pinned only when direct_url.json names the pin."""
if origin is not None and _outside_checkout(origin, root): commit = _direct_url_commit(origin) if commit == PINNED_COMMIT: return {"kind": "pinned", "commit": commit} if commit: return {"kind": "installed", "commit": commit} return {"kind": "checkout", "commit": "unknown"} return {"kind": "checkout", "commit": _git_commit(root)}
def aureon_source() -> dict[str, str]: """The aureon import this process will use, after the guard has chosen a path.
Raises FileNotFoundError, via repo_root(), when there is no checkout. There is no separate 'no checkout' status. The server needs the checkout. """
apply_space_guard() root = repo_root() found = importlib.util.find_spec("aureon") origin_text = getattr(found, "origin", None) if found is not None else None origin = Path(origin_text) if origin_text else None return describe_aureon_source(origin, root)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454"""Streamable HTTP bind rule, bearer check, and per-client limits.
No key is read from disk. AUREON_PUBLIC_API_KEY is an optional runtimeenvironment variable. When it is unset, the public surface is served only ifAUREON_PUBLIC_OPEN=1. With neither one set, the listener must be 127.0.0.1."""
from __future__ import annotations
import asyncioimport hashlibimport hmacimport jsonimport osimport timefrom collections import OrderedDictfrom collections.abc import Callablefrom dataclasses import dataclass
LOCAL_BIND = "127.0.0.1"_DEFAULT_RATE_LIMIT = 120_DEFAULT_RATE_WINDOW_S = 60.0_DEFAULT_MAX_BODY = 1_048_576_DEFAULT_TIMEOUT_S = 30.0_DEFAULT_TRUSTED_PROXY_HOPS = 1_DEFAULT_MAX_CLIENTS = 4096# The public worker pool is 4. One live session holds the SSE GET and a POST# at the same time, so the cap stays at that same low number._DEFAULT_MAX_INFLIGHT = 4
@dataclass(frozen=True)class HttpLimits: """Limits for one server process. Values come from the environment."""
api_key: str max_body_bytes: int rate_limit: int rate_window_s: float timeout_s: float trusted_proxy_hops: int = _DEFAULT_TRUSTED_PROXY_HOPS max_clients: int = _DEFAULT_MAX_CLIENTS max_inflight: int = _DEFAULT_MAX_INFLIGHT
class RateLimiter: """Fixed window of request starts, keyed by client id.
Expired windows are dropped. The table keeps at most ``max_clients`` ids and evicts the least recently used id when a new one arrives. """
def __init__( self, limit: int, window_s: float, max_clients: int = _DEFAULT_MAX_CLIENTS, now: Callable[[], float] | None = None, ) -> None: self.limit = limit self.window_s = window_s self.max_clients = max_clients self._now = now or time.monotonic self._hits: OrderedDict[str, list[float]] = OrderedDict()
def allow(self, client_id: str) -> bool: now = self._now() self._evict_expired(now) if client_id in self._hits: self._hits.move_to_end(client_id) elif len(self._hits) >= self.max_clients: self._hits.popitem(last=False) hits = [stamp for stamp in self._hits.get(client_id, []) if now - stamp < self.window_s] if len(hits) >= self.limit: self._hits[client_id] = hits self._hits.move_to_end(client_id) return False hits.append(now) self._hits[client_id] = hits self._hits.move_to_end(client_id) return True
def _evict_expired(self, now: float) -> None: expired = [ client_id for client_id, hits in self._hits.items() if not hits or now - hits[-1] >= self.window_s ] for client_id in expired: del self._hits[client_id]
def _positive_int(name: str, default: int) -> int: raw = os.environ.get(name, "").strip() if not raw: return default try: value = int(raw) except ValueError as exc: raise SystemExit(f"{name} must be a positive integer") from exc if value <= 0: raise SystemExit(f"{name} must be a positive integer") return value
def _positive_float(name: str, default: float) -> float: raw = os.environ.get(name, "").strip() if not raw: return default try: value = float(raw) except ValueError as exc: raise SystemExit(f"{name} must be a positive number") from exc if value <= 0: raise SystemExit(f"{name} must be a positive number") return value
def load_http_limits() -> HttpLimits: """Read the optional key and the limit environment variables."""
return HttpLimits( api_key=os.environ.get("AUREON_PUBLIC_API_KEY", "").strip(), max_body_bytes=_positive_int("AUREON_PUBLIC_MAX_BODY_BYTES", _DEFAULT_MAX_BODY), rate_limit=_positive_int("AUREON_PUBLIC_RATE_LIMIT", _DEFAULT_RATE_LIMIT), rate_window_s=_positive_float("AUREON_PUBLIC_RATE_WINDOW_S", _DEFAULT_RATE_WINDOW_S), timeout_s=_positive_float("AUREON_PUBLIC_REQUEST_TIMEOUT_S", _DEFAULT_TIMEOUT_S), trusted_proxy_hops=_nonnegative_int( "AUREON_PUBLIC_TRUSTED_PROXY_HOPS", _DEFAULT_TRUSTED_PROXY_HOPS, ), max_clients=_positive_int("AUREON_PUBLIC_RATE_MAX_CLIENTS", _DEFAULT_MAX_CLIENTS), max_inflight=_positive_int("AUREON_PUBLIC_MAX_INFLIGHT", _DEFAULT_MAX_INFLIGHT), )
def _nonnegative_int(name: str, default: int) -> int: raw = os.environ.get(name, "").strip() if not raw: return default try: value = int(raw) except ValueError as exc: raise SystemExit(f"{name} must be a non-negative integer") from exc if value < 0: raise SystemExit(f"{name} must be a non-negative integer") return value
def public_bind_allowed(host: str) -> bool: """True when this host may listen.
A bearer key or AUREON_PUBLIC_OPEN=1 allows the requested host. Otherwise only 127.0.0.1 is allowed. """
if os.environ.get("AUREON_PUBLIC_API_KEY", "").strip(): return True if os.environ.get("AUREON_PUBLIC_OPEN") == "1": return True return host == LOCAL_BIND
def resolve_http_bind(host: str) -> str: """Return host, or refuse a non-local bind when the surface is locked."""
if public_bind_allowed(host): return host raise SystemExit( "Streamable HTTP binds to 127.0.0.1 unless AUREON_PUBLIC_API_KEY is set " "or AUREON_PUBLIC_OPEN=1." )
def _header_map(scope: dict) -> dict[str, str]: found: dict[str, str] = {} for key, value in scope.get("headers") or []: found[key.decode("latin1").lower()] = value.decode("latin1") return found
def _bearer(authorization: str) -> str | None: parts = authorization.split(" ", 1) if len(parts) != 2 or parts[0].lower() != "bearer": return None token = parts[1].strip() if not token: return None return token
def _key_matches(presented: str, expected: str) -> bool: presented_bytes = presented.encode("utf-8") expected_bytes = expected.encode("utf-8") if len(presented_bytes) != len(expected_bytes): return False return hmac.compare_digest(presented_bytes, expected_bytes)
def _socket_peer(scope: dict) -> str: client = scope.get("client") if isinstance(client, (list, tuple)) and client and client[0]: return str(client[0]) return "unknown"
def _forwarded_hops(value: str) -> list[str]: return [part.strip() for part in value.split(",") if part.strip()]
def client_address(scope: dict, headers: dict[str, str], trusted_proxy_hops: int) -> str: """Client address behind ``trusted_proxy_hops`` trusted proxies.
``AUREON_PUBLIC_TRUSTED_PROXY_HOPS`` defaults to 1. When the header is present and has at least that many values, the client is ``hops[-trusted_proxy_hops]``. With the default, that is the last value, including a header that contains only one address. A fake first hop does not become its own bucket. Zero trusted hops ignores the header and uses the socket peer. The real Hugging Face header shape still has to be confirmed on the private Space. """
peer = _socket_peer(scope) note_forwarded_shape(headers.get("x-forwarded-for", "")) if trusted_proxy_hops <= 0: return peer hops = _forwarded_hops(headers.get("x-forwarded-for", "")) if len(hops) < trusted_proxy_hops: return peer return hops[-trusted_proxy_hops]
_SHAPE_CAP = 32_forwarded_shapes: list[dict[str, object]] = []
def _hop_kind(token: str) -> str: """Classify one hop. The returned label is not the address."""
host = token.strip() if host.startswith("[") and "]" in host: host = host[1 : host.index("]")] elif host.count(":") == 1 and host.rsplit(":", 1)[-1].isdigit(): host = host.rsplit(":", 1)[0] try: import ipaddress
parsed = ipaddress.ip_address(host) except ValueError: return "other" return "ipv4" if parsed.version == 4 else "ipv6"
def note_forwarded_shape(value: str) -> None: """Record hop count and hop kinds when the diagnostic is on.
``AUREON_PUBLIC_FORWARDED_DIAG=1`` opts in. The record does not store the header or the addresses. """
if os.environ.get("AUREON_PUBLIC_FORWARDED_DIAG") != "1": return hops = _forwarded_hops(value) _forwarded_shapes.append({"hops": len(hops), "kinds": [_hop_kind(hop) for hop in hops]}) del _forwarded_shapes[:-_SHAPE_CAP]
def forwarded_shapes() -> list[dict[str, object]]: """Copies of the diagnostic shapes. Empty unless the diagnostic is on."""
return [dict(item) for item in _forwarded_shapes]
def clear_forwarded_shapes() -> None: _forwarded_shapes.clear()
def _client_id(scope: dict, headers: dict[str, str], limits: HttpLimits) -> str: """Bucket by address. The bearer is the id only when it matches the configured key.
Open mode has no configured key, so a presented bearer is never the client id. """
address = client_address(scope, headers, limits.trusted_proxy_hops) if limits.api_key: presented = _bearer(headers.get("authorization", "")) if presented is not None and _key_matches(presented, limits.api_key): digest = hashlib.sha256(presented.encode("utf-8")).hexdigest() return f"bearer:{digest}" return f"ip:{address}"
def _content_length(headers: dict[str, str]) -> int | None: raw = headers.get("content-length", "").strip() if not raw or not raw.isdigit(): return None return int(raw)
async def _reject(send, status: int, error: str, *, retry_after: str | None = None) -> None: body = json.dumps({"error": error}).encode("utf-8") header_list = [ (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode("ascii")), ] if status == 401: header_list.append((b"www-authenticate", b"Bearer")) if status == 405: header_list.append((b"allow", b"POST")) if retry_after is not None: header_list.append((b"retry-after", retry_after.encode("ascii"))) await send({"type": "http.response.start", "status": status, "headers": header_list}) await send({"type": "http.response.body", "body": body})
class PublicHttpMiddleware: """ASGI wrapper for the Streamable HTTP app. Lifespan scopes pass through."""
def __init__(self, app, limits: HttpLimits, limiter: RateLimiter | None = None) -> None: self.app = app self.limits = limits self.limiter = limiter if limiter is not None else RateLimiter( limits.rate_limit, limits.rate_window_s, max_clients=limits.max_clients, ) self._inflight = 0 self._inflight_lock = asyncio.Lock()
async def __call__(self, scope, receive, send) -> None: if scope.get("type") != "http": await self.app(scope, receive, send) return path = scope.get("path") or "" if path != "/mcp" and not path.startswith("/mcp/"): await self.app(scope, receive, send) return headers = _header_map(scope) client_id = _client_id(scope, headers, self.limits) if not self.limiter.allow(client_id): retry_after = str(max(1, int(self.limits.rate_window_s))) await _reject(send, 429, "rate_limit", retry_after=retry_after) return if self.limits.api_key: presented = _bearer(headers.get("authorization", "")) if presented is None or not _key_matches(presented, self.limits.api_key): await _reject(send, 401, "unauthorized") return method = scope.get("method", "GET") if method == "GET": # Streamable HTTP's long-lived event stream. Stateless JSON mode # does not use it. Answering here keeps it off the call slots. await _reject(send, 405, "method_not_allowed") return if method == "POST": declared = _content_length(headers) if declared is not None and declared > self.limits.max_body_bytes: await _reject(send, 413, "body_too_large") return receive = await _bounded_receive( receive, self.limits.max_body_bytes, send, self.limits.timeout_s, ) if receive is None: return if not await self._acquire_inflight(): await _reject(send, 503, "busy") return try: if method != "POST": await self.app(scope, receive, send) return started = False
async def send_wrapper(message) -> None: nonlocal started if message.get("type") == "http.response.start": started = True await send(message)
try: await asyncio.wait_for( self.app(scope, receive, send_wrapper), timeout=self.limits.timeout_s, ) except TimeoutError: if started: raise await _reject(send, 504, "timeout") finally: await self._release_inflight()
async def _acquire_inflight(self) -> bool: async with self._inflight_lock: if self._inflight >= self.limits.max_inflight: return False self._inflight += 1 return True
async def _release_inflight(self) -> None: async with self._inflight_lock: self._inflight -= 1
async def _bounded_receive(receive, max_body: int, send, timeout_s: float): """Buffer a POST body and reject it once the arrived bytes pass the cap.
Chunked requests omit content-length. Every message is counted until ``more_body`` is false or the client disconnects. Empty chunks do not stop the count, and the unread remainder is not passed through. ``timeout_s`` bounds the whole read. An idle or unfinished body returns HTTP 408 instead of handing the stream to the application. """
buffered: list[dict] = [] total = 0 deadline = asyncio.get_running_loop().time() + timeout_s while True: remaining = deadline - asyncio.get_running_loop().time() if remaining <= 0: await _reject(send, 408, "body_timeout") return None try: message = await asyncio.wait_for(receive(), timeout=remaining) except TimeoutError: await _reject(send, 408, "body_timeout") return None kind = message.get("type") if kind != "http.request": buffered.append(message) if kind == "http.disconnect": break continue chunk = message.get("body") or b"" total += len(chunk) if total > max_body: await _reject(send, 413, "body_too_large") return None buffered.append(message) if not message.get("more_body", False): break index = 0
async def replay(): nonlocal index if index < len(buffered): message = buffered[index] index += 1 return message return await receive()
return replay123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405"""Scan public modules, classes, and functions for the full-body plan.
The scan is AST only. It does not import aureon and it does not call anything."""
from __future__ import annotations
import astimport jsonimport refrom collections import Counter, defaultdictfrom pathlib import Path
STAGE = { "harmonic": 1, "cognition": 2, "queen": 2, "swarm": 2, "swarm_motion": 2, "gates": 2, "governance": 2, "alignment": 2, "observer": 2, "organism": 3, "bio": 3, "evaluation": 3, "vault": 3, "identity": 3, "data_feeds": 4, "atn": 4, "decoders": 4, "search": 4, "portals": 4, "monitors": 4, "analytics": 4, "trading": 5, "exchanges": 5, "bots": 5, "bots_intelligence": 5, "bridges": 5, "scanners": 5, "strategies": 5, "portfolio": 5, "accounting": 5, "conversion": 5, "autonomous": 6, "code_architect": 6, "inhouse_ai": 6, "operator": 6, "launch": 6, "command_centers": 6, "connectors": 6, "saas": 6, "miner": 6, "generated": 6,}
OPERATOR_PACKAGES = { "trading", "exchanges", "bots", "bots_intelligence", "bridges", "scanners", "strategies", "portfolio", "accounting", "conversion", "autonomous", "code_architect", "inhouse_ai", "operator", "launch", "command_centers", "connectors", "saas", "miner", "identity", "vault",}
ORDER_RE = re.compile( r"place_order|create_order|submit_order|live_order|market_order|limit_order|send_order", re.I,)LAUNCH_RE = re.compile( r"^(main|start_|stop_|launch|serve|run_server|boot|demo)$|serve_forever|continuous|create_web", re.I,)WRITE_RE = re.compile(r"write_text|write_bytes|\.write\(|mkdir|open\([^)]*['\"][wa]", re.I)KEY_RE = re.compile( r"api_key|secret|password|credential|dotenv|owner_address|master_key|from_env|private_key|read_identity", re.I,)FETCH_RE = re.compile(r"^(fetch_|download_|get_live)|requests\.|urlopen|httpx\.", re.I)RISKY_RE = re.compile( r"(?<![\w])append(?![\w])|" r"(?<![\w])publish(?![\w])|" r"\bThread\b|" r"\.start\s*\(|" r"\bunlink\b|" r"\bmkdir\b|" r"(?<![\w.])eval\s*\(|" r"(?<![\w.])exec\s*\(|" r"\bemit_\w*|" r"open\s*\([^)]*['\"][wa]", re.I,)
def stage_for(pkg: str, rel: str) -> int: low = rel.lower() if pkg == "core": if any(token in low for token in ("organism", "memory", "thought_bus")): return 3 if any(token in low for token in ("hnc", "lambda", "field", "harmonic", "canonical")): return 1 return 6 if pkg == "utils": return 1 if any(token in low for token in ("auris", "queen_hive", "queen")) else 6 if pkg == "wisdom": return 1 if "qgita" in low else 6 return STAGE.get(pkg, 6)
def source_is_risky(src: str) -> bool: """True when a full function body or a class ``__init__`` has a risky token."""
return bool(src and RISKY_RE.search(src))
def safety(pkg: str, name: str, src: str, stage: int) -> tuple[str, str]: blob = name + "\n" + src if pkg == "identity" or (pkg == "vault" and KEY_RE.search(blob)): return "operator", "personal or key material; operator only; never returned" if ORDER_RE.search(blob) or pkg in { "trading", "exchanges", "bots", "bots_intelligence", "bridges", "scanners", }: return "operator", "order-capable path; live_orders refused; no live send" if LAUNCH_RE.search(name) or "serve_forever" in src or "while True" in src: return "operator", "process, loop, or UI start; own flag; status and stop" if WRITE_RE.search(src) or source_is_risky(src): return "operator", "full-body scan found a risky token; the public server refuses it" if KEY_RE.search(blob): return "operator", "reads keys from env only; never logged or returned" if pkg in OPERATOR_PACKAGES and stage >= 5: return "operator", "package is operator-scoped; no public import" if FETCH_RE.search(blob): return "public", "live public fetch allowed; source label and timeout" server, text = "public", "runs from inputs or committed files; no keys and no repo write" return _honest_effect(name, server, text)
def _honest_effect(name: str, server: str, text: str) -> tuple[str, str]: """Names that write or start are not 'no repo write'."""
leaf = name.split(".")[-1] if re.match(r"^(write_|save_|export_|dump_)", leaf, re.I) or leaf.lower() == "start": if "no repo write" in text: return server, "write or process start; the public server refuses it" return server, text
def required_count(node: ast.AST) -> int: if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): return 0 args = [item for item in node.args.args if item.arg not in {"self", "cls"}] required = len(args) - len(node.args.defaults) for default in node.args.kw_defaults: if default is None: required += 1 if node.args.vararg or node.args.kwarg: return required return max(required, 0)
def _span(lines: list[str], node: ast.AST) -> str: start = getattr(node, "lineno", 1) - 1 end = getattr(node, "end_lineno", None) or getattr(node, "lineno", 1) return "\n".join(lines[start:end])
def _init_source(lines: list[str], class_node: ast.ClassDef) -> str: for item in class_node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == "__init__": return _span(lines, item) return ""
def _scan_tree(pkg: str, rel: str, text: str, server_default: str | None = None) -> list[dict]: rows: list[dict] = [] try: tree = ast.parse(text) except SyntaxError: stage = 5 if pkg == "unified_margin_trader" else stage_for(pkg, rel) rows.append( { "package": pkg, "module": rel, "symbol": "<syntax>", "kind": "module", "server": "operator", "form": "resource", "safety": "file does not parse", "stage": stage, "required": 0, } ) return rows stage = 5 if pkg == "unified_margin_trader" else stage_for(pkg, rel) lines = text.splitlines() module_server = server_default or "operator" if pkg == "unified_margin_trader" else safety(pkg, Path(rel).stem, "", stage)[0] module_safety = ( "order-capable tree; live_orders refused" if pkg == "unified_margin_trader" else "module surface; import is lazy and blob-checked when the file is the checkout" ) rows.append( { "package": pkg, "module": rel, "symbol": Path(rel).stem, "kind": "module", "server": module_server, "form": "resource", "safety": module_safety, "stage": stage, "required": 0, } ) for node in tree.body: if isinstance(node, ast.ClassDef) and not node.name.startswith("_"): server, safe = ( ("operator", "live_orders refused; no live send") if pkg == "unified_margin_trader" else safety(pkg, node.name, _init_source(lines, node) or _span(lines, node), stage) ) rows.append( { "package": pkg, "module": rel, "symbol": node.name, "kind": "class", "server": server, "form": "resource", "safety": safe, "stage": stage, "required": 0, } ) for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and not item.name.startswith("_"): server, safe = ( ("operator", "live_orders refused; no live send") if pkg == "unified_margin_trader" else safety( pkg, item.name, _span(lines, item) + "\n" + _init_source(lines, node), stage, ) ) rows.append( { "package": pkg, "module": rel, "symbol": f"{node.name}.{item.name}", "kind": "method", "server": server, "form": "tool", "safety": safe, "stage": stage, "required": required_count(item), "async": isinstance(item, ast.AsyncFunctionDef), } ) elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and not node.name.startswith("_"): server, safe = ( ("operator", "live_orders refused; no live send") if pkg == "unified_margin_trader" else safety(pkg, node.name, _span(lines, node), stage) ) rows.append( { "package": pkg, "module": rel, "symbol": node.name, "kind": "function", "server": server, "form": "tool", "safety": safe, "stage": stage, "required": required_count(node), "async": isinstance(node, ast.AsyncFunctionDef), } ) return rows
def scan(root: Path) -> list[dict]: rows: list[dict] = [] aureon = root / "aureon" for pkg_path in sorted(path for path in aureon.iterdir() if (path / "__init__.py").is_file()): for path in sorted(pkg_path.rglob("*.py")): if "__pycache__" in path.parts: continue rel = str(path.relative_to(aureon)) text = path.read_text(encoding="utf-8", errors="replace") rows.extend(_scan_tree(pkg_path.name, rel, text)) umt = root / "unified_margin_trader" for path in sorted(umt.rglob("*.py")): if "__pycache__" in path.parts: continue text = path.read_text(encoding="utf-8", errors="replace") rows.extend(_scan_tree("unified_margin_trader", str(path.relative_to(root)), text, "operator")) return rows
def render_plan(rows: list[dict]) -> str: lines = [ "# Full body MCP plan", "", "This is the stage-0 inventory of every public module, class, function, and method in the 54 `aureon` packages plus `unified_margin_trader`. A name that starts with `_` is not listed.", "", "A layer is at full depth only where a measured call runs that entry point. Listing it here, or reading its signature, is not depth. A helper call is not that layer's cognition. The depth table in each later stage counts calls, not rows.", "", "MCP lets outside models call Aureon's tools. No outside model or API becomes Aureon's reasoning. The cognition runs in Aureon's own code.", "", "Public (`aureon-public`) runs entry points that need no keys, personal data, writes, or live fetches. Operator (`aureon-operator`) is stdio only and stays off unless `AUREON_OPERATOR_MCP=1`. It is deny-by-default: the only calls that run are `accounting/file_drop.py` `registered_ingestors` and `portfolio/aureon_billion_goal_tracker.py` `get_days_remaining`, both with `allow_fetch` and `allow_write` false. It does not read keys. Live orders return `live_orders: refused`.", "", "Functions and methods are tools. Modules and classes are resources (the surface, not a constructed instance). The running servers address them through `body_call` and `body_surface` so the catalog stays one pair of tools instead of nineteen thousand registrations. The form column is the kind of call. `body_call` runs the real function. `body_surface` does not.", "", "`repo_root()` and `aureon_source()` raise `FileNotFoundError` when there is no checkout. The servers need that checkout.", "", "Any checkout file loaded beside the pin must pass the git blob check in `mcp/aureon_public/pin_blob.py` before it is executed. A file whose blob is not the blob at pin `8aa6a2d9` is not imported.", "", "HOLD stays explicit: trade readiness, the Auris-to-Lambda link, QGITA detection and false-alarm rates, Schumann f0, and HumanEval not run. `consciousness_*` keys are dropped. The pin and `AUREON_PUBLIC_REQUIRE_PIN` stay. Space entry points call `enforce_public_pin()`.", "", "## Stages", "", "1. HNC, harmonic core, Auris, and QGITA.", "2. cognition, queen, swarm, swarm_motion, gates, governance, alignment, observer.", "3. organism, bio, evaluation, memory and vault, identity readers.", "4. data_feeds, atn, decoders, search, portals, monitors, analytics.", "5. trading, exchanges, bots, bots_intelligence, bridges, scanners, strategies, portfolio, accounting, unified_margin_trader, conversion. Operator server. Live orders refused.", "6. autonomous, code_architect, inhouse_ai, operator, launch, command_centers, connectors, saas, miner, generated, and the rest.", "7. Space entry points and MCP registry packaging.", "", "## Counts", "", "| Package | Symbols | Public | Operator | Stage |", "| --- | ---: | ---: | ---: | --- |", ] by_pkg: dict[str, list[dict]] = defaultdict(list) for row in rows: by_pkg[row["package"]].append(row) for pkg in sorted(by_pkg): items = by_pkg[pkg] public = sum(1 for row in items if row["server"] == "public") operator = sum(1 for row in items if row["server"] == "operator") stages = ",".join(str(item) for item in sorted({row["stage"] for row in items})) lines.append(f"| {pkg} | {len(items)} | {public} | {operator} | {stages} |") lines.extend( [ "", f"Total symbols: {len(rows)}. Packages: {len(by_pkg)}.", "", "Stage totals: " + ", ".join(f"{stage}={count}" for stage, count in sorted(Counter(row["stage"] for row in rows).items())) + ".", "", "Server totals: " + ", ".join(f"{server}={count}" for server, count in sorted(Counter(row["server"] for row in rows).items())) + ".", "", "## Every public module, class, and function", "", "Columns: stage, server, form, kind, module, symbol, safety.", "", "| Stage | Server | Form | Kind | Module | Symbol | Safety |", "| ---: | --- | --- | --- | --- | --- | --- |", ] ) for row in rows: safety_text = row["safety"].replace("|", "/") symbol = row["symbol"].replace("|", "/") lines.append( f"| {row['stage']} | {row['server']} | {row['form']} | {row['kind']} | `{row['module']}` | `{symbol}` | {safety_text} |" ) return "\n".join(lines) + "\n"
def write_outputs(root: Path) -> tuple[int, Path, Path]: rows = scan(root) plan = root / "docs" / "mcp" / "FULL_BODY_PLAN.md" inventory = root / "docs" / "mcp" / "inventory.json" plan.parent.mkdir(parents=True, exist_ok=True) plan.write_text(render_plan(rows), encoding="utf-8") inventory.write_text(json.dumps(rows, separators=(",", ":")), encoding="utf-8") return len(rows), plan, inventory123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594"""Read-only and one-step tools for organism layers that do not order or write state/.
Dispositions follow the scoping table. A package with no safe callable stayscatalog-only. Blocked trading imports are not called."""
from __future__ import annotations
import astfrom pathlib import Pathfrom typing import Any
from aureon_public import pathsfrom aureon_public.quiet import quietfrom aureon_public.text import AURIS_FOUR, HOLD_LINEfrom aureon_public.tools import _dumps, _finite
# kind: public tool name, catalog (named, not called), or operator (not on this server).PACKAGES: tuple[dict[str, str], ...] = ( {"package": "accounting", "kind": "operator", "reason": "Inferred private. Not opened. No live orders."}, {"package": "alignment", "kind": "catalog", "reason": "Not opened. No safe zero-write callable was wrapped."}, {"package": "analytics", "kind": "catalog", "reason": "Lighthouse seat module was not given a separate tool. QGITA lighthouse math is wrapped on wisdom."}, {"package": "appliance", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "approval", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "atn", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "autonomous", "kind": "operator", "reason": "Self-coding and launchers. Operator server only. No live orders."}, {"package": "bio", "kind": "membrane_screen", "reason": "screen_ingress is read-only containment. The Flask transport is not re-exported."}, {"package": "bots", "kind": "operator", "reason": "Blocked by guard.py. Operator refusal only. No live orders."}, {"package": "bots_intelligence", "kind": "operator", "reason": "Blocked by guard.py. Operator refusal only. No live orders."}, {"package": "bridges", "kind": "operator", "reason": "Blocked by guard.py. Operator refusal only. No live orders."}, {"package": "briefing", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "code_architect", "kind": "operator", "reason": "Self-coding. Operator server only. No repo writes from this server."}, {"package": "cognition", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "command_centers", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "connectors", "kind": "operator", "reason": "Inferred private. Not opened. No live orders."}, {"package": "conversion", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "core", "kind": "public", "reason": "Canonical field, LambdaEngine, circulation catalog, and the repository-layer hold."}, {"package": "data_feeds", "kind": "catalog", "reason": "Feeds are key-adjacent. Not called."}, {"package": "decoders", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "evaluation", "kind": "evidence_predict_next", "reason": "predict_next and the committed-report formatters. evaluate_organism and the self-coder harness are not called."}, {"package": "exchanges", "kind": "operator", "reason": "Blocked by guard.py. Operator refusal only. No live orders."}, {"package": "gates", "kind": "catalog", "reason": "Signature pass was not done. Not called."}, {"package": "generated", "kind": "catalog", "reason": "Generated trees are not exposed."}, {"package": "governance", "kind": "catalog", "reason": "Seat resolvers were not started."}, {"package": "grants", "kind": "catalog", "reason": "Out of the public tool surface."}, {"package": "harmonic", "kind": "public", "reason": "HarmonicRealityField plus substrate, echo, observer, potential, and projection. HFT order types are not called."}, {"package": "identity", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "inhouse_ai", "kind": "catalog", "reason": "The operator tool registry is not re-exported."}, {"package": "integrations", "kind": "catalog", "reason": "External systems. Not called."}, {"package": "intelligence", "kind": "catalog", "reason": "GlobalMarketOrganism is not a stateless API. Not called."}, {"package": "launch", "kind": "operator", "reason": "Process start. Operator server only. This server does not launch it."}, {"package": "miner", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "monitors", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "observability", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "observer", "kind": "catalog", "reason": "HarmonicObserver attaches to the live daemon. Not called."}, {"package": "operator", "kind": "operator", "reason": "Flask app and the existing /mcp routes. Not mounted here."}, {"package": "organism", "kind": "repository_layers_hold", "reason": "compose_repository_layers on an empty root. No network transport."}, {"package": "plumber", "kind": "catalog", "reason": "Crypto extras. Not called."}, {"package": "portfolio", "kind": "operator", "reason": "Inferred private. Not opened. No live orders."}, {"package": "portals", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "queen", "kind": "catalog", "reason": "QueenLayer init is not called. Auris node and evaluator calls live on utils."}, {"package": "s51", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "saas", "kind": "operator", "reason": "Billing. Operator server only. No charges."}, {"package": "scanners", "kind": "operator", "reason": "Blocked by guard.py. Operator refusal only. No live orders."}, {"package": "search", "kind": "catalog", "reason": "Not repo_search. Not called."}, {"package": "simulation", "kind": "catalog", "reason": "Long-running. Not called."}, {"package": "strategies", "kind": "operator", "reason": "Trading-adjacent. Operator refusal only. No live orders."}, {"package": "swarm", "kind": "catalog", "reason": "Council seat is named in organism_catalog. The council is not started."}, {"package": "swarm_motion", "kind": "catalog", "reason": "Not opened. No safe callable wrapped."}, {"package": "trading", "kind": "operator", "reason": "Blocked by guard.py. Operator refusal only. No live orders."}, {"package": "utils", "kind": "public", "reason": "Nine nodes and the coherence evaluator. QueenHiveMind.__init__ is not called."}, {"package": "vault", "kind": "catalog", "reason": "State files. Not opened and not written."}, {"package": "wisdom", "kind": "public", "reason": "QGITAMarketAnalyzer, FTCPDetector, and LighthouseModel metric calls. Signals are dropped."},)
HOLDS = { "trade_readiness": "HOLD", "auris_to_lambda": "HOLD", "qgita_detection_rate": "HOLD", "qgita_false_alarm_rate": "HOLD", "schumann_f0": "null. HOLD", "human_eval": "not run. HOLD",}
def _package_rows() -> list[dict[str, str]]: root = paths.repo_root() / "aureon" rows = [] for row in PACKAGES: present = (root / row["package"]).is_dir() or row["package"] == "unified_margin_trader" rows.append({**row, "present": "yes" if present else "no", "holds": HOLD_LINE}) return rows
@quietdef package_dispositions(package: str | None = None) -> str: """Disposition of each aureon package. Label: inferred from the scoping table, except where a tool below calls a real function.
Blocked packages are operator-only. This tool does not import them.
Args: package: Optional package name. Omitted returns the full table. Label: inferred. """
rows = _package_rows() if package: chosen = [row for row in rows if row["package"] == package] if not chosen: return _dumps( { "holds": HOLDS, "label": "inferred", "provenance": "inferred", "reason": "Unknown package.", "status": "unavailable", } ) rows = chosen return _dumps( { "holds": HOLDS, "label": "inferred. Package dispositions. Not a measurement.", "packages": rows, "provenance": "inferred", "status": "inferred", "which_auris": AURIS_FOUR, } )
@quietdef hnc_substrate_eval(t: float = 0.0) -> str: """One HarmonicSubstrate.evaluate call. Provenance: inferred. This is not HarmonicRealityField.step.
The substrate equation is the class docstring. No formula was added. Trade readiness: HOLD.
Args: t: Time passed to evaluate. Label: cited, HarmonicSubstrate.evaluate. """
number = _finite(t) if number is None: return _dumps({"provenance": "cited", "reason": "t is missing", "status": "unavailable"}) from aureon.harmonic.aureon_harmonic_reality import HarmonicSubstrate
substrate = HarmonicSubstrate() return _dumps( { "label": "inferred. One HarmonicSubstrate.evaluate call.", "provenance": "inferred", "status": "inferred", "t": number, "value": float(substrate.evaluate(number)), } )
@quietdef hnc_echo_eval(current_lambda: float = 0.0) -> str: """One CausalEcho.evaluate call on a new echo. Provenance: inferred.
The buffer starts at zeros in CausalEcho.__init__. This is that function, not a new formula. Trade readiness: HOLD.
Args: current_lambda: Value passed to evaluate. Label: cited, CausalEcho.evaluate. """
number = _finite(current_lambda) if number is None: return _dumps({"provenance": "cited", "reason": "current_lambda is missing", "status": "unavailable"}) from aureon.harmonic.aureon_harmonic_reality import CausalEcho
echo = CausalEcho() return _dumps( { "label": "inferred. One CausalEcho.evaluate call on a new instance.", "provenance": "inferred", "status": "inferred", "value": float(echo.evaluate(number)), } )
@quietdef hnc_observer_eval(current_lambda: float = 0.0) -> str: """One ObserverNode.evaluate call on a new observer. Provenance: inferred.
Args: current_lambda: Value passed to evaluate. Label: cited, ObserverNode.evaluate. """
number = _finite(current_lambda) if number is None: return _dumps({"provenance": "cited", "reason": "current_lambda is missing", "status": "unavailable"}) from aureon.harmonic.aureon_harmonic_reality import ObserverNode
observer = ObserverNode() return _dumps( { "label": "inferred. One ObserverNode.evaluate call on a new instance.", "provenance": "inferred", "status": "inferred", "value": float(observer.evaluate(number)), } )
@quietdef hnc_potential_eval(lambda_val: float = 0.0) -> str: """One UnifiedPotential.evaluate call. Provenance: inferred.
The potential string is the class docstring. No formula was added. Trade readiness: HOLD.
Args: lambda_val: Value passed to evaluate. Label: cited, UnifiedPotential.evaluate. """
number = _finite(lambda_val) if number is None: return _dumps({"provenance": "cited", "reason": "lambda_val is missing", "status": "unavailable"}) from aureon.harmonic.aureon_harmonic_reality import UnifiedPotential
potential = UnifiedPotential() return _dumps( { "label": "inferred. One UnifiedPotential.evaluate call.", "provenance": "inferred", "status": "inferred", "value": float(potential.evaluate(number)), } )
@quietdef hnc_translate_project(psi_5d: float = 1.0, phi: float = 0.0, delta_phi: float = 0.0, f_value: float = 1.0) -> str: """One TranslationMap.project_to_3d call with observed_residual left unset. Provenance: inferred.
Noise is the method's own result when no residual is supplied. Label: cited, TranslationMap.project_to_3d.
Args: psi_5d: High-dimensional state. Label: cited. phi: Extra angle. Label: cited. delta_phi: Phase difference. Label: cited. f_value: Brane frequency passed as F. Label: cited. """
numbers = { "psi_5d": _finite(psi_5d), "phi": _finite(phi), "delta_phi": _finite(delta_phi), "f_value": _finite(f_value), } if any(value is None for value in numbers.values()): return _dumps({"provenance": "cited", "reason": "A projection input is missing", "status": "unavailable"}) from aureon.harmonic.aureon_harmonic_reality import TranslationMap
mapped = TranslationMap() projected, noise = mapped.project_to_3d( psi_5d=float(numbers["psi_5d"]), phi=float(numbers["phi"]), delta_phi=float(numbers["delta_phi"]), F=float(numbers["f_value"]), ) return _dumps( { "label": "inferred. project_to_3d with no observed residual.", "noise": float(noise), "projected": float(projected), "provenance": "inferred", "status": "inferred", } )
@quietdef qgita_ftcp_detect(values: list[float] | None = None) -> str: """FTCPDetector.detect_ftcps on a caller series or a short default. Provenance: inferred.
Detection rate: HOLD. False-alarm rate: HOLD. This is not QGITAMarketAnalyzer.signals.
Args: values: Optional series of at least three numbers. Omitted uses 0,1,1,2,3,5,8. Label: inferred for the call. The detector is cited. """
series = [0.0, 1.0, 1.0, 2.0, 3.0, 5.0, 8.0] if values is None else [] if values is not None: for item in values: number = _finite(item) if number is None: return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "provenance": "cited", "reason": "A value is missing", "status": "unavailable", } ) series.append(number) if len(series) < 3: return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "provenance": "cited", "reason": "At least three values are required", "status": "unavailable", } ) import numpy as np
from aureon.wisdom.aureon_qgita_framework import FTCPDetector
detector = FTCPDetector() times = np.arange(len(series), dtype=float) found = detector.detect_ftcps(times, np.asarray(series, dtype=float)) return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "ftcp_count": len(found), "label": "inferred. FTCPDetector.detect_ftcps. Not a detection rate.", "provenance": "inferred", "status": "inferred", } )
@quietdef qgita_lighthouse_coherence(values: list[float] | None = None) -> str: """LighthouseModel.compute_linear_coherence on one series. Provenance: inferred.
Detection rate: HOLD. False-alarm rate: HOLD. validate_ftcp is not called. Signals are not returned.
Args: values: Optional series. Omitted uses 1,1,1,1,1. Label: inferred for the call. The method is cited. """
series = [1.0, 1.0, 1.0, 1.0, 1.0] if values is None else [] if values is not None: for item in values: number = _finite(item) if number is None: return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "provenance": "cited", "reason": "A value is missing", "status": "unavailable", } ) series.append(number) import numpy as np
from aureon.wisdom.aureon_qgita_framework import LighthouseModel
model = LighthouseModel() signal = np.asarray(series, dtype=float) return _dumps( { "c_linear": float(model.compute_linear_coherence(signal)), "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "label": "inferred. LighthouseModel.compute_linear_coherence.", "provenance": "inferred", "status": "inferred", } )
@quietdef membrane_screen(text: str = "") -> str: """screen_ingress on caller text. Provenance: cited. This does not dispatch a tool and does not trade.
Args: text: Inbound text screened as data. Label: cited, aureon/bio/mcp_membrane.py screen_ingress. """
from dataclasses import asdict
missing = _load_phenolic_fingerprint() if missing: return _dumps( { "label": "cited-unverified. phenolic_fingerprint was not loaded, so screen_ingress did not run.", "provenance": "cited-unverified", "reason": missing, "status": "unavailable", } ) try: from aureon.bio.mcp_membrane import screen_ingress except Exception as exc: return _dumps( { "label": "cited-unverified. screen_ingress did not import in this process.", "provenance": "cited-unverified", "reason": f"{type(exc).__name__}: {exc}"[:240], "status": "unavailable", } )
verdict = screen_ingress(str(text), source="aureon-public") body = asdict(verdict) body["label"] = ( "cited. screen_ingress. phenolic_fingerprint loaded from checkout " "after the blob check for pin 8aa6a2d9. Not an order." ) body["provenance"] = "cited" body["status"] = "cited" return _dumps(body)
@quietdef repository_layers_hold() -> str: """compose_repository_layers on an empty directory. Provenance: cited.
No field or market transport is passed, and the empty root has no sibling checkouts, so this does not open a network socket from those call sites. may_act stays false.
Args: none: This tool takes no inputs. Label: cited, aureon/organism/repository_layers.py compose_repository_layers. """
import tempfile
from aureon.organism.repository_layers import compose_repository_layers
empty = Path(tempfile.mkdtemp(prefix="aureon-public-layers-")) try: report = compose_repository_layers(repos_root=empty) finally: empty.rmdir() report["label"] = "cited. Empty-root hold join. Not a network observation." report["provenance"] = "cited" return _dumps(report)
@quietdef evidence_predict_next(values: list[float] | None = None) -> str: """evaluate.organism_proof.predict_next. Provenance: inferred.
This does not call evaluate_organism. HumanEval: not run. HOLD.
Args: values: Optional numbers. Omitted uses 1,2,3. Label: inferred for the call. The function is cited. """
series: list[float] = [] raw = [1.0, 2.0, 3.0] if values is None else values for item in raw: number = _finite(item) if number is None: return _dumps( { "human_eval": "not run. HOLD", "provenance": "cited", "reason": "A value is missing", "status": "unavailable", } ) series.append(number) from aureon.evaluation.organism_proof import predict_next
predicted = predict_next(series) return _dumps( { "human_eval": "not run. HOLD", "label": "inferred. predict_next. evaluate_organism was not called.", "predicted": predicted, "provenance": "inferred", "status": "inferred", } )
@quietdef source_names(package: str) -> str: """Top-level class and function names parsed from a package's Python files. Provenance: cited.
This reads source text with ast. It does not import the package and does not call those functions. Blocked packages are refused.
Args: package: aureon package name, or unified_margin_trader. Label: cited, the file names on disk. """
blocked = { "exchanges", "trading", "bots", "bots_intelligence", "bridges", "scanners", } if package in blocked or package == "unified_margin_trader": return _dumps( { "label": "cited. guard.py refuses these imports. Names are not loaded.", "package": package, "provenance": "cited", "status": "unavailable", } ) root = paths.repo_root() / "aureon" / package if not root.is_dir(): return _dumps( { "provenance": "cited", "reason": "Package directory is missing", "status": "unavailable", } ) names: list[dict[str, str]] = [] for path in sorted(root.glob("*.py")): if path.name == "__init__.py": continue try: tree = ast.parse(path.read_text(encoding="utf-8", errors="replace")) except SyntaxError: continue for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): names.append({"file": path.name, "kind": type(node).__name__, "name": node.name}) if len(names) >= 40: break if len(names) >= 40: break return _dumps( { "label": "cited. ast names only. Functions were not called.", "names": names, "package": package, "provenance": "cited", "status": "cited", } )
def _load_phenolic_fingerprint(root: Path | None = None) -> str | None: """Register the checkout's phenolic_fingerprint without putting the repo root on sys.path.
The file is executed only when its git blob is the blob at pin 8aa6a2d9. A different checkout copy is refused and is not loaded. """
from aureon_public.pin_blob import ( PHENOLIC_MISMATCH, PINNED_PHENOLIC_BLOB, load_pinned_source, )
base = paths.repo_root() if root is None else root path = base / "phenolic_fingerprint.py" return load_pinned_source( "phenolic_fingerprint", path, PINNED_PHENOLIC_BLOB, PHENOLIC_MISMATCH, )
def public_layer_tools() -> list[Any]: from aureon_public.alignment_layer import TOOLS as ALIGNMENT_TOOLS from aureon_public.more_layers import TOOLS from aureon_public.stage1_rest import TOOLS as STAGE1_TOOLS from aureon_public.stage2_layer import TOOLS as STAGE2_TOOLS
return [ package_dispositions, hnc_substrate_eval, hnc_echo_eval, hnc_observer_eval, hnc_potential_eval, hnc_translate_project, qgita_ftcp_detect, qgita_lighthouse_coherence, membrane_screen, repository_layers_hold, evidence_predict_next, source_names, *TOOLS, *ALIGNMENT_TOOLS, *STAGE1_TOOLS, *STAGE2_TOOLS, ]
def packages_resource() -> str: """Every package disposition, including operator exclusions. Provenance: inferred.
Auris meanings stay separate. The conjecture is not called. The nine nodes and the coherence evaluator are the utils tools. The persona is not scored. Label: inferred. """
return package_dispositions()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""One stdio session: list the catalog and call each tool once. Writes raw JSON."""
from __future__ import annotations
import argparseimport asyncioimport importlib.metadataimport jsonimport osimport sysfrom pathlib import Pathfrom typing import Any
from mcp import ClientSession, StdioServerParametersfrom mcp.client.stdio import stdio_client
from aureon_public import pathsfrom aureon_public.body import enabled_stage, probes_forfrom aureon_public.guard_loader import apply_space_guard
def _text_content(result: Any) -> str: parts = [] for block in result.content: text = getattr(block, "text", None) if text is not None: parts.append(text) return "\n".join(parts)
def _environment() -> dict[str, Any]: apply_space_guard() import aureon
direct = None try: dist = importlib.metadata.distribution("aureon") raw = dist.read_text("direct_url.json") direct = json.loads(raw) if raw else None except Exception as exc: # noqa: BLE001 - the record should say the pin was not readable direct = {"error": type(exc).__name__} return { "aureon_file": aureon.__file__, "aureon_direct_url": direct, "python": sys.executable, }
async def _session(out_path: Path) -> dict[str, Any]: env = { "PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", ""), "PYTHONUNBUFFERED": "1", } params = StdioServerParameters( command=sys.executable, args=["-m", "aureon_public"], env=env, cwd=str(Path.cwd()), ) async with stdio_client(params) as (read, write): async with ClientSession(read, write) as session: initialized = await session.initialize() tools = await session.list_tools() resources = await session.list_resources() prompts = await session.list_prompts() calls = {} for name, arguments in ( ("hnc_reality_step", {}), ("hnc_canonical_read", {}), ("hnc_blend_read", {}), ("lambda_engine_step", {}), ("auris_nodes", {}), ("auris_coherence", {}), ("qgita_analyze", {}), ("organism_replay_read", {}), ("organism_catalog", {}), ("package_dispositions", {}), ("hnc_substrate_eval", {}), ("hnc_echo_eval", {}), ("hnc_observer_eval", {}), ("hnc_potential_eval", {}), ("hnc_translate_project", {}), ("qgita_ftcp_detect", {}), ("qgita_lighthouse_coherence", {}), ("membrane_screen", {}), ("repository_layers_hold", {}), ("evidence_predict_next", {}), ("source_names", {"package": "core"}), ): result = await session.call_tool(name, arguments) calls[name] = { "arguments": arguments, "isError": result.isError, "text": _text_content(result), } # The class default is multiverse on. Record the other committed path # beside it so the two coherences are not mixed. for stage in range(1, enabled_stage() + 1): for probe in probes_for(stage): arguments = { "module": probe["module"], "symbol": probe["symbol"], "arguments_json": json.dumps(probe.get("arguments") or {}), } result = await session.call_tool("body_call", arguments) calls[f"body_call:{probe['symbol']}"] = { "arguments": arguments, "isError": result.isError, "text": _text_content(result), } depth = await session.call_tool("body_depth", {}) calls["body_depth"] = { "arguments": {}, "isError": depth.isError, "text": _text_content(depth), } surface = await session.call_tool( "body_surface", { "module": "harmonic/aureon_harmonic_reality.py", "symbol": "HarmonicSubstrate", }, ) calls["body_surface:HarmonicSubstrate"] = { "arguments": { "module": "harmonic/aureon_harmonic_reality.py", "symbol": "HarmonicSubstrate", }, "isError": surface.isError, "text": _text_content(surface), } off = await session.call_tool("hnc_reality_step", {"enable_multiverse": False}) calls["hnc_reality_step_multiverse_off"] = { "arguments": {"enable_multiverse": False}, "isError": off.isError, "text": _text_content(off), "note": "Not the class default. Committed multiverse-off path.", } resource_bodies = {} for item in resources.resources: uri = str(item.uri) body = await session.read_resource(uri) chunks = [] for block in body.contents: content = getattr(block, "content", None) text = getattr(block, "text", None) if text is not None: chunks.append(text) elif content is not None: chunks.append(str(content)) resource_bodies[uri] = "\n".join(chunks) prompt_bodies = {} for item in prompts.prompts: rendered = await session.get_prompt(item.name) messages = [] for message in rendered.messages: content = message.content messages.append(getattr(content, "text", str(content))) prompt_bodies[item.name] = messages record = { "environment": _environment(), "instructions_checked_in_process": True, "server_instructions": getattr(initialized, "instructions", None), "prompts": [ {"name": item.name, "description": item.description} for item in prompts.prompts ], "prompt_bodies": prompt_bodies, "resources": [ {"uri": str(item.uri), "name": item.name, "description": item.description} for item in resources.resources ], "resource_bodies": resource_bodies, "tools": [ { "name": item.name, "description": item.description, "inputSchema": item.inputSchema, } for item in tools.tools ], "calls": calls, } out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") return record
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-measure") parser.add_argument( "--out", type=Path, default=paths.repo_root() / "measured" / "aureon_public_run.json", ) args = parser.parse_args(argv) asyncio.run(_session(args.out))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Identity fields for a measured record.
The record names the commit that was HEAD while it was written. That commit isthe parent of the commit that adds the record file. A dirty working tree isrefused: the stamp would mix uncommitted edits into that commit name."""
from __future__ import annotations
import subprocessfrom pathlib import Path
from aureon_public.guard_loader import PINNED_COMMITfrom aureon_public.paths import repo_root
# git rev-parse 8aa6a2d971cc529484e2a5e261e28afafab4e4f4:aureonPIN_AUREON_TREE = "8aef927b7fe6276c187e4c73c79f0de012ad980d"CODE_COMMIT_NOTE = ( "This is the parent of the commit that contains this record. " "The record cannot name the commit that adds the file.")
def _git(*args: str) -> str: return subprocess.check_output( ["git", "-C", str(repo_root()), *args], text=True, ).strip()
def pin_tree_skip_reason(root: Path) -> str | None: """Why this checkout cannot be compared with the pinned aureon tree.
None means the comparison can run. A missing .git, a shallow clone, or a clone that does not contain the pin commit is skipped. The comparison itself stays an assertion when the history is present. """
if not (Path(root) / ".git").exists(): return "no .git; the pin tree comparison needs a git checkout" try: shallow = subprocess.check_output( ["git", "-C", str(root), "rev-parse", "--is-shallow-repository"], text=True, stderr=subprocess.STDOUT, ).strip() except (OSError, subprocess.CalledProcessError) as exc: detail = getattr(exc, "stdout", None) or str(exc) return f"git could not read this checkout: {detail}".strip() if shallow == "true": return "shallow clone; the pin commit may be absent" present = subprocess.run( ["git", "-C", str(root), "cat-file", "-e", f"{PINNED_COMMIT}^{{commit}}"], check=False, capture_output=True, text=True, ) if present.returncode != 0: return f"pin commit {PINNED_COMMIT} is not in this clone" return None
def measurement_stamp() -> dict[str, str]: """Pin, aureon/ tree hash, and the code commit that was HEAD.
Raises RuntimeError when git status --porcelain is not empty. """
dirty = _git("status", "--porcelain") if dirty.strip(): raise RuntimeError( "measurement_stamp refuses a dirty working tree. " "Commit the code, then write the measured record.\n" + dirty.strip() ) return { "aureon_tree": _git("rev-parse", "HEAD:aureon"), "code_commit": _git("rev-parse", "HEAD"), "code_commit_note": CODE_COMMIT_NOTE, "pin": PINNED_COMMIT, "pin_aureon_tree": _git("rev-parse", f"{PINNED_COMMIT}:aureon"), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632"""One helper function per package. A helper call is not that layer's cognition. No new formulas."""
from __future__ import annotations
import tempfilefrom datetime import datefrom pathlib import Pathfrom typing import Any
from aureon_public.quiet import quietfrom aureon_public.tools import _dumps as _public_dumpsfrom aureon_public.tools import _finite
def _dumps(payload: dict[str, Any]) -> str: label = payload.get("label") if isinstance(label, str) and not label.startswith("helper."): payload = dict(payload) payload["label"] = "helper. " + label return _public_dumps(payload)
# package, kind, reason. kind is the tool name or "excluded".UPDATES: tuple[tuple[str, str, str], ...] = ( ("alignment", "alignment_consonance", "consonance_score. No pillar singleton."), ("analytics", "analytics_fear_greed", "derive_fear_greed on a supplied series. No backtest run."), ("appliance", "appliance_sha256", "sha256_file on a temp file that is deleted. The repo is not hashed."), ("approval", "approval_subject_line", "subject_line only. Owner address is not read."), ("atn", "excluded", "Public functions fetch earthquakes, flares, or prices. Not called."), ("briefing", "briefing_severity", "severity_rank. The brief assembler and pytest runner are not called."), ("cognition", "cognition_logic_flow", "compute_logic_flow on an in-memory bus. summarize_patterns is a stage-2 tool. The report writer is not called."), ("command_centers", "excluded", "Entry points launch UIs or read API-key status. Not called."), ("conversion", "excluded", "The conversion hub takes capital and is not a pure read."), ("data_feeds", "data_feed_parse_tick", "parse_binance_tick on one dict. No socket is opened."), ("decoders", "decoder_haversine", "haversine stays import-refused. Stage-2 tools call the Sumerian and I Ching getters. Decoders are not started."), ("gates", "gates_reading", "is_human_held, ungrounded_nodes, and build_report on an empty check list. The benchmark runner is not called."), ("generated", "generated_default_inputs", "build_default_inputs. Deterministic score model. No network."), ("governance", "governance_seasonal_gate", "seasonal_gate_for_date. Live authorization is not issued."), ("grants", "grants_breath_interval", "breath_interval only. Dossiers are not read."), ("identity", "excluded", "read_identity can load personal files. Not called."), ("inhouse_ai", "excluded", "The tool registry can dispatch. Not re-exported."), ("integrations", "integrations_phi_plan", "build_phi_swarm_plan. No model is called."), ("intelligence", "intelligence_resonance", "calculate_harmonic_resonance. Trading permission is not called."), ("miner", "excluded", "The only public function constructs a bridge. Not called."), ("monitors", "excluded", "aureon_live_monitor exits on import without aiohttp, and the wave monitor sets LIVE=1. Not called."), ("observability", "observability_redact", "redact_observability_value. Events are not emitted."), ("observer", "observer_kp_sample", "parse_kp_file of the committed Kp file, one sample. Stage-2 tools read mode flags, the DE440 prefix, and the source registry. No download."), ("plumber", "plumber_sha256", "sha256_hex. No key is generated."), ("portals", "portals_html_to_text", "html_to_text. Dashboards are not fetched."), ("queen", "queen_zpe_ground", "compute_zpe_ground. Queen phase and order gates are not called."), ("s51", "s51_summarize_receipts", "summarize_compounding with no receipts, through dispatch. The sim is not run."), ("search", "search_summarize_text", "summarize_text. Online fetch is not called."), ("simulation", "simulation_hz_to_rgb", "hz_to_rgb. Simulations are not run."), ("swarm", "swarm_voice_for_gamma", "voice_for_gamma. The council is not convened."), ("swarm_motion", "excluded", "The only public function constructs the hive. Not called."), ("vault", "vault_count_words", "count_words. Key stores and persona files are not read."),)
def _apply() -> None: from aureon_public.layers import PACKAGES
by_name = {row["package"]: row for row in PACKAGES} for package, kind, reason in UPDATES: row = by_name[package] row["kind"] = kind row["reason"] = reason if reason.startswith("Helper only.") else "Helper only. " + reason
_apply()
def _missing(name: str) -> str: return _dumps( { "provenance": "cited", "reason": f"{name} is missing", "status": "unavailable", } )
@quietdef alignment_consonance(ratio: float = 1.0) -> str: """alignment.harmonic_resonance.consonance_score. Provenance: inferred.
Args: ratio: Frequency ratio. Non-positive is the function's own zero. Label: cited, consonance_score. """
number = _finite(ratio) if number is None: return _missing("ratio") from aureon.alignment.harmonic_resonance import consonance_score
return _dumps( { "label": "inferred. consonance_score.", "provenance": "inferred", "score": float(consonance_score(number)), "status": "inferred", } )
@quietdef analytics_fear_greed() -> str: """analytics.backtest_sentiment_oracle.derive_fear_greed on a 40-step series. Provenance: inferred.
No backtest is run. Trade readiness: HOLD.
Args: none: The series is a fixed 40-step fixture ramp, not market data. Label: inferred. """
from aureon.analytics.backtest_sentiment_oracle import derive_fear_greed
closes = [100.0 + index for index in range(40)] volumes = [1.0 for _ in range(40)] result = derive_fear_greed(closes, volumes, 39) result["label"] = "inferred. derive_fear_greed on a fixed 40-step fixture ramp, not market data. Not a backtest." result["provenance"] = "inferred" result["status"] = "inferred" result["trade_readiness"] = "HOLD" return _dumps(result)
@quietdef appliance_sha256() -> str: """appliance.build_pipeline.sha256_file on a temp file that is deleted. Provenance: cited.
Args: none: The bytes are written under the system temp directory and removed. Label: cited, sha256_file. """
from aureon.appliance.build_pipeline import sha256_file
handle = tempfile.NamedTemporaryFile(prefix="aureon-public-sha-", delete=False) path = Path(handle.name) try: handle.write(b"aureon-public") handle.close() digest = sha256_file(path) finally: path.unlink(missing_ok=True) return _dumps( { "label": "cited. sha256_file on a deleted temp file.", "provenance": "cited", "sha256": digest, "status": "cited", } )
@quietdef approval_subject_line(action: str = "status") -> str: """approval.compose.subject_line. Provenance: cited. The owner address is not read.
Args: action: Title text. Label: cited, subject_line. """
from aureon.approval.compose import subject_line
return _dumps( { "label": "cited. subject_line. No message is sent.", "provenance": "cited", "status": "cited", "subject": subject_line(action or "status"), } )
@quietdef briefing_severity(severity: str = "high") -> str: """briefing.schemas.severity_rank. Provenance: cited. The assembler is not called.
Args: severity: Rank label. Label: cited, severity_rank. """
from aureon.briefing.schemas import severity_rank
return _dumps( { "label": "cited. severity_rank.", "provenance": "cited", "rank": int(severity_rank(severity)), "status": "cited", } )
@quietdef cognition_logic_flow() -> str: """cognition.logic_flow.compute_logic_flow. Provenance: inferred.
The bus is in memory. write_logic_flow_report is not called. Trade readiness: HOLD.
Args: none: The function's own default seed score is used. Label: cited, compute_logic_flow. """
from aureon.cognition.logic_flow import compute_logic_flow
report = compute_logic_flow().to_dict() report["label"] = "inferred. compute_logic_flow. The report file was not written." report["provenance"] = "inferred" report["status"] = "inferred" report["trade_readiness"] = "HOLD" return _dumps(report)
@quietdef data_feed_parse_tick() -> str: """data_feeds.unified_ws_feed.parse_binance_tick on one dict. Provenance: inferred.
One fixture tick, not market data. No socket was opened. Trade readiness: HOLD.
Args: none: One fixture tick, not market data. No socket was opened. Label: inferred. """
from aureon.data_feeds.unified_ws_feed import parse_binance_tick
tick = parse_binance_tick( {"s": "BTCUSDT", "b": "1", "a": "2", "c": "1.5", "v": "3", "P": "0", "E": 1}, received_at=1.0, ) body = tick.__dict__ if tick is not None and hasattr(tick, "__dict__") else {"tick": None} body["label"] = "inferred. parse_binance_tick on one fixture tick, not market data. No socket was opened." body["provenance"] = "inferred" body["status"] = "inferred" if tick is not None else "unavailable" body["trade_readiness"] = "HOLD" return _dumps(body)
@quietdef decoder_haversine() -> str: """decoders.grail_convergence.haversine. Provenance: inferred.
Args: none: The two points are 0,0 and 0,1. Label: inferred. """
from aureon.decoders.grail_convergence import haversine
return _dumps( { "kilometres": float(haversine(0.0, 0.0, 0.0, 1.0)), "label": "inferred. haversine.", "provenance": "inferred", "status": "inferred", } )
@quietdef gates_reading(action: str = "draft") -> str: """gates.switchboard.is_human_held and gates.panel.ungrounded_nodes. Provenance: cited.
The benchmark writer is not called. Auris panel vote is not called. The nine-node list is the ungrounded-node return when no slice is grounded.
Args: action: Text passed to is_human_held. Label: cited, is_human_held. """
from aureon.gates.panel import ungrounded_nodes from aureon.gates.switchboard import is_human_held
return _dumps( { "human_held": bool(is_human_held(action)), "label": "cited. is_human_held and ungrounded_nodes. The panel was not convened.", "provenance": "cited", "status": "cited", "ungrounded_nodes": list(ungrounded_nodes(frozenset())), "which_auris": "Nine-node names from NODE_SLICE via ungrounded_nodes. Not the conjecture, not the persona, not the coherence evaluator.", } )
@quietdef governance_seasonal_gate() -> str: """governance.celtic_voice_bank.seasonal_gate_for_date. Provenance: cited.
Live authorization is not issued.
Args: none: The date is 2026-01-15. Label: cited, seasonal_gate_for_date. """
from aureon.governance.celtic_voice_bank import seasonal_gate_for_date
return _dumps( { "gate": seasonal_gate_for_date(date(2026, 1, 15)), "label": "cited. seasonal_gate_for_date.", "provenance": "cited", "status": "cited", } )
@quietdef grants_breath_interval() -> str: """grants.daemon.breath_interval. Provenance: cited. Dossiers are not read.
Args: none: urgency is None, which the function documents as its slowest interval. Label: cited, breath_interval. """
from aureon.grants.daemon import breath_interval
return _dumps( { "interval_s": float(breath_interval(None)), "label": "cited. breath_interval. No dossier was read.", "provenance": "cited", "status": "cited", } )
@quietdef integrations_phi_plan() -> str: """integrations.ollama.hnc_phi_swarm.build_phi_swarm_plan. Provenance: inferred.
No model is called.
Args: none: flow is observe and catalog_size is 2. Label: inferred. """
from aureon.integrations.ollama.hnc_phi_swarm import build_phi_swarm_plan
plan = build_phi_swarm_plan({"flow": "observe"}, catalog_size=2, max_total_calls=4) plan["label"] = "inferred. build_phi_swarm_plan. No model was called." plan["provenance"] = "inferred" plan["status"] = "inferred" return _dumps(plan)
@quietdef intelligence_resonance() -> str: """intelligence.aureon_advanced_intelligence.calculate_harmonic_resonance. Provenance: inferred.
Trading permission is not called.
Args: none: The two frequencies are 100 and 200. Label: inferred. """
from aureon.intelligence.aureon_advanced_intelligence import calculate_harmonic_resonance
return _dumps( { "label": "inferred. calculate_harmonic_resonance.", "provenance": "inferred", "resonance": float(calculate_harmonic_resonance(100.0, 200.0)), "status": "inferred", "trade_readiness": "HOLD", } )
@quietdef observability_redact() -> str: """observability.runtime.redact_observability_value. Provenance: cited. No event is emitted.
Args: none: The value is a short string with no secret. Label: cited, redact_observability_value. """
from aureon.observability.runtime import redact_observability_value
return _dumps( { "label": "cited. redact_observability_value.", "provenance": "cited", "redacted": redact_observability_value("public-note"), "status": "cited", } )
@quietdef observer_kp_sample() -> str: """observer.historical_backtest.parse_kp_file, one sample. Provenance: cited or unavailable.
The committed Kp file is read when it is present. Nothing is downloaded. Schumann f0: null. HOLD.
Args: none: start_year 2024 and max_samples 1. Label: cited, parse_kp_file. """
from aureon.observer.historical_backtest import DEFAULT_KP_PATH, parse_kp_file
if not DEFAULT_KP_PATH.is_file(): return _dumps( { "label": "cited. The committed Kp file is not in this tree.", "provenance": "cited", "reason": "Kp file missing", "schumann_f0": "null. HOLD", "status": "unavailable", } ) samples = parse_kp_file(DEFAULT_KP_PATH, start_year=2024, max_samples=1) first = samples[0] if samples else None return _dumps( { "count": len(samples), "kp": None if first is None else float(first.kp), "label": "cited. parse_kp_file, one sample. Not a Schumann measurement.", "provenance": "cited", "schumann_f0": "null. HOLD", "status": "cited" if first is not None else "unavailable", } )
@quietdef plumber_sha256() -> str: """plumber.crypto.sha256_hex. Provenance: cited. No key is generated.
Args: none: The text is aureon-public. Label: cited, sha256_hex. """
from aureon.plumber.crypto import sha256_hex
return _dumps( { "label": "cited. sha256_hex. No key was generated.", "provenance": "cited", "sha256": sha256_hex("aureon-public"), "status": "cited", } )
@quietdef portals_html_to_text() -> str: """portals.ifs.html_to_text. Provenance: cited. No dashboard is fetched.
Args: none: The HTML is a one-line fixture. Label: cited, html_to_text. """
from aureon.portals.ifs import html_to_text
return _dumps( { "label": "cited. html_to_text.", "provenance": "cited", "status": "cited", "text": html_to_text("<p>hold</p>"), } )
@quietdef queen_zpe_ground(lambda_t: float = 1.0) -> str: """queen.temporal_ground.compute_zpe_ground. Provenance: inferred.
This is the queen math already in that module. The phase ladder and order gates are not called. The persona is not scored. Trade readiness: HOLD.
Args: lambda_t: Field value. Label: cited, compute_zpe_ground. """
number = _finite(lambda_t) if number is None: return _missing("lambda_t") from aureon.queen.temporal_ground import compute_zpe_ground
body = compute_zpe_ground(number).to_dict() body["label"] = "inferred. compute_zpe_ground. Persona was not scored." body["provenance"] = "inferred" body["status"] = "inferred" body["trade_readiness"] = "HOLD" body["which_auris"] = "Not the conjecture, not the nine nodes, not the coherence evaluator, and not the persona." return _dumps(body)
@quietdef s51_summarize_receipts() -> str: """s51.aureon_51_compound.summarize_compounding with no receipts. Provenance: cited.
The sim is not run. Trade readiness: HOLD.
Args: none: An empty receipt list. Label: cited, summarize_compounding. """
from aureon.s51.aureon_51_compound import summarize_compounding
body = summarize_compounding([]) body["receipt_status"] = body.get("status") body["label"] = "cited. summarize_compounding with no receipts." body["provenance"] = "cited" body["status"] = "cited" body["trade_readiness"] = "HOLD" return _dumps(body)
@quietdef search_summarize_text() -> str: """search.online_research_cinema.summarize_text. Provenance: cited. No URL is fetched.
Args: none: One sentence and the topic hold. Label: cited, summarize_text. """
from aureon.search.online_research_cinema import summarize_text
return _dumps( { "label": "cited. summarize_text. No URL was fetched.", "provenance": "cited", "status": "cited", "summary": summarize_text("Hold the claim.", "hold"), } )
@quietdef simulation_hz_to_rgb() -> str: """simulation.aureon_world_simulator.hz_to_rgb. Provenance: inferred. No simulation is run.
Args: none: The frequency is 528. Label: inferred. """
from aureon.simulation.aureon_world_simulator import hz_to_rgb
red, green, blue = hz_to_rgb(528.0) return _dumps( { "blue": int(blue), "green": int(green), "label": "inferred. hz_to_rgb. No simulation was run.", "provenance": "inferred", "red": int(red), "status": "inferred", } )
@quietdef swarm_voice_for_gamma(gamma: float = 0.5) -> str: """swarm.druidic_council.voice_for_gamma. Provenance: inferred. The council is not convened.
Args: gamma: Coherence in 0 to 1. Label: cited, voice_for_gamma. """
number = _finite(gamma) if number is None: return _missing("gamma") from aureon.swarm.druidic_council import voice_for_gamma
try: band, weight = voice_for_gamma(number) except ValueError as exc: return _dumps( { "provenance": "cited", "reason": str(exc), "status": "unavailable", } ) return _dumps( { "label": "inferred. voice_for_gamma. The council was not convened.", "provenance": "inferred", "status": "inferred", "voice_band": band, "voice_weight": float(weight), } )
@quietdef vault_count_words() -> str: """vault.voice.document_artifact_skill.count_words. Provenance: cited.
Key stores and persona files are not read.
Args: none: The text is two words. Label: cited, count_words. """
from aureon.vault.voice.document_artifact_skill import count_words
return _dumps( { "count": int(count_words("two words")), "label": "cited. count_words. No vault file was read.", "provenance": "cited", "status": "cited", } )
TOOLS: list[Any] = [ alignment_consonance, analytics_fear_greed, appliance_sha256, approval_subject_line, briefing_severity, cognition_logic_flow, data_feed_parse_tick, decoder_haversine, gates_reading, governance_seasonal_gate, grants_breath_interval, integrations_phi_plan, intelligence_resonance, observability_redact, observer_kp_sample, plumber_sha256, portals_html_to_text, queen_zpe_ground, s51_summarize_receipts, search_summarize_text, simulation_hz_to_rgb, swarm_voice_for_gamma, vault_count_words,]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Locate the checkout that vendors the Space replays. Does not write."""
from __future__ import annotations
from pathlib import Path
_MARKER = Path("huggingface") / "hnc-field" / "guard.py"_AUREON = Path("aureon") / "core" / "hnc_field.py"
def repo_root() -> Path: """Directory that contains both the Space guard and the aureon package.
Raises FileNotFoundError when this process is not inside that checkout. The server needs the checkout, the same as the earlier public server. """
here = Path(__file__).resolve() for parent in here.parents: if (parent / _MARKER).is_file() and (parent / _AUREON).is_file(): return parent raise FileNotFoundError("huggingface/hnc-field/guard.py was not found above the server")
def brain_json() -> Path: return repo_root() / "huggingface" / "hnc-field" / "replay" / "brain.json"
def qgita_json() -> Path: return repo_root() / "huggingface" / "qgita-snr" / "replay" / "qgita_snr.json"
def qgita_series() -> Path: return repo_root() / "huggingface" / "qgita-snr" / "data" / "de440_timeseries.csv"
def organism_json() -> Path: return repo_root() / "huggingface" / "organism-replay" / "replay" / "organism.json"
def auris_json() -> Path: return repo_root() / "huggingface" / "fixed-seed-reproducible-runs" / "auris_nodes.json"
def holds_readme() -> Path: return repo_root() / "huggingface" / "README.md"
def space_guard() -> Path: return repo_root() / "huggingface" / "hnc-field" / "guard.py"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350"""Git-blob check for a file loaded from the checkout beside a pinned aureon.
Every checkout load goes through ``load_pinned_source`` or the pinned finder.Those helpers require the expected blob, read the file once, and executethose same bytes. ``huggingface/hnc-field/guard.py`` is checked the same way.Nothing under ``mcp/`` uses ``spec_from_file_location``."""
from __future__ import annotations
import hashlibimport importlib.utilimport sysfrom importlib.abc import Loaderfrom pathlib import Pathfrom types import ModuleType
PINNED_PHENOLIC_BLOB = "325484e9299eecb427cf0063590b0a1d17c16f31"PHENOLIC_MISMATCH = "checkout phenolic_fingerprint differs from pin 8aa6a2d9"
def git_blob_sha1(data: bytes) -> str: """SHA-1 of a git blob: the header ``blob <len>\\0`` plus the file bytes."""
header = f"blob {len(data)}\0".encode("ascii") return hashlib.sha1(header + data).hexdigest()
def pinned_blob_refusal(path: Path, expected: str, mismatch: str) -> str | None: """Return mismatch text when path is not the pinned blob. None when it matches."""
if not path.is_file(): return f"{path.name} is not in this checkout" digest = git_blob_sha1(path.read_bytes()) if digest != expected: return mismatch return None
class _SameBytesLoader(Loader): """Execute the bytes already hashed. Does not read the path again."""
def __init__(self, data: bytes, origin: str) -> None: self._data = data self._origin = origin
def create_module(self, spec: object) -> None: return None
def exec_module(self, module: ModuleType) -> None: module.__file__ = self._origin origin = Path(self._origin) if origin.name == "__init__.py": module.__path__ = [str(origin.parent)] code = compile(self._data, self._origin, "exec") exec(code, module.__dict__)
def expected_pin_blob(path: Path, root: Path, commit: str) -> tuple[str | None, str | None]: """Return the blob hash recorded at ``commit`` for ``path``.
This reads git, not the working-tree file. ``(None, None)`` means the path is outside the checkout. """
try: relative = path.resolve().relative_to(root.resolve()).as_posix() except ValueError: return None, None import subprocess
try: pin_blob = subprocess.check_output( ["git", "rev-parse", f"{commit}:{relative}"], cwd=root, text=True, stderr=subprocess.DEVNULL, ).strip() except (OSError, subprocess.CalledProcessError): return None, f"{relative} is not in pin {commit[:12]}" if not pin_blob: return None, "expected blob is required" return pin_blob, None
class PinnedAureonFinder: """Blob-check every ``aureon`` import against the pin. A mismatch raises."""
def __init__(self, root: Path, commit: str) -> None: self.root = root self.commit = commit
def find_spec(self, fullname: str, path: object, target: object = None) -> object: del path, target if fullname != "aureon" and not fullname.startswith("aureon."): return None relative = self._relative(fullname) if relative is None: raise ImportError(f"{fullname} is not an aureon module path") expected, error = expected_pin_blob(self.root / relative, self.root, self.commit) if error or not expected: raise ImportError(error or "expected blob is required") for candidate in self._files(fullname, relative): try: data = candidate.read_bytes() except OSError: continue if git_blob_sha1(data) != expected: continue return self._spec(fullname, data, candidate) raise ImportError(f"checkout {relative} differs from pin {self.commit[:12]}")
def _relative(self, fullname: str) -> str | None: parts = fullname.split(".") py_file = Path(*parts).with_suffix(".py") init_file = Path(*parts) / "__init__.py" for relative in (py_file, init_file): expected, _error = expected_pin_blob(self.root / relative, self.root, self.commit) if expected: return relative.as_posix() return None
def _files(self, fullname: str, relative: str) -> list[Path]: files: list[Path] = [] checkout = self.root / relative installed = self._installed_origin(fullname) # The pin install is first when direct_url.json names this pin. # Every candidate still has to match the pin blob before it runs. # An install of any other commit stays behind the checkout. pinned = self._pinned_install(installed) if pinned is not None: files.append(pinned) if checkout.is_file() and checkout not in files: files.append(checkout) if installed is not None and installed not in files: files.append(installed) return files
def _pinned_install(self, installed: Path | None) -> Path | None: if installed is None or not installed.is_file(): return None from aureon_public.guard_loader import _direct_url_commit, _outside_checkout
if not _outside_checkout(installed, self.root): return None if _direct_url_commit(installed) != self.commit: return None return installed
def _installed_origin(self, fullname: str) -> Path | None: removed = [finder for finder in sys.meta_path if isinstance(finder, PinnedAureonFinder)] for finder in removed: sys.meta_path.remove(finder) try: spec = importlib.util.find_spec(fullname) finally: for finder in reversed(removed): sys.meta_path.insert(0, finder) origin = getattr(spec, "origin", None) if spec is not None else None if not origin or origin == "namespace": return None path = Path(origin) return path if path.is_file() else None
def _spec(self, fullname: str, data: bytes, path: Path) -> object: loader = _SameBytesLoader(data, str(path)) spec = importlib.util.spec_from_loader(fullname, loader, origin=str(path)) if spec is None: raise ImportError(f"{fullname} could not be loaded") spec.has_location = True if path.name == "__init__.py": spec.submodule_search_locations = [str(path.parent)] return spec
def _loaded_by_finder(module: object) -> bool: loader = getattr(getattr(module, "__spec__", None), "loader", None) return isinstance(loader, _SameBytesLoader)
def refuse_preseeded_aureon() -> None: """Raise when an ``aureon`` module is already loaded by another loader.
``import`` returns a ``sys.modules`` hit without calling the finder. A guard or a caller that plants a fake module first would skip the blob check. """
for name, module in list(sys.modules.items()): if module is None: continue if name != "aureon" and not name.startswith("aureon."): continue if not _loaded_by_finder(module): raise ImportError(f"{name} was not loaded through the pinned finder")
def import_through_finder(dotted: str) -> ModuleType: """Import ``dotted`` and each parent through ``PinnedAureonFinder``.
``find_spec`` on the full name is not used. That call imports parent packages before any blob check. A parent already in ``sys.modules`` from another loader is refused rather than reused. """
if dotted != "aureon" and not dotted.startswith("aureon."): raise ImportError("only an aureon module can be loaded") install_pinned_aureon_finder() parts = dotted.split(".") for index in range(1, len(parts) + 1): name = ".".join(parts[:index]) existing = sys.modules.get(name) if existing is not None: if not _loaded_by_finder(existing): raise ImportError(f"{name} was not loaded through the pinned finder") continue importlib.import_module(name) loaded = sys.modules.get(name) if loaded is None or not _loaded_by_finder(loaded): raise ImportError(f"{name} was not loaded through the pinned finder") module = sys.modules.get(dotted) if module is None: raise ImportError(f"{dotted} could not be loaded") return module
def install_pinned_aureon_finder(root: Path | None = None, commit: str | None = None) -> PinnedAureonFinder: """Install the finder once. Later aureon imports fail closed on a blob mismatch."""
from aureon_public.guard_loader import PINNED_COMMIT from aureon_public.paths import repo_root
base = repo_root() if root is None else root pin = PINNED_COMMIT if commit is None else commit for finder in sys.meta_path: if isinstance(finder, PinnedAureonFinder): return finder finder = PinnedAureonFinder(base, pin) sys.meta_path.insert(0, finder) return finder
def load_pinned_source(module_name: str, path: Path, expected_blob: str, mismatch: str) -> str | None: """Read ``path`` once. Refuse unless those bytes are ``expected_blob``. Exec them.
Returns None when the module is ready. A refusal string means it was not executed. An empty ``expected_blob`` is a refusal and does not read the file. """
if not expected_blob: return "expected blob is required" try: data = path.read_bytes() except OSError: return f"{path.name} is not in this checkout" if git_blob_sha1(data) != expected_blob: return mismatch if module_name in sys.modules: return None loader = _SameBytesLoader(data, str(path)) spec = importlib.util.spec_from_loader(module_name, loader, origin=str(path)) if spec is None: return f"{path.name} could not be loaded" spec.has_location = True if path.name == "__init__.py": spec.submodule_search_locations = [str(path.parent)] module = importlib.util.module_from_spec(spec) module.__file__ = str(path) if path.name == "__init__.py": module.__path__ = [str(path.parent)] parent_name, _, child = module_name.rpartition(".") module.__package__ = parent_name if parent_name else module_name sys.modules[module_name] = module try: loader.exec_module(module) except Exception as exc: sys.modules.pop(module_name, None) return f"{type(exc).__name__}: {exc}"[:240] parent = sys.modules.get(parent_name) if parent_name else None if parent is not None: setattr(parent, child, module) return None
def load_checkout_module(module_name: str, path: Path, root: Path, commit: str) -> tuple[ModuleType | None, str | None]: """Load a checkout module and its checkout parents through ``load_pinned_source``."""
parts = module_name.split(".") for index in range(1, len(parts)): parent_name = ".".join(parts[:index]) if parent_name in sys.modules: continue parent_path = root.joinpath(*parts[:index], "__init__.py") expected, error = expected_pin_blob(parent_path, root, commit) if error or not expected: return None, error or "expected blob is required" refusal = load_pinned_source( parent_name, parent_path, expected, f"checkout {parent_path.relative_to(root).as_posix()} differs from pin {commit[:12]}", ) if refusal: return None, refusal expected, error = expected_pin_blob(path, root, commit) if error or not expected: return None, error or "expected blob is required" try: relative = path.resolve().relative_to(root.resolve()).as_posix() except ValueError: relative = path.name refusal = load_pinned_source( module_name, path, expected, f"checkout {relative} differs from pin {commit[:12]}", ) if refusal: return None, refusal loaded = sys.modules.get(module_name) if loaded is None: return None, f"{path.name} could not be loaded" return loaded, None
def checkout_blob_refusal(path: Path, root: Path, commit: str) -> str | None: """Refuse a checkout file whose git blob is not the blob at ``commit``.
Returns None when the bytes match. A missing pin path is a refusal. The caller skips this when the import comes from an installed copy outside the checkout. """
if not path.is_file(): return f"{path} is not in this checkout" try: relative = path.resolve().relative_to(root.resolve()).as_posix() except ValueError: return "path is outside the checkout" expected, error = expected_pin_blob(path, root, commit) if error: return error if not expected: return "expected blob is required" try: data = path.read_bytes() except OSError: return f"{path.name} is not in this checkout" if git_blob_sha1(data) != expected: return f"checkout {relative} differs from pin {commit[:12]}" return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258"""Stdio and Streamable HTTP sessions against aureon-public.
Run from measured/aureon_public_protocol_run.sh. Do not hand-edit the output.
The process requires AUREON_PUBLIC_REQUIRE_PIN=1 and an aureon install whosedirect_url.json names the pin. The HTTP listener is 127.0.0.1. One tools/callis alignment_consonance_read with ratio 1.0."""
from __future__ import annotations
import argparseimport asyncioimport importlib.metadataimport jsonimport osimport signalimport socketimport subprocessimport sysimport tempfileimport timefrom pathlib import Pathfrom typing import Any
from mcp import ClientSession, StdioServerParametersfrom mcp.client.stdio import stdio_clientfrom mcp.client.streamable_http import streamable_http_client
from aureon_public import pathsfrom aureon_public.guard_loader import aureon_sourcefrom aureon_public.server import enforce_public_pin
TOOL_NAME = "alignment_consonance_read"TOOL_ARGUMENTS = {"ratio": 1.0}_BIND_HOST = "127.0.0.1"
def _dump(model: Any) -> dict[str, Any]: return model.model_dump(mode="json", by_alias=True)
def _server_env() -> dict[str, str]: env: dict[str, str] = {} for key in ("HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER", "LANG", "TMPDIR"): value = os.environ.get(key) if value: env[key] = value env["PYTHONUNBUFFERED"] = "1" env["AUREON_PUBLIC_REQUIRE_PIN"] = "1" return env
async def _list_pages(method: Any) -> list[dict[str, Any]]: pages: list[dict[str, Any]] = [] cursor: str | None = None seen: set[str] = set() while True: result = await method() if cursor is None else await method(cursor=cursor) page = _dump(result) pages.append(page) nxt = page.get("nextCursor") if not isinstance(nxt, str) or not nxt or nxt in seen: return pages seen.add(nxt) cursor = nxt
async def _exchange(session: ClientSession) -> dict[str, Any]: initialized = await session.initialize() tools_list = await _list_pages(session.list_tools) resources_list = await _list_pages(session.list_resources) prompts_list = await _list_pages(session.list_prompts) called = await session.call_tool(TOOL_NAME, TOOL_ARGUMENTS) return { "initialize": _dump(initialized), "prompts_list": prompts_list, "resources_list": resources_list, "tools_call": { "arguments": TOOL_ARGUMENTS, "name": TOOL_NAME, "result": _dump(called), }, "tools_list": tools_list, }
async def _stdio_session() -> dict[str, Any]: params = StdioServerParameters( command=sys.executable, args=["-m", "aureon_public"], env=_server_env(), cwd=str(Path.cwd()), ) async with stdio_client(params) as (read, write): async with ClientSession(read, write) as session: return await _exchange(session)
def _free_port() -> int: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind((_BIND_HOST, 0)) return int(sock.getsockname()[1])
def _port_open(port: int) -> bool: try: with socket.create_connection((_BIND_HOST, port), timeout=0.2): return True except OSError: return False
def _stop_process_group(proc: subprocess.Popen[str]) -> None: if proc.poll() is not None: return try: os.killpg(proc.pid, signal.SIGTERM) except ProcessLookupError: return try: proc.wait(timeout=5) except subprocess.TimeoutExpired: try: os.killpg(proc.pid, signal.SIGKILL) except ProcessLookupError: return proc.wait(timeout=5)
def _wait_until_listening(proc: subprocess.Popen[str], log_path: Path, port: int) -> None: deadline = time.monotonic() + 30 while time.monotonic() < deadline: if proc.poll() is not None: raise RuntimeError(_log_tail(log_path) or f"server exited {proc.returncode}") if _port_open(port): return time.sleep(0.1) raise TimeoutError(_log_tail(log_path) or f"{_BIND_HOST}:{port} did not accept a connection")
def _log_tail(path: Path) -> str: try: text = path.read_text(encoding="utf-8", errors="replace") except OSError: return "" return text[-4000:]
async def _http_session(port: int) -> dict[str, Any]: url = f"http://{_BIND_HOST}:{port}/mcp" log_fd, log_name = tempfile.mkstemp(prefix="aureon-public-http-") os.close(log_fd) log_path = Path(log_name) log = log_path.open("w", encoding="utf-8") proc = subprocess.Popen( [ sys.executable, "-m", "aureon_public", "--transport", "streamable-http", "--host", _BIND_HOST, "--port", str(port), ], cwd=str(Path.cwd()), env=_server_env(), stdout=log, stderr=subprocess.STDOUT, start_new_session=True, text=True, ) try: _wait_until_listening(proc, log_path, port) last: BaseException | None = None for _attempt in range(8): if proc.poll() is not None: break try: body = await _exchange_http(url) return { "host": _BIND_HOST, "port": port, "url": url, **body, } except Exception as exc: # noqa: BLE001 - the listener can accept TCP before MCP answers last = exc await asyncio.sleep(0.25) tail = _log_tail(log_path) raise RuntimeError(f"streamable http session failed: {last}\n{tail}") finally: log.close() _stop_process_group(proc) log_path.unlink(missing_ok=True)
async def _exchange_http(url: str) -> dict[str, Any]: async with streamable_http_client(url) as (read, write, _get_session_id): async with ClientSession(read, write) as session: return await _exchange(session)
def _environment() -> dict[str, Any]: os.environ["AUREON_PUBLIC_REQUIRE_PIN"] = "1" enforce_public_pin() import aureon
direct = None try: dist = importlib.metadata.distribution("aureon") raw = dist.read_text("direct_url.json") direct = json.loads(raw) if raw else None except Exception as exc: # noqa: BLE001 - the record should say the pin was not readable direct = {"error": type(exc).__name__} from aureon_public.measurement_stamp import measurement_stamp
return { "aureon_direct_url": direct, "aureon_file": aureon.__file__, "aureon_source": aureon_source(), "mcp": importlib.metadata.version("mcp"), "python": sys.executable, "require_pin": "1", **measurement_stamp(), }
async def _run(out_path: Path) -> dict[str, Any]: os.environ["AUREON_PUBLIC_REQUIRE_PIN"] = "1" enforce_public_pin() stdio = await _stdio_session() http = await _http_session(_free_port()) record = { "environment": _environment(), "stdio": stdio, "streamable_http": http, } out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") return record
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-protocol-measure") parser.add_argument( "--out", type=Path, default=paths.repo_root() / "measured" / "aureon_public_protocol.json", ) args = parser.parse_args(argv) asyncio.run(_run(args.out))
if __name__ == "__main__": main()1234567891011121314151617181920212223"""Keep import banners off stdout. MCP stdio uses stdout for JSON-RPC."""
from __future__ import annotations
import sysfrom functools import wrapsfrom typing import Any, Callable
def quiet(fn: Callable[..., Any]) -> Callable[..., Any]: @wraps(fn) def wrapped(*args: Any, **kwargs: Any) -> Any: from aureon_public.guard_loader import apply_space_guard
apply_space_guard() saved = sys.stdout sys.stdout = sys.stderr try: return fn(*args, **kwargs) finally: sys.stdout = saved
return wrapped1234567# aureon is pinned to the commit the Spaces and the measured brain run use.# mcp==1.30.0,<2 installs 1.30.0 and excludes every 2.x release.# MCP 2 renamed FastMCP to MCPServer. Migration is a later decision.# The check and the sources are in mcp/aureon_public/COVERAGE_PLAN.md.mcp==1.30.0,<2numpy>=1.26aureon @ git+https://github.com/RA-CONSULTING/Aureon-OS.git@8aa6a2d971cc529484e2a5e261e28afafab4e4f4123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""FastMCP server aureon-public. stdio by default, streamable HTTP optional."""
from __future__ import annotations
import argparseimport jsonimport loggingimport osimport sys
from mcp.server.fastmcp import FastMCP
from aureon_public import body, layers, surfaces, toolsfrom aureon_public.guard_loader import PINNED_COMMIT, apply_space_guard, aureon_sourcefrom aureon_public.text import SERVER_PLAIN
SERVER_INSTRUCTIONS = ( f"{SERVER_PLAIN} " "This server is read-only. It does not place orders, read keys, start circulation, " "self-code, self-repair, or write the repository or state/.")
def refuse_sweep_environment() -> None: """AUREON_PUBLIC_SWEEP is not a server mode. Setting it must not start the server."""
if os.environ.get("AUREON_PUBLIC_SWEEP"): raise SystemExit("AUREON_PUBLIC_SWEEP must not be set. The server will not start.")
def enforce_public_pin(source: dict[str, str] | None = None) -> None: """Refuse to start when public hosting requires the pinned commit.
AUREON_PUBLIC_REQUIRE_PIN=1 is unset for local runs. Those runs still report aureon_source. Public hosting must set the variable. """
if os.environ.get("AUREON_PUBLIC_REQUIRE_PIN") != "1": return current = aureon_source() if source is None else source if current.get("kind") == "pinned" and current.get("commit") == PINNED_COMMIT: return raise SystemExit( "AUREON_PUBLIC_REQUIRE_PIN=1 requires aureon_source kind pinned " f"at {PINNED_COMMIT}. This process would use {current}." )
def build_server(host: str = "127.0.0.1", port: int = 8077) -> FastMCP: """Register the milestone-1 tools, resources, and prompts."""
refuse_sweep_environment() apply_space_guard() source = aureon_source() instructions = ( f"{SERVER_INSTRUCTIONS} " f"aureon_source={json.dumps(source, sort_keys=True)}" ) server = FastMCP( "aureon-public", instructions=instructions, host=host, port=port, streamable_http_path="/mcp", # JSON responses and no session. GET /mcp is not a long-lived event # stream. The HTTP guard answers that GET with 405 so it cannot hold # an in-flight call slot. json_response=True, stateless_http=True, ) for fn in ( tools.hnc_reality_step, tools.hnc_canonical_read, tools.hnc_blend_read, tools.lambda_engine_step, tools.auris_nodes, tools.auris_coherence, tools.qgita_analyze, tools.organism_replay_read, tools.organism_catalog, *layers.public_layer_tools(), body.body_call, body.body_surface, body.body_depth, body.body_registry, ): server.tool()(fn) server.resource("aureon://packages", mime_type="application/json")(layers.packages_resource) server.resource( "aureon://hnc/harmonic-reality/defaults", mime_type="application/json", )(surfaces.harmonic_reality_defaults) server.resource( "aureon://hnc/lambda-engine/defaults", mime_type="application/json", )(surfaces.lambda_engine_defaults) server.resource( "aureon://hnc/params/code-defaults", mime_type="application/json", )(surfaces.hnc_params_code_defaults) server.resource( "aureon://auris/nodes", mime_type="application/json", description=surfaces.auris_nodes_resource.__doc__, )(surfaces.auris_nodes_resource) server.resource("aureon://organism/seats", mime_type="application/json")(surfaces.organism_seats_resource) server.resource("aureon://organism/nodes", mime_type="application/json")(surfaces.organism_nodes_resource) server.resource("aureon://organism/systems", mime_type="application/json")(surfaces.organism_systems_resource) server.resource("aureon://body/depth", mime_type="application/json")(body.body_depth) server.resource("aureon://body/registry", mime_type="application/json")(body.body_registry) server.resource("aureon://holds", mime_type="application/json")(surfaces.holds_resource) server.resource("aureon://replay/brain", mime_type="application/json")(surfaces.replay_brain_resource) server.resource("aureon://replay/qgita", mime_type="application/json")(surfaces.replay_qgita_resource) server.resource("aureon://replay/organism", mime_type="application/json")(surfaces.replay_organism_resource) server.resource( "aureon://replay/auris", mime_type="application/json", description=surfaces.replay_auris_resource.__doc__, )(surfaces.replay_auris_resource) for fn in ( surfaces.explain_two_lambda_implementations, surfaces.explain_auris_four_meanings, surfaces.explain_qgita_adapter, surfaces.explain_organism_replay, ): server.prompt()(fn) return server
def streamable_http_config(app: object, host: str, port: int): """Uvicorn config that does not rewrite the client from forwarded headers.
Uvicorn's default ``proxy_headers`` trusts ``X-Forwarded-For`` from 127.0.0.1 and replaces ``scope["client"]`` before this process's middleware runs. ``proxy_headers=False`` and an empty ``forwarded_allow_ips`` leave that header for ``http_guard`` only. """
import uvicorn
return uvicorn.Config( app, host=host, port=port, log_level="warning", proxy_headers=False, forwarded_allow_ips="", )
def serve_streamable_http(server: FastMCP, host: str, port: int) -> None: """Listen with the bearer check and the rate, size, and timeout limits."""
import uvicorn
from aureon_public.http_guard import PublicHttpMiddleware, load_http_limits
app = PublicHttpMiddleware(server.streamable_http_app(), load_http_limits()) uvicorn.Server(streamable_http_config(app, host, port)).run()
def main(argv: list[str] | None = None) -> None: """stdio, or streamable HTTP when --transport streamable-http is set."""
logging.basicConfig(stream=sys.stderr, level=logging.WARNING) parser = argparse.ArgumentParser(prog="aureon-public") parser.add_argument("--transport", choices=("stdio", "streamable-http"), default="stdio") parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", type=int, default=8077) args = parser.parse_args(argv) refuse_sweep_environment() apply_space_guard() enforce_public_pin() if args.transport == "stdio": build_server().run(transport="stdio") return from aureon_public.http_guard import resolve_http_bind
host = resolve_http_bind(args.host) server = build_server(host=host, port=args.port) serve_streamable_http(server, host, args.port)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Hugging Face Space entry for aureon-public. This file does not deploy it.
The process sets AUREON_PUBLIC_REQUIRE_PIN=1 and AUREON_OBSERVER_MODE=dry_run.AUREON_PUBLIC_SWEEP must be unset. The image must not contain an API key.Set AUREON_PUBLIC_API_KEY at runtime to require a bearer token. SetAUREON_PUBLIC_OPEN=1, with no key, to serve the read-only surface on apublic bind. With neither, the listener is 127.0.0.1."""
from __future__ import annotations
import jsonimport osimport sys
from aureon_public.http_guard import resolve_http_bindfrom aureon_public.server import ( build_server, enforce_public_pin, refuse_sweep_environment, serve_streamable_http,)
_QUEEN_MODULE = "queen/temporal_ground.py"_QUEEN_SYMBOL = "compute_zpe_ground"_QUEEN_REASON = "plan stage 4 is not open"_CLOSED_PACKAGES = ("miner", "accounting", "queen", "exchanges", "trading")
def prepare_space_environment() -> None: """Pin, dry-run, and the sweep refusal. Does not set a key or OPEN."""
if os.environ.get("AUREON_PUBLIC_SWEEP"): raise SystemExit("AUREON_PUBLIC_SWEEP must not be set. The server will not start.") mode = os.environ.get("AUREON_OBSERVER_MODE", "").strip() if mode and mode != "dry_run": raise SystemExit("AUREON_OBSERVER_MODE must be dry_run.") os.environ["AUREON_OBSERVER_MODE"] = "dry_run" os.environ["AUREON_PUBLIC_REQUIRE_PIN"] = "1" refuse_sweep_environment() enforce_public_pin()
def closed_stage_report() -> dict: """Stage 3 and 4 stay closed inside this entry point."""
from aureon_public.body import body_call, package_depth
depth = package_depth() queen_text = body_call(_QUEEN_MODULE, _QUEEN_SYMBOL) queen = json.loads(queen_text) packages = {name: depth[name] for name in _CLOSED_PACKAGES} reachable = {name: packages[name]["reachable"] for name in _CLOSED_PACKAGES} queen_refused = queen.get("called") is not True and queen.get("reason") == _QUEEN_REASON closed = all(reachable[name] == 0 for name in _CLOSED_PACKAGES) return { "closed_packages_reachable": reachable, "observer_mode": os.environ.get("AUREON_OBSERVER_MODE", ""), "ok": bool(queen_refused and closed and os.environ.get("AUREON_OBSERVER_MODE") == "dry_run"), "queen_call": queen, "require_pin": os.environ.get("AUREON_PUBLIC_REQUIRE_PIN", ""), "sweep_set": bool(os.environ.get("AUREON_PUBLIC_SWEEP")), }
def space_host() -> str: """0.0.0.0 when a key or OPEN=1 allows it. Otherwise 127.0.0.1."""
requested = os.environ.get("AUREON_PUBLIC_HOST", "").strip() if not requested: unlocked = bool(os.environ.get("AUREON_PUBLIC_API_KEY", "").strip()) unlocked = unlocked or os.environ.get("AUREON_PUBLIC_OPEN") == "1" requested = "0.0.0.0" if unlocked else "127.0.0.1" return resolve_http_bind(requested)
def space_port() -> int: raw = os.environ.get("PORT", "7860").strip() or "7860" try: port = int(raw) except ValueError as exc: raise SystemExit("PORT must be an integer") from exc if port <= 0: raise SystemExit("PORT must be an integer") return port
def main(argv: list[str] | None = None) -> None: """Serve Streamable HTTP, or print the closed-stage report for --check."""
args = list(sys.argv[1:] if argv is None else argv) prepare_space_environment() if "--check" in args: report = closed_stage_report() sys.stdout.write(json.dumps(report, sort_keys=True) + "\n") if not report["ok"]: raise SystemExit(1) return host = space_host() port = space_port() server = build_server(host=host, port=port) serve_streamable_http(server, host, port)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240"""Authenticated session against python -m aureon_public.space.
Run from measured/aureon_public_space_run.sh. Do not hand-edit the output.Docker is not required. The script records which runtime answered.The bearer token is generated in this process and is not written to the record."""
from __future__ import annotations
import argparseimport asyncioimport importlib.metadataimport jsonimport osimport secretsimport signalimport socketimport subprocessimport sysimport tempfileimport timefrom pathlib import Pathfrom typing import Any
import httpxfrom mcp import ClientSessionfrom mcp.client.streamable_http import streamable_http_client
from aureon_public import pathsfrom aureon_public.guard_loader import aureon_sourcefrom aureon_public.server import enforce_public_pin
_BIND_HOST = "127.0.0.1"_RUNTIME = "local entry point python -m aureon_public.space; Docker is not installed on this machine"
def _dump(model: Any) -> dict[str, Any]: return model.model_dump(mode="json", by_alias=True)
def _server_env(api_key: str) -> dict[str, str]: env: dict[str, str] = {} for key in ("HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER", "LANG", "TMPDIR"): value = os.environ.get(key) if value: env[key] = value env["PYTHONUNBUFFERED"] = "1" env["AUREON_PUBLIC_API_KEY"] = api_key env["AUREON_PUBLIC_HOST"] = _BIND_HOST env.pop("AUREON_PUBLIC_OPEN", None) return env
def _free_port() -> int: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind((_BIND_HOST, 0)) return int(sock.getsockname()[1])
def _port_open(port: int) -> bool: try: with socket.create_connection((_BIND_HOST, port), timeout=0.2): return True except OSError: return False
def _stop(proc: subprocess.Popen[str]) -> None: if proc.poll() is not None: return try: os.killpg(proc.pid, signal.SIGTERM) except ProcessLookupError: return try: proc.wait(timeout=5) except subprocess.TimeoutExpired: try: os.killpg(proc.pid, signal.SIGKILL) except ProcessLookupError: return proc.wait(timeout=5)
def _log_tail(path: Path) -> str: try: return path.read_text(encoding="utf-8", errors="replace")[-4000:] except OSError: return ""
def _entry_check(env: dict[str, str]) -> dict[str, Any]: completed = subprocess.run( [sys.executable, "-m", "aureon_public.space", "--check"], cwd=str(Path.cwd()), env=env, capture_output=True, text=True, check=False, ) if completed.returncode != 0: raise RuntimeError(completed.stderr[-4000:] or completed.stdout[-4000:]) return json.loads(completed.stdout)
async def _exchange(session: ClientSession) -> dict[str, Any]: initialized = await session.initialize() tools = _dump(await session.list_tools()) consonance = await session.call_tool("alignment_consonance_read", {"ratio": 1.0}) queen = await session.call_tool( "body_call", { "module": "queen/temporal_ground.py", "symbol": "compute_zpe_ground", "arguments_json": "", }, ) return { "initialize": _dump(initialized), "tools_call": [ { "arguments": {"ratio": 1.0}, "name": "alignment_consonance_read", "result": _dump(consonance), }, { "arguments": { "arguments_json": "", "module": "queen/temporal_ground.py", "symbol": "compute_zpe_ground", }, "name": "body_call", "result": _dump(queen), }, ], "tools_list": [tools], }
async def _session(url: str, api_key: str) -> dict[str, Any]: headers = {"Authorization": f"Bearer {api_key}"} async with httpx.AsyncClient(headers=headers, timeout=60.0) as client: async with streamable_http_client(url, http_client=client) as (read, write, _session_id): async with ClientSession(read, write) as session: return await _exchange(session)
def _environment() -> dict[str, Any]: os.environ["AUREON_PUBLIC_REQUIRE_PIN"] = "1" enforce_public_pin() import aureon
direct = None try: dist = importlib.metadata.distribution("aureon") raw = dist.read_text("direct_url.json") direct = json.loads(raw) if raw else None except Exception as exc: # noqa: BLE001 - the record should say the pin was not readable direct = {"error": type(exc).__name__} from aureon_public.measurement_stamp import measurement_stamp
return { "api_key_stored": False, "auth": "bearer", "aureon_direct_url": direct, "aureon_file": aureon.__file__, "aureon_source": aureon_source(), "docker": "not installed", "entry": "python -m aureon_public.space", "mcp": importlib.metadata.version("mcp"), "observer_mode": "dry_run", "open": "unset", "python": sys.executable, "require_pin": "1", "runtime": _RUNTIME, **measurement_stamp(), }
async def _run(out_path: Path) -> None: os.environ["AUREON_PUBLIC_REQUIRE_PIN"] = "1" enforce_public_pin() api_key = secrets.token_hex(16) env = _server_env(api_key) entry_check = _entry_check(env) port = _free_port() env["PORT"] = str(port) log_fd, log_name = tempfile.mkstemp(prefix="aureon-public-space-") os.close(log_fd) log_path = Path(log_name) log = log_path.open("w", encoding="utf-8") proc = subprocess.Popen( [sys.executable, "-m", "aureon_public.space"], cwd=str(Path.cwd()), env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True, text=True, ) try: deadline = time.monotonic() + 30 while time.monotonic() < deadline: if proc.poll() is not None: raise RuntimeError(_log_tail(log_path) or f"space entry exited {proc.returncode}") if _port_open(port): break time.sleep(0.1) else: raise TimeoutError(_log_tail(log_path) or "space entry did not listen") url = f"http://{_BIND_HOST}:{port}/mcp" body = await _session(url, api_key) record = { "entry_check": entry_check, "environment": _environment(), "streamable_http": {"host": _BIND_HOST, "port": port, "url": url, **body}, } if api_key in json.dumps(record): raise RuntimeError("the bearer token was written into the record") out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") finally: log.close() _stop(proc) log_path.unlink(missing_ok=True)
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-space-measure") parser.add_argument( "--out", type=Path, default=paths.repo_root() / "measured" / "aureon_public_space.json", ) args = parser.parse_args(argv) asyncio.run(_run(args.out))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Stdio session for the remaining stage-1 tools. Writes raw JSON.
Run from measured/aureon_public_stage1_run.sh. Do not hand-edit the output."""
from __future__ import annotations
import argparseimport asyncioimport importlib.metadataimport inspectimport jsonimport osimport sysfrom pathlib import Pathfrom typing import Any
from mcp import ClientSession, StdioServerParametersfrom mcp.client.stdio import stdio_client
from aureon_public import pathsfrom aureon_public.guard_loader import apply_space_guardfrom aureon_public.stage1_rest import TOOLS
def _text_content(result: Any) -> str: parts = [] for block in result.content: text = getattr(block, "text", None) if text is not None: parts.append(text) return "\n".join(parts)
def _defaults(fn: Any) -> dict[str, Any]: signature = inspect.signature(fn) arguments = {} for name, param in signature.parameters.items(): if param.default is inspect.Parameter.empty: continue if param.default == "": continue arguments[name] = param.default return arguments
def _environment() -> dict[str, Any]: apply_space_guard() import aureon
direct = None try: dist = importlib.metadata.distribution("aureon") raw = dist.read_text("direct_url.json") direct = json.loads(raw) if raw else None except Exception as exc: # noqa: BLE001 - the record should say the pin was not readable direct = {"error": type(exc).__name__} from aureon_public.measurement_stamp import measurement_stamp
return { "aureon_direct_url": direct, "aureon_file": aureon.__file__, "python": sys.executable, **measurement_stamp(), }
async def _session(out_path: Path) -> dict[str, Any]: env = { "PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", ""), "PYTHONUNBUFFERED": "1", } params = StdioServerParameters( command=sys.executable, args=["-m", "aureon_public"], env=env, cwd=str(Path.cwd()), ) async with stdio_client(params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() calls = {} for fn in TOOLS: arguments = _defaults(fn) result = await session.call_tool(fn.__name__, arguments) text = _text_content(result) record_call = { "arguments": arguments, "isError": result.isError, "text": text, } try: body = json.loads(text) except json.JSONDecodeError: body = None if isinstance(body, dict) and body.get("input_source"): record_call["input_note"] = body.get("input_note") record_call["input_source"] = body["input_source"] calls[fn.__name__] = record_call record = {"calls": calls, "environment": _environment()} out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8") return record
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-stage1-measure") parser.add_argument( "--out", type=Path, default=paths.repo_root() / "measured" / "aureon_public_stage1.json", ) args = parser.parse_args(argv) asyncio.run(_session(args.out))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531"""Remaining stage-1 packages: generated and swarm.
Calls go through dispatch. Organism is not a stage-1 tool. Stage 2 is notopened. Defaults are labelled. No queen, miner, swarm_motion, brain, ornetwork client is imported here."""
from __future__ import annotations
import jsonfrom typing import Any
from aureon_public.alignment_layer import label_resultfrom aureon_public.body import _unavailable, dispatchfrom aureon_public.quiet import quietfrom aureon_public.tools import _finite
# Constants copied from tests/test_druidic_council.py._COUNCIL_SOURCE = "tests/test_druidic_council.py"_NOW = 1_786_473_600.0_PROPOSAL = "a" * 64_PROMPT = "b" * 64_HNC = "hnc:live_field:receipt-a"_AURIS = "auris:cosmic_state:receipt-b"
# Vectors copied from tests/test_swarm_fleadh.py::test_steer_flow_preserves_step_length_exactly._STEER_U = [1.0, 2.0, 0.0, 0.5]_STEER_GRAD = [0.3, -0.8, 0.4, 0.0]
# Full-strength inputs from tests/generated/test_harmonic_nexus_score_model.py._FULL_INPUTS = { "source_strength": 1.0, "coherence_agreement": 1.0, "repeatability": 1.0, "friction_feasibility": 1.0, "contradiction_handling": 1.0,}_BOUNDS_INPUTS = { "source_strength": 2.0, "coherence_agreement": -1.0, "repeatability": 0.5, "friction_feasibility": 0.5, "contradiction_handling": 0.5,}_BREAKDOWN_INPUTS = { "source_strength": 1.0, "coherence_agreement": 0.5, "repeatability": 0.25, "friction_feasibility": 0.5, "contradiction_handling": 1.0,}
_EXAMPLE = "Fixed example arguments, not a reading."_DEFAULTS = "These fields are the dataclass defaults, not a reading."
def _call(module: str, symbol: str, arguments: dict[str, Any]) -> str: return dispatch(module, symbol, arguments, server="public")
def _seat_arguments() -> dict[str, Any]: return { "seat": "seer", "agent_id": "agent-seer", "decision": "ACCEPT", "reason": "seer verified its discipline boundary", "gamma": 0.90, "proposal_digest": _PROPOSAL, "prompt_digest": _PROMPT, "hnc_receipt_id": _HNC, "auris_receipt_id": _AURIS, "auris_node_receipt_id": "auris:node:seer:receipt", "source_timestamp": _NOW - 5.0, "derived_at": _NOW - 1.0, }
@quietdef generated_default_inputs() -> str: """build_default_inputs. Provenance: cited.
The defaults are the function's own conservative inputs from SOURCE_COUNT. They are not a live market reading and not a lighthouse reading.
Args: none: This tool takes no inputs. Label: cited, build_default_inputs. """
return label_result( _call( "generated/research_cinema/harmonic_nexus_score_model.py", "build_default_inputs", {}, ), "tests/generated/test_harmonic_nexus_score_model.py::test_default_inputs_are_conservative", "Fixed fixture from that test. The function builds its own defaults. Not a live reading.", )
@quietdef generated_normalized() -> str: """HarmonicNexusScoreInputs.normalized on the bounds fixture. Provenance: cited.
The five numbers are tests/generated/test_harmonic_nexus_score_model.py test_harmonic_nexus_score_bounds_inputs. Not a live reading.
Args: none: The fixture is fixed. Label: cited. """
return label_result( _call( "generated/research_cinema/harmonic_nexus_score_model.py", "HarmonicNexusScoreInputs.normalized", {"init": _BOUNDS_INPUTS}, ), "tests/generated/test_harmonic_nexus_score_model.py::test_harmonic_nexus_score_bounds_inputs", "Fixed fixture from that test. Not a live reading.", )
@quietdef generated_score() -> str: """harmonic_nexus_score on the full-strength fixture. Provenance: cited.
The five ones are test_harmonic_nexus_score_full_strength_is_100. The score is that fixture, not a live reading. It does not score any Aureon or HNC claim, so 100.0 cannot be quoted as evidence.
Args: none: The fixture is fixed. Label: cited. """
return label_result( _call( "generated/research_cinema/harmonic_nexus_score_model.py", "harmonic_nexus_score", {"inputs": _FULL_INPUTS}, ), "tests/generated/test_harmonic_nexus_score_model.py::test_harmonic_nexus_score_full_strength_is_100", ( "Fixed fixture from that test. Not a live reading. " "This does not score any Aureon or HNC claim, so 100.0 cannot be quoted as evidence." ), )
@quietdef generated_breakdown() -> str: """score_breakdown on the breakdown fixture. Provenance: cited.
The inputs are test_harmonic_nexus_breakdown_matches_score. Not a live reading.
Args: none: The fixture is fixed. Label: cited. """
return label_result( _call( "generated/research_cinema/harmonic_nexus_score_model.py", "score_breakdown", {"inputs": _BREAKDOWN_INPUTS}, ), "tests/generated/test_harmonic_nexus_score_model.py::test_harmonic_nexus_breakdown_matches_score", "Fixed fixture from that test. Not a live reading.", )
@quietdef swarm_voice_read(gamma: float = 0.80) -> str: """voice_for_gamma. Provenance: cited.
The default 0.80 is the ACTIVE row in tests/test_druidic_council.py test_voice_bands_use_raw_gamma_without_invented_multiplier. It is not a live lighthouse reading.
Args: gamma: Coherence passed to voice_for_gamma. Label: cited. """
number = _finite(gamma) if number is None: return _unavailable("gamma is missing") text = _call("swarm/druidic_council.py", "voice_for_gamma", {"gamma": number}) if number == 0.80: return label_result( text, "tests/test_druidic_council.py::test_voice_bands_use_raw_gamma_without_invented_multiplier", "Fixed fixture from that test. Not a live lighthouse reading.", ) return text
@quietdef swarm_steer_flow(u_json: str = "", grad_json: str = "") -> str: """steer_flow. Provenance: cited.
The default vectors are tests/test_swarm_fleadh.py test_steer_flow_preserves_step_length_exactly. Not a live crowd reading.
Args: u_json: JSON list. Empty uses the test vector. Label: cited. grad_json: JSON list. Empty uses the test gradient. Label: cited. """
raw_u = u_json.strip() or json.dumps(_STEER_U) raw_grad = grad_json.strip() or json.dumps(_STEER_GRAD) try: flow = json.loads(raw_u) grad = json.loads(raw_grad) except json.JSONDecodeError: return _unavailable("arguments are not JSON") if not isinstance(flow, list) or not isinstance(grad, list): return _unavailable("u and grad must be lists") text = _call("swarm/fleadh.py", "steer_flow", {"u": flow, "grad": grad}) if flow == _STEER_U and grad == _STEER_GRAD: return label_result( text, "tests/test_swarm_fleadh.py::test_steer_flow_preserves_step_length_exactly", "Fixed fixture from that test. Not a live reading.", ) return text
@quietdef swarm_build_seat() -> str: """build_seat_receipt for the seer seat in the council test. Provenance: cited.
The arguments are the seer row of _seat_receipts in tests/test_druidic_council.py. The receipt is that fixture, not a live council.
Args: none: The fixture is fixed. Label: cited. """
return label_result( _call("swarm/druidic_council.py", "build_seat_receipt", _seat_arguments()), _COUNCIL_SOURCE, "Fixed fixture from tests/test_druidic_council.py. Not a live council.", )
def _agent_init() -> dict[str, Any]: return {"agent_id": "stage1", "role": "scout", "actions": ["hold"]}
@quietdef swarm_agent_substrate() -> str: """SwarmAgent.substrate at t 0. Provenance: cited.
The agent id, role, and action are fixed example arguments. t is 0. The value is that call, not a reading.
Args: none: The example is fixed. Label: cited. """
return label_result( _call( "swarm/agent.py", "SwarmAgent.substrate", {"init": _agent_init(), "t": 0.0}, ), "aureon.swarm.agent.SwarmAgent.substrate", _EXAMPLE, )
@quietdef swarm_agent_to_dict() -> str: """SwarmAgent.to_dict on the fixed example agent. Provenance: cited.
Args: none: The example is fixed. Label: cited. """
return label_result( _call("swarm/agent.py", "SwarmAgent.to_dict", {"init": _agent_init()}), "aureon.swarm.agent.SwarmAgent", _EXAMPLE, )
@quietdef swarm_agent_propose() -> str: """SwarmAgent.propose with one fixed action vector. Provenance: cited.
cluster_gamma is omitted as null, which the method treats as not yet measured. Not a live coherence reading.
Args: none: The example is fixed. Label: cited. """
return label_result( _call( "swarm/agent.py", "SwarmAgent.propose", { "init": _agent_init(), "action_vectors": {"hold": [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}, "cluster_gamma": None, }, ), "aureon.swarm.agent.SwarmAgent.propose", _EXAMPLE + " cluster_gamma null means the method's own not-yet-measured branch.", )
@quietdef swarm_coherence_gamma() -> str: """ClusterCoherence.gamma on an empty window. Provenance: cited.
The window 8 is the class default. gamma is None while the window is warming. That None is the method's own result, not a reading.
Args: none: The example is fixed. Label: cited. """
return label_result( _call( "swarm/coherence.py", "ClusterCoherence.gamma", {"init": {"window": 8}}, ), "aureon.swarm.coherence.ClusterCoherence", "Window 8 is the class default. An empty window is not a reading.", )
@quietdef swarm_coherence_to_dict() -> str: """ClusterCoherence.to_dict on an empty window. Provenance: cited.
Args: none: The example is fixed. Label: cited. """
return label_result( _call("swarm/coherence.py", "ClusterCoherence.to_dict", {"init": {"window": 8}}), "aureon.swarm.coherence.ClusterCoherence", "Window 8 is the class default. Not a reading.", )
@quietdef swarm_echo() -> str: """CausalEchoBus.echo on an empty bus. Provenance: cited.
tau 3 is the class default. step 0 has nothing stored, so the method returns None. That None is a dark echo, not a reading.
Args: none: The example is fixed. Label: cited. """
return label_result( _call("swarm/memory_bus.py", "CausalEchoBus.echo", {"init": {"tau": 3}, "step": 0}), "aureon.swarm.memory_bus.CausalEchoBus.echo", "tau 3 is the class default. An empty bus is not a reading.", )
@quietdef swarm_echo_to_dict() -> str: """CausalEchoBus.to_dict on an empty bus. Provenance: cited.
Args: none: The example is fixed. Label: cited. """
return label_result( _call("swarm/memory_bus.py", "CausalEchoBus.to_dict", {"init": {"tau": 3}}), "aureon.swarm.memory_bus.CausalEchoBus", "tau 3 is the class default. Not a reading.", )
@quietdef swarm_steer_field() -> str: """SteeringField.steer with no heading. Provenance: cited.
resistance 0.5 is the class default. heading null is the method's no-heading branch. Not a live path.
Args: none: The example is fixed. Label: cited. """
return label_result( _call( "swarm/steering.py", "SteeringField.steer", {"init": {"resistance": 0.5}, "proposal": [1.0, 0.0, 0.0], "heading": None}, ), "aureon.swarm.steering.SteeringField.steer", "resistance 0.5 is the class default. heading null is a fixed example, not a reading.", )
@quietdef swarm_seat_to_dict() -> str: """SeatReceipt.to_dict on a fixed example payload. Provenance: cited.
The payload is one field, not a validated council receipt.
Args: none: The example is fixed. Label: cited. """
return label_result( _call( "swarm/druidic_council.py", "SeatReceipt.to_dict", {"init": {"payload": {"seat": "seer"}}}, ), "aureon.swarm.druidic_council.SeatReceipt", "Fixed example payload. Not a council reading.", )
@quietdef swarm_council_to_dict() -> str: """CouncilReceipt.to_dict on a fixed example payload. Provenance: cited.
The payload is one field, not a validated council receipt.
Args: none: The example is fixed. Label: cited. """
return label_result( _call( "swarm/druidic_council.py", "CouncilReceipt.to_dict", {"init": {"payload": {"schema": "example"}}}, ), "aureon.swarm.druidic_council.CouncilReceipt", "Fixed example payload. Not a council reading.", )
@quietdef swarm_actualization_to_dict() -> str: """Actualization.to_dict on explicit empty fields. Provenance: cited.
actualized false, action null, and canonical_status canonical_dark are fixed example arguments. They are not a gate reading.
Args: none: The example is fixed. Label: cited. """
return label_result( _call( "swarm/queen_gate.py", "Actualization.to_dict", { "init": { "actualized": False, "action": None, "gamma_cluster": None, "gamma_effective": None, "canonical_status": "canonical_dark", } }, ), "aureon.swarm.queen_gate.Actualization", "Fixed example fields. canonical_dark is the gate's own dark-field word. Not a reading.", )
# Copied from tests/test_swarm_hive.py::test_agent_keeps_a_normalized_soft_simplex._HIVE_ACTIONS = ["hold", "advance", "retreat"]_HIVE_CONTEXT = [0.4, 0.2, -0.1, 0.3, 0.0, 0.1, -0.2, 0.05]_HIVE_SOURCE = "tests/test_swarm_hive.py::test_agent_keeps_a_normalized_soft_simplex"
@quietdef swarm_agent_update() -> str: """SwarmAgent.update on the hive test's first context.
The agent id, role, actions, and CONTEXT are that test. The cluster is empty and the echo is absent, as the loop starts. The function returns None.
Args: none: The fixture is fixed. Label: cited. """
return label_result( _call( "swarm/agent.py", "SwarmAgent.update", { "cluster_states": [], "context": _HIVE_CONTEXT, "echo": None, "init": { "actions": _HIVE_ACTIONS, "agent_id": "a1", "role": "research", }, }, ), _HIVE_SOURCE, "The first update in that test. Empty cluster and no echo. The return is None.", )
TOOLS: list[Any] = [ generated_default_inputs, generated_normalized, generated_score, generated_breakdown, swarm_voice_read, swarm_steer_flow, swarm_build_seat, swarm_agent_update, swarm_agent_substrate, swarm_agent_to_dict, swarm_agent_propose, swarm_coherence_gamma, swarm_coherence_to_dict, swarm_echo, swarm_echo_to_dict, swarm_steer_field, swarm_seat_to_dict, swarm_council_to_dict, swarm_actualization_to_dict,]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306"""Real stage-2 call arguments. Values are copied from the repo, not invented.
A fixture name is resolved only inside a sweep worker. The public servernever sets ``AUREON_PUBLIC_SWEEP``, so a client cannot ask for a fixture."""
from __future__ import annotations
import csvimport jsonfrom pathlib import Pathfrom typing import Any
from aureon_public.paths import repo_root
# Copied from tests/test_phenolic_bridge.py.PHENOLIC_ANALYSIS: dict[str, Any] = { "valid": True, "alpha": 0.05, "source_path": "x.csv", "formats": ["native"], "controls": {"positive": {"passed": True}, "negative": {"passed": True}}, "compounds": { "caffeic acid": { "test_A_p": 0.003, "test_B_p": 0.7, "separable": False, "n_peaks": 59, "sources": ["doi:cga"], }, "luteolin": { "test_A_p": 0.005, "test_B_p": 0.6, "separable": True, "n_peaks": 21, "sources": ["doi:lut", "COMPUTED GFN2-xTB (theoretical, non-experimental)"], }, "apigenin": { "test_A_p": 0.8, "test_B_p": 0.9, "separable": False, "n_peaks": 5, "sources": ["doi:api"], }, },}
# reports/measured/organism.json holds baseline 6 and predicted 7 for the tick# field, and organism_proof.TICKS is 8. The history before the held-out tick is# 0 through 6.TICK_HISTORY = [0, 1, 2, 3, 4, 5, 6]
DE440_SOURCE = "data/de440_timeseries.csv"DE440_LIMIT = 80REPORTS = { "auris": "reports/measured/auris_nodes.json", "brain": "reports/measured/brain.json", "organism": "reports/measured/organism.json", "qgita": "reports/measured/qgita_snr.json", "self_coder": "reports/measured/self_coder.json",}
# Reachable entry points the sweep calls, and the public server does not# register, because the worker cannot be given the real object as JSON.NOT_A_TOOL: dict[tuple[str, str], str] = { ("decoders/book_of_ur.py", "test_phi_resonance_me"): ( "The argument is a SumerianMe. That class is not on the constructor " "allowlist, so the public server does not build one. The sweep uses " "the catalog entry ENSHIP from aureon/decoders/book_of_ur.py." ), ("observer/momentum.py", "set_momentum_tracker"): ( "The argument is a MomentumTracker. The class is not on the constructor " "allowlist. The sweep constructs an empty tracker inside the worker." ), ("observer/predictor.py", "make_predictor"): ( "The argument is a HarmonicObserver. The class is not on the constructor " "allowlist. The sweep uses the construction in " "tests/observer/test_predictor_contract.py: trace_interval_s 1.0 and " "publish_to_bus false." ), ("observer/wave_predictor.py", "set_wave_predictor"): ( "The argument is a WavePredictor. The class is not on the constructor " "allowlist. The sweep constructs an empty predictor inside the worker." ), ("observer/wave_predictor.py", "make_predictor"): ( "The argument is a WavePredictor. The class is not on the constructor " "allowlist. The sweep constructs an empty predictor inside the worker." ),}
def de440_lambda_prefix(limit: int = DE440_LIMIT) -> list[float]: """The first Lambda values of the committed DE440 file."""
path = repo_root() / DE440_SOURCE values: list[float] = [] with path.open(newline="", encoding="utf-8") as handle: for row in csv.DictReader(handle): values.append(float(row["Lambda"])) if len(values) >= limit: break return values
def load_report(relative: str) -> dict[str, Any]: """One committed measured report. The file is read, not rewritten."""
path = repo_root() / relative loaded = json.loads(path.read_text(encoding="utf-8")) if not isinstance(loaded, dict): raise TypeError(relative) return loaded
def attempts_for(module: str, symbol: str) -> list[dict[str, Any]]: """Argument calls for one stage-2 entry point. Empty when no-arg is the call."""
key = (module, symbol) table: dict[tuple[str, str], list[dict[str, Any]]] = { ("cognition/phenolic_bridge.py", "summarize_patterns"): [ { "arguments": {"analysis": PHENOLIC_ANALYSIS}, "label": "phenolic_test_fixture", "note": "Fixture dict from the phenolic bridge test. Not a laboratory result.", "source": "tests/test_phenolic_bridge.py", } ], ("decoders/book_of_ur.py", "test_phi_resonance_me"): [ { "fixture": "sumerian_enship", "label": "enship", "note": "First foundation me in the module catalog.", "source": "aureon/decoders/book_of_ur.py", } ], ("evaluation/auris_node_eval.py", "render_auris_markdown"): [_report_attempt("auris")], ("evaluation/brain_proof.py", "render_brain_markdown"): [_report_attempt("brain")], ("evaluation/measured_proof.py", "self_coder_report"): [ { "fixture": "repo_root_path", "label": "checkout_root", "note": "The checkout path. This calls the harness.", "source": "aureon/evaluation/measured_proof.py", } ], ("evaluation/measured_proof.py", "render_self_coder_markdown"): [_report_attempt("self_coder")], ("evaluation/organism_proof.py", "predict_next"): [ { "arguments": {"values": TICK_HISTORY}, "label": "tick_history", "note": "Ticks 0 through 6. The committed organism report's tick baseline is 6 and the held-out tick is 7.", "source": "reports/measured/organism.json", } ], ("evaluation/organism_proof.py", "render_organism_markdown"): [_report_attempt("organism")], ("evaluation/qgita_snr_benchmark.py", "render_qgita_markdown"): [_report_attempt("qgita")], ("gates/benchmark.py", "build_report"): [ { "arguments": {"checks": []}, "label": "empty_checks", "note": "The function's own comment says an empty check list must not pass. The panel is not convened.", "source": "aureon/gates/benchmark.py", } ], ("gates/panel.py", "ungrounded_nodes"): [ { "arguments": {"grounded_slices": []}, "label": "empty_grounded_set", "note": "The empty set in tests/gates/test_switchboard.py. Nothing was measured.", "source": "tests/gates/test_switchboard.py", } ], ("gates/switchboard.py", "is_human_held"): [ { "arguments": {"action": "draft"}, "label": "draft", "note": "An ordinary action in the switchboard test.", "source": "tests/gates/test_switchboard.py", }, { "arguments": {"action": "submit"}, "label": "submit", "note": "A human-held verb in the switchboard test.", "source": "tests/gates/test_switchboard.py", }, ], ("observer/fitter.py", "fit_tanh"): [_de440_attempt()], ("observer/fitter.py", "fit_full"): [_de440_attempt()], ("observer/live_data_policy.py", "fallback_marker"): [ { "arguments": {"source": "b70_probe", "when": 123.0}, "label": "b70_probe", "note": "The marker call in tests/benchmarks/benchmark_aureon_scope.py. when is 123.0 in that test.", "source": "tests/benchmarks/benchmark_aureon_scope.py", } ], ("observer/momentum.py", "set_momentum_tracker"): [ { "fixture": "empty_momentum_tracker", "label": "empty_tracker", "note": "MomentumTracker() takes no readings.", "source": "aureon/observer/momentum.py", } ], ("observer/predictor.py", "make_predictor"): [ { "fixture": "empty_harmonic_observer", "label": "unpublished_observer", "note": "The test constructs the observer with publish_to_bus false.", "source": "tests/observer/test_predictor_contract.py", } ], ("observer/real_data_contract.py", "make_test_fixture_metric"): [ { "arguments": {"name": "fixture.metric", "value": 1}, "label": "fixture_metric", "note": "The name and value in tests/test_real_data_contract.py. The envelope is a test fixture.", "source": "tests/test_real_data_contract.py", } ], ("observer/real_data_contract.py", "summarize_truth_status"): [ { "arguments": {"metrics": [{"truth_status": "test_fixture"}]}, "label": "one_test_fixture_status", "note": "truth_status test_fixture is the status make_test_fixture_metric writes. This is one status, not a census of sources.", "source": "aureon/observer/real_data_contract.py", } ], ("observer/wave_predictor.py", "set_wave_predictor"): [ { "fixture": "empty_wave_for_set", "label": "empty_predictor", "note": "WavePredictor() takes no trace.", "source": "aureon/observer/wave_predictor.py", } ], ("observer/wave_predictor.py", "make_predictor"): [ { "fixture": "empty_wave_for_make", "label": "empty_predictor", "note": "WavePredictor() takes no trace.", "source": "aureon/observer/wave_predictor.py", } ], ("s51/aureon_51_compound.py", "summarize_compounding"): [ { "arguments": {"receipts": []}, "label": "no_receipts", "note": "The module calls summarize_compounding with an empty list when run as a script. The result is no_data. No trade is added.", "source": "aureon/s51/aureon_51_compound.py", } ], } return table.get(key, [])
def _report_attempt(name: str) -> dict[str, Any]: relative = REPORTS[name] return { "fixture": f"report:{relative}", "label": relative, "note": "The committed measured report. This call formats that file. It does not rerun the proof.", "source": relative, }
def _de440_attempt() -> dict[str, Any]: return { "fixture": "de440_lambda_prefix", "label": "de440_lambda_prefix", "note": f"The first {DE440_LIMIT} Lambda values of {DE440_SOURCE}. A curve fit of that prefix, not a live trace.", "source": DE440_SOURCE, }
def resolve_fixture(name: str) -> dict[str, Any]: """Build one real argument inside the sweep worker."""
if name == "repo_root_path": return {"root": repo_root()} if name == "sumerian_enship": from aureon.decoders.book_of_ur import _ME_CATALOG
me = next(item for item in _ME_CATALOG if item.id == "ENSHIP") return {"me": me} if name == "empty_harmonic_observer": from aureon.observer.harmonic_observer import HarmonicObserver
return {"observer": HarmonicObserver(trace_interval_s=1.0, publish_to_bus=False)} if name == "empty_momentum_tracker": from aureon.observer.momentum import MomentumTracker
return {"t": MomentumTracker()} if name == "empty_wave_for_set": from aureon.observer.wave_predictor import WavePredictor
return {"p": WavePredictor()} if name == "empty_wave_for_make": from aureon.observer.wave_predictor import WavePredictor
return {"predictor": WavePredictor()} if name == "de440_lambda_prefix": return {"lambda_values": de440_lambda_prefix()} if name.startswith("report:"): return {"report": load_report(name.split(":", 1)[1])} raise KeyError(name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226"""Sweep plan-stage-2 modules in isolated processes with sockets blocked.
A module is refused when its import loads ``inhouse_ai``, ``ollama_config``,or an HTTP client, or when the import opens a connection, starts a process,or writes outside the sandbox. The public server reads the committed recordand refuses those modules before a worker starts.
bash measured/aureon_public_stage2_sweep.sh"""
from __future__ import annotations
import argparseimport jsonimport osimport subprocessimport sysfrom collections import defaultdictfrom pathlib import Pathfrom typing import Any
ADAPTER_MARKERS = ("inhouse_ai", "ollama_config")# urllib.parse is not a client. urllib.request and http.client are.HTTP_ROOTS = frozenset( {"requests", "httpx", "urllib3", "aiohttp", "websocket", "websockets"})HTTP_PREFIXES = ( "http.client", "urllib.request", "urllib.response",)RECORD_NAME = "aureon_public_stage2_imports.json"
def is_http_client(name: str) -> bool: """True when ``name`` is an HTTP client module or a submodule of one."""
root = name.split(".", 1)[0] if root in HTTP_ROOTS: return True return any(name == prefix or name.startswith(prefix + ".") for prefix in HTTP_PREFIXES)
def import_refusal( bad: list[str], socket_attempts: list[str], processes: list[str] | None = None, writes: list[str] | None = None,) -> str | None: """Why an import is refused. None when the import is clean."""
if socket_attempts or any( any(marker in name for marker in ADAPTER_MARKERS) or is_http_client(name) for name in bad ): return "module import loads an adapter or http client" if processes: return "module import starts a process" if writes: return "module import writes outside the sandbox" return None
def import_is_refused( bad: list[str], socket_attempts: list[str], processes: list[str] | None = None, writes: list[str] | None = None,) -> bool: """The rule the measured record and body_call share."""
return import_refusal(bad, socket_attempts, processes, writes) is not None
def _dotted(module: str) -> str: stem = module[:-3] if module.endswith(".py") else module return "aureon." + stem.replace("/", ".")
def child_main(module: str) -> None: """Import one module. Stdout is one JSON object."""
from aureon_public.sweep_guard import declare_sandbox, install_sweep_guard, snapshot
os.environ["AUREON_PUBLIC_SWEEP"] = "1" declare_sandbox() install_sweep_guard() error = None try: from aureon_public.call_worker import _load
_load(_dotted(module), module) except Exception as exc: error = f"{type(exc).__name__}: {exc}"[:240] import sys as _sys
bad = sorted( name for name in _sys.modules if any(marker in name for marker in ADAPTER_MARKERS) or is_http_client(name) ) snap = snapshot() json.dump( { "bad": bad, "error": error, "process": snap["processes"], "socket": snap["sockets"], "writes": snap["writes"], }, sys.stdout, )
def stage2_modules() -> list[tuple[str, str]]: """Public function and method modules in plan stage 2."""
from aureon_public.body import _inventory from aureon_public.coverage_plan import safety_category, stage_for
rows, _index = _inventory() categories: dict[str, set[str]] = defaultdict(set) for row in rows: categories[str(row["package"])].add(safety_category(str(row.get("safety") or ""))) found: dict[str, str] = {} for row in rows: package = str(row["package"]) if stage_for(package, categories[package]) != 2: continue if row["server"] != "public" or row["kind"] not in {"function", "method"}: continue found.setdefault(str(row["module"]), package) return sorted(found.items())
def _one(module: str, timeout: float) -> dict[str, Any]: completed = subprocess.run( [sys.executable, "-m", "aureon_public.stage2_import_sweep", "--module", module], cwd=os.environ.get("TMPDIR") or "/tmp", capture_output=True, text=True, timeout=timeout, check=False, ) if completed.returncode != 0 and not completed.stdout.strip(): return { "bad": [], "error": f"sweep exited {completed.returncode}", "socket": [], "stderr": completed.stderr[-400:], } try: payload = json.loads(completed.stdout) except json.JSONDecodeError: return { "bad": [], "error": "sweep result was not JSON", "socket": [], "stderr": (completed.stderr or completed.stdout)[-400:], } if not isinstance(payload, dict): return {"bad": [], "error": "sweep result was not an object", "socket": []} return payload
def build_record(timeout: float) -> dict[str, Any]: from aureon_public.guard_loader import aureon_source from aureon_public.measurement_stamp import measurement_stamp from aureon_public.sweep_layout import layout_record
source = aureon_source() stamp = measurement_stamp() modules = [] for module, package in stage2_modules(): print(module, file=sys.stderr) payload = _one(module, timeout) bad = [str(item) for item in payload.get("bad") or []] sockets = [str(item) for item in payload.get("socket") or []] processes = [str(item) for item in payload.get("process") or []] writes = [str(item) for item in payload.get("writes") or []] refusal = import_refusal(bad, sockets, processes, writes) modules.append( { "bad": bad, "error": payload.get("error"), "module": module, "package": package, "process": processes, "refusal": refusal, "refused": refusal is not None, "socket": bool(sockets), "writes": writes, } ) return { "adapters": list(ADAPTER_MARKERS), "aureon_source": source, "http_clients": sorted(HTTP_ROOTS | set(HTTP_PREFIXES)), "layout": layout_record(), "modules": modules, "processes": "blocked", "sockets": "blocked", "writes": "outside sandbox blocked", **stamp, }
def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="aureon-public-stage2-import-sweep") parser.add_argument("--module", help="import one module and print JSON") parser.add_argument("--out", type=Path) parser.add_argument("--timeout", type=float, default=45.0) args = parser.parse_args(argv) if args.module: child_main(args.module) return record = build_record(args.timeout) text = json.dumps(record, indent=2, sort_keys=True) + "\n" if args.out is None: sys.stdout.write(text) return args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(text, encoding="utf-8")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782"""Stage-2 tools. Each call goes through dispatch. Inputs are files or tests in the repo.
No queen, miner, swarm_motion, in-house adapter, or network client is importedhere. A number in the result is the function's result on the named input."""
from __future__ import annotations
from typing import Any
from aureon_public.alignment_layer import label_resultfrom aureon_public.body import _unavailable, dispatchfrom aureon_public.quiet import quietfrom aureon_public.stage2_arguments import ( DE440_SOURCE, PHENOLIC_ANALYSIS, REPORTS, TICK_HISTORY, de440_lambda_prefix, load_report,)
_MODE = "aureon/observer/production_mode.py"# The public worker sets AUREON_OBSERVER_MODE=dry_run. The code default is a# cited source line and is not the value these tools return._MODE_SOURCE = "aureon/observer/production_mode.py"_MODE_CITED = ( "The worker sets AUREON_OBSERVER_MODE=dry_run. " "Cited source, aureon/observer/production_mode.py: `DEFAULT_MODE = ObserverMode.LIVE`. " "That line is not this result.")
def _call(module: str, symbol: str, arguments: dict[str, Any]) -> str: return dispatch(module, symbol, arguments, server="public", timeout=30.0)
@quietdef stage2_summarize_patterns() -> str: """Distil the phenolic bridge test's analysis dict.
The dict is tests/test_phenolic_bridge.py. It is not a laboratory result from this server. The result names separable compounds and provenance counts in that dict.
Args: none: The fixture is fixed. Label: cited. """
return label_result( _call( "cognition/phenolic_bridge.py", "summarize_patterns", {"analysis": PHENOLIC_ANALYSIS}, ), "tests/test_phenolic_bridge.py", "Fixture dict from that test. Not a laboratory result.", )
@quietdef stage2_sumerian_decoder() -> str: """Build the Book of Ur decoder from the me catalog in that file.
The catalog is the module's own table. This is not a live geographic reading.
Args: none: The catalog is in the module. Label: cited. """
return label_result( _call("decoders/book_of_ur.py", "get_sumerian_decoder", {}), "aureon/decoders/book_of_ur.py", "The decoder is built from the me catalog in that file.", )
@quietdef stage2_sumerian_vector() -> str: """Return the bearing the Sumerian decoder computes from the Ur coordinates in that file.
Args: none: The coordinates are in the module. Label: cited. """
return label_result( _call("decoders/book_of_ur.py", "get_sumerian_geographic_vector", {}), "aureon/decoders/book_of_ur.py", "The vector is computed from the coordinates in that file.", )
@quietdef stage2_iching_decoder() -> str: """Build the I Ching decoder from the hexagram table in that file.
Args: none: The table is in the module. Label: cited. """
return label_result( _call("decoders/iching_decoder.py", "get_iching_decoder", {}), "aureon/decoders/iching_decoder.py", "The decoder is built from the hexagram table in that file.", )
@quietdef stage2_iching_vector() -> str: """Return the geographic vector the I Ching decoder computes from its own table.
Args: none: The table is in the module. Label: cited. """
return label_result( _call("decoders/iching_decoder.py", "get_iching_geographic_vector", {}), "aureon/decoders/iching_decoder.py", "The vector is computed from the table in that file.", )
def _render(name: str, module: str, symbol: str) -> str: relative = REPORTS[name] try: report = load_report(relative) except (OSError, TypeError, ValueError) as exc: return _unavailable(f"{relative} could not be read: {exc}") return label_result( _call(module, symbol, {"report": report}), relative, "The committed measured report. This formats that file. It does not rerun the proof.", )
@quietdef stage2_render_auris() -> str: """Format the committed Auris report as markdown.
The numbers are reports/measured/auris_nodes.json. This does not re-evaluate the nodes.
Args: none: The file is fixed. Label: cited. """
return _render("auris", "evaluation/auris_node_eval.py", "render_auris_markdown")
@quietdef stage2_render_brain() -> str: """Format the committed brain report as markdown.
The numbers are reports/measured/brain.json. This does not rerun the brain proof.
Args: none: The file is fixed. Label: cited. """
return _render("brain", "evaluation/brain_proof.py", "render_brain_markdown")
@quietdef stage2_render_self_coder() -> str: """Format the committed self-coder report as markdown.
The numbers are reports/measured/self_coder.json. This does not run the harness.
Args: none: The file is fixed. Label: cited. """
return _render("self_coder", "evaluation/measured_proof.py", "render_self_coder_markdown")
@quietdef stage2_render_organism() -> str: """Format the committed organism report as markdown.
The numbers are reports/measured/organism.json. This does not rerun circulation.
Args: none: The file is fixed. Label: cited. """
return _render("organism", "evaluation/organism_proof.py", "render_organism_markdown")
@quietdef stage2_render_qgita() -> str: """Format the committed QGITA report as markdown.
The numbers are reports/measured/qgita_snr.json. This does not rerun the benchmark.
Args: none: The file is fixed. Label: cited. """
return _render("qgita", "evaluation/qgita_snr_benchmark.py", "render_qgita_markdown")
@quietdef stage2_predict_next() -> str: """Apply the pre-registered next-step rule to ticks 0 through 6.
reports/measured/organism.json records tick baseline 6 and held-out tick 7. organism_proof.TICKS is 8. The result is that rule on this series, not a new organism run.
Args: none: The series is fixed. Label: cited. """
return label_result( _call("evaluation/organism_proof.py", "predict_next", {"values": TICK_HISTORY}), "reports/measured/organism.json", "Ticks 0 through 6. The committed report's tick baseline is 6 and the held-out tick is 7.", )
@quietdef stage2_build_report() -> str: """Assemble a gate report from an empty check list.
aureon/gates/benchmark.py says an empty list must not pass. The panel is not convened. The status is the assembler's empty-list result, not a gate measurement.
Args: none: The check list is empty. Label: cited. """
return label_result( _call("gates/benchmark.py", "build_report", {"checks": []}), "aureon/gates/benchmark.py", "Empty check list. The panel is not convened. An empty list must not pass.", )
@quietdef stage2_ungrounded_nodes() -> str: """Name the panel nodes whose slice is absent from an empty grounded set.
The empty set is tests/gates/test_switchboard.py. Tiger and Panda stay in the result because nothing in the organism measures those slices. This is not a live vote.
Args: none: The grounded set is empty. Label: cited. """
return label_result( _call("gates/panel.py", "ungrounded_nodes", {"grounded_slices": []}), "tests/gates/test_switchboard.py", "Empty grounded set from that test. Nothing was measured.", )
@quietdef stage2_is_human_held(action: str = "draft") -> str: """Say whether an action is on the human-held list.
The default draft is an ordinary action in tests/gates/test_switchboard.py and is not held. submit is held. This does not execute the action.
Args: action: The action string passed to is_human_held. Label: cited, the switchboard test. """
if not isinstance(action, str): return _unavailable("action is missing") text = _call("gates/switchboard.py", "is_human_held", {"action": action}) if action == "draft": return label_result( text, "tests/gates/test_switchboard.py", "draft is an ordinary action in that test. It is not human-held.", ) if action == "submit": return label_result( text, "tests/gates/test_switchboard.py", "submit is a human-held verb in that test.", ) return text
def _fit(symbol: str) -> str: try: values = de440_lambda_prefix() except (OSError, KeyError, TypeError, ValueError) as exc: return _unavailable(f"{DE440_SOURCE} could not be read: {exc}") return label_result( _call("observer/fitter.py", symbol, {"lambda_values": values}), DE440_SOURCE, "The first 80 Lambda values of that file. A curve fit of that prefix, not a live trace and not a white-paper coefficient.", )
@quietdef stage2_fit_tanh() -> str: """Fit alpha and g to the first 80 Lambda values in data/de440_timeseries.csv.
This is a curve fit of that prefix. It is not a live trace and it is not the white-paper coefficients.
Args: none: The prefix is fixed. Label: cited. """
return _fit("fit_tanh")
@quietdef stage2_fit_full() -> str: """Fit alpha, g, beta, and tau to the first 80 Lambda values in data/de440_timeseries.csv.
This is a curve fit of that prefix. It is not a live trace and it is not the white-paper coefficients.
Args: none: The prefix is fixed. Label: cited. """
return _fit("fit_full")
@quietdef stage2_simulation_fallback() -> str: """Read whether simulation fallback is allowed in this worker.
The worker does not set AUREON_ALLOW_SIM_FALLBACK. The function's production posture is false. This does not fetch a feed.
Args: none: The worker environment is the public worker environment. Label: cited. """
return label_result( _call("observer/live_data_policy.py", "simulation_fallback_allowed", {}), "aureon/observer/live_data_policy.py", "The worker does not set AUREON_ALLOW_SIM_FALLBACK. False is that function's production posture.", )
@quietdef stage2_fallback_marker() -> str: """Build the fallback audit dict from the benchmark test.
source is b70_probe and when is 123.0, both from tests/benchmarks/benchmark_aureon_scope.py. The dict says the reading is a test fixture.
Args: none: The arguments are the benchmark's. Label: cited. """
return label_result( _call( "observer/live_data_policy.py", "fallback_marker", {"source": "b70_probe", "when": 123.0}, ), "tests/benchmarks/benchmark_aureon_scope.py", "when is 123.0 in that test. The dict is a test-fixture marker, not a live reading.", )
@quietdef stage2_momentum_tracker() -> str: """Return the momentum tracker installed in this worker.
A fresh worker has none, so the result is null. That null is not a momentum reading.
Args: none: No tracker is installed. Label: cited. """
return label_result( _call("observer/momentum.py", "get_momentum_tracker", {}), "aureon/observer/momentum.py", "A fresh worker has no tracker. Null is that fact, not a momentum reading.", )
@quietdef stage2_momentum_predict() -> str: """Ask the momentum predictor with no tracker installed.
The default symbol is BTCUSD, the function's own default. The result is the function's neutral no-data signal. It does not read a price.
Args: none: The symbol default is the function's. Label: cited. """
return label_result( _call("observer/momentum.py", "momentum_predict_fn", {}), "aureon/observer/momentum.py", "No tracker is installed. The neutral signal is the function's no-data result, not a price.", )
def _mode_call(symbol: str) -> str: """Call one production-mode entry point and keep its return value."""
return label_result( _call("observer/production_mode.py", symbol, {}), _MODE_SOURCE, _MODE_CITED, )
@quietdef stage2_observer_mode() -> str: """Return get_mode under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. It is not a broker session and it does not place an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("get_mode")
@quietdef stage2_reload_mode() -> str: """Return reload_mode under AUREON_OBSERVER_MODE=dry_run.
This does not write a file and does not start a process. The result is that function's return.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("reload_mode")
@quietdef stage2_is_live() -> str: """Return is_live under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not place an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("is_live")
@quietdef stage2_is_shadow() -> str: """Return is_shadow under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. It does not describe a broker session.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("is_shadow")
@quietdef stage2_gate_buy_veto() -> str: """Return gate_buy_veto_active under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not place an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("gate_buy_veto_active")
@quietdef stage2_gate_sell_veto() -> str: """Return gate_sell_veto_active under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not place an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("gate_sell_veto_active")
@quietdef stage2_narrow_band() -> str: """Return narrow_band_threshold_active under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not change an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("narrow_band_threshold_active")
@quietdef stage2_kelly_buffer() -> str: """Return kelly_buffer_scaling_active under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not size an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("kelly_buffer_scaling_active")
@quietdef stage2_vote_addition() -> str: """Return vote_addition_active under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not cast a vote.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("vote_addition_active")
@quietdef stage2_phase_veto() -> str: """Return phase_veto_active under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not block an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("phase_veto_active")
@quietdef stage2_volatility_veto() -> str: """Return volatility_veto_active under AUREON_OBSERVER_MODE=dry_run.
The result is that function's return. This call does not block an order.
Args: none: The worker sets AUREON_OBSERVER_MODE=dry_run. Label: cited. """
return _mode_call("volatility_veto_active")
@quietdef stage2_repo_root() -> str: """Resolve the checkout that contains aureon/ and data/.
The public result may keep only the path type. The path is the checkout this process loaded.
Args: none: The start path is the worker's current directory. Label: cited. """
return label_result( _call("observer/real_data_contract.py", "repo_root_from", {}), "aureon/observer/real_data_contract.py", "The function walks parents for an aureon/ and data/ directory.", )
@quietdef stage2_source_registry() -> str: """Read data/real_data_sources.json.
The object is that file. This does not contact the sources.
Args: none: The path is the function's own default. Label: cited. """
return label_result( _call("observer/real_data_contract.py", "load_source_registry", {}), "data/real_data_sources.json", "The committed registry. No source was contacted.", )
@quietdef stage2_source_ids() -> str: """List the source ids in data/real_data_sources.json.
A set does not survive the public result cap as a list. The ids are the keys load_source_registry returns from that file.
Args: none: The path is the function's own default. Label: cited. """
return label_result( _call("observer/real_data_contract.py", "registered_source_ids", {}), "data/real_data_sources.json", "The ids are the keys of that file. A set may be returned as its type name.", )
@quietdef stage2_test_fixture_metric() -> str: """Build the test-fixture metric named in tests/test_real_data_contract.py.
The name is fixture.metric and the value is 1. The envelope's truth status is test_fixture. It is not a live metric.
Args: none: The name and value are the test's. Label: cited. """
return label_result( _call( "observer/real_data_contract.py", "make_test_fixture_metric", {"name": "fixture.metric", "value": 1}, ), "tests/test_real_data_contract.py", "The name and value in that test. truth_status is test_fixture. Not a live metric.", )
@quietdef stage2_truth_counts() -> str: """Count truth statuses in a one-item list whose status is test_fixture.
test_fixture is the status make_test_fixture_metric writes. The count is of that one status, not a census of operational sources.
Args: none: The list is that one status. Label: cited. """
return label_result( _call( "observer/real_data_contract.py", "summarize_truth_status", {"metrics": [{"truth_status": "test_fixture"}]}, ), "aureon/observer/real_data_contract.py", "One test_fixture status, the status make_test_fixture_metric writes. Not a census.", )
@quietdef stage2_wave_predictor() -> str: """Return the wave predictor installed in this worker.
A fresh worker has none, so the result is null. That null is not a forecast.
Args: none: No predictor is installed. Label: cited. """
return label_result( _call("observer/wave_predictor.py", "get_wave_predictor", {}), "aureon/observer/wave_predictor.py", "A fresh worker has no predictor. Null is that fact, not a forecast.", )
@quietdef stage2_wave_predict() -> str: """Ask the wave predictor with none installed.
The default symbol is BTCUSD, the function's own default. The result is the function's neutral not-running signal. It does not forecast a price.
Args: none: The symbol default is the function's. Label: cited. """
return label_result( _call("observer/wave_predictor.py", "wave_predictor_predict", {}), "aureon/observer/wave_predictor.py", "No predictor is installed. The neutral signal is the function's not-running result, not a price.", )
@quietdef stage2_summarize_compounding() -> str: """Summarize an empty closed-trade receipt list.
aureon/s51/aureon_51_compound.py calls this with an empty list when run as a script. The result is no_data. No trade is added.
Args: none: The receipt list is empty. Label: cited. """
return label_result( _call("s51/aureon_51_compound.py", "summarize_compounding", {"receipts": []}), "aureon/s51/aureon_51_compound.py", "Empty receipt list. The module reports no_data. No trade is added.", )
# Entry points these tools call. coverage_plan counts a tested point only when it is still reachable.TESTED: tuple[tuple[str, str], ...] = ( ("cognition/phenolic_bridge.py", "summarize_patterns"), ("decoders/book_of_ur.py", "get_sumerian_decoder"), ("decoders/book_of_ur.py", "get_sumerian_geographic_vector"), ("decoders/iching_decoder.py", "get_iching_decoder"), ("decoders/iching_decoder.py", "get_iching_geographic_vector"), ("evaluation/auris_node_eval.py", "render_auris_markdown"), ("evaluation/brain_proof.py", "render_brain_markdown"), ("evaluation/measured_proof.py", "render_self_coder_markdown"), ("evaluation/organism_proof.py", "predict_next"), ("evaluation/organism_proof.py", "render_organism_markdown"), ("evaluation/qgita_snr_benchmark.py", "render_qgita_markdown"), ("gates/benchmark.py", "build_report"), ("gates/panel.py", "ungrounded_nodes"), ("gates/switchboard.py", "is_human_held"), ("observer/fitter.py", "fit_tanh"), ("observer/fitter.py", "fit_full"), ("observer/live_data_policy.py", "simulation_fallback_allowed"), ("observer/live_data_policy.py", "fallback_marker"), ("observer/momentum.py", "get_momentum_tracker"), ("observer/momentum.py", "momentum_predict_fn"), ("observer/production_mode.py", "get_mode"), ("observer/production_mode.py", "reload_mode"), ("observer/production_mode.py", "is_live"), ("observer/production_mode.py", "is_shadow"), ("observer/production_mode.py", "gate_buy_veto_active"), ("observer/production_mode.py", "gate_sell_veto_active"), ("observer/production_mode.py", "narrow_band_threshold_active"), ("observer/production_mode.py", "kelly_buffer_scaling_active"), ("observer/production_mode.py", "vote_addition_active"), ("observer/production_mode.py", "phase_veto_active"), ("observer/production_mode.py", "volatility_veto_active"), ("observer/real_data_contract.py", "repo_root_from"), ("observer/real_data_contract.py", "load_source_registry"), ("observer/real_data_contract.py", "registered_source_ids"), ("observer/real_data_contract.py", "make_test_fixture_metric"), ("observer/real_data_contract.py", "summarize_truth_status"), ("observer/wave_predictor.py", "get_wave_predictor"), ("observer/wave_predictor.py", "wave_predictor_predict"), ("s51/aureon_51_compound.py", "summarize_compounding"),)
TOOLS: list[Any] = [ stage2_summarize_patterns, stage2_sumerian_decoder, stage2_sumerian_vector, stage2_iching_decoder, stage2_iching_vector, stage2_render_auris, stage2_render_brain, stage2_render_self_coder, stage2_render_organism, stage2_render_qgita, stage2_predict_next, stage2_build_report, stage2_ungrounded_nodes, stage2_is_human_held, stage2_fit_tanh, stage2_fit_full, stage2_simulation_fallback, stage2_fallback_marker, stage2_momentum_tracker, stage2_momentum_predict, stage2_observer_mode, stage2_reload_mode, stage2_is_live, stage2_is_shadow, stage2_gate_buy_veto, stage2_gate_sell_veto, stage2_narrow_band, stage2_kelly_buffer, stage2_vote_addition, stage2_phase_veto, stage2_volatility_veto, stage2_repo_root, stage2_source_registry, stage2_source_ids, stage2_test_fixture_metric, stage2_truth_counts, stage2_wave_predictor, stage2_wave_predict, stage2_summarize_compounding,]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279"""Resources and prompts. Bodies are quoted from the checkout or from code constants."""
from __future__ import annotations
import jsonfrom typing import Any
from aureon_public import pathsfrom aureon_public.quiet import quietfrom aureon_public.text import AURIS_FOUR, HOLD_LINE, SERVER_PLAIN
def _text(path_reader: Any) -> str: return path_reader().read_text(encoding="utf-8")
def _dumps(payload: dict[str, Any]) -> str: return json.dumps(payload, ensure_ascii=False, allow_nan=False, sort_keys=True)
@quietdef harmonic_reality_defaults() -> str: """Code defaults for HarmonicRealityField. Not a fit and not a measurement.
The class default enable_multiverse is True (multiverse on). Label: cited, aureon/harmonic/aureon_harmonic_reality.py. """
from aureon.harmonic.aureon_harmonic_reality import ( DEFAULT_ALPHA, DEFAULT_BETA, DEFAULT_DELTA_T, DEFAULT_G, DEFAULT_TAU, PHI_INVERSE, SCHUMANN_BASE, HarmonicRealityField, )
formula = "" for line in (HarmonicRealityField.__doc__ or "").splitlines(): if "Λ(t)" in line or "Λ(t)" in line: formula = line.strip() break if not formula: for line in (HarmonicRealityField.__doc__ or "").splitlines(): if "Λ" in line and "=" in line: formula = line.strip() break return _dumps( { "class_default_enable_multiverse": True, "delta_t": DEFAULT_DELTA_T, "formula": formula, "g": DEFAULT_G, "alpha": DEFAULT_ALPHA, "beta": DEFAULT_BETA, "label": "cited. Code defaults. Not a measurement.", "phi_inverse": PHI_INVERSE, "sample_rate": 1000.0, "schumann_base_constant": SCHUMANN_BASE, "schumann_f0": "null. HOLD.", "tau": DEFAULT_TAU, } )
@quietdef lambda_engine_defaults() -> str: """LambdaEngine module constants. BETA is _resolve_beta(), not a fitted file.
This resource does not read state/. Label: cited, aureon/core/aureon_lambda_engine.py. """
from aureon.core import aureon_lambda_engine as engine
return _dumps( { "ALPHA": engine.ALPHA, "BETA": engine.BETA, "BETA_note": "BETA is _resolve_beta(). When AUREON_HNC_BETA is unset the function returns 1.0.", "DELTA_T": engine.DELTA_T, "FREQUENCIES": list(engine.FREQUENCIES), "G": engine.G, "TAU": engine.TAU, "WEIGHTS": list(engine.WEIGHTS), "label": "cited. Not a fitted result. state/hnc_fitted_params.json was not read.", } )
@quietdef hnc_params_code_defaults() -> str: """HNCParams field defaults. Not a fit. load_params is not called.
Label: cited, aureon/core/hnc_params.py HNCParams. """
from aureon.core.hnc_params import HNCParams
params = HNCParams() return _dumps( { "alpha": params.alpha, "beta": params.beta, "delta_t": params.delta_t, "fitted_at": params.fitted_at, "fitted_from": params.fitted_from, "g": params.g, "label": "cited. Code defaults on HNCParams. Not a fit. load_params was not called.", "r_squared": params.r_squared, "tau": params.tau, } )
@quietdef auris_nodes_resource() -> str: """Nine nodes. This resource is the AURIS_NODES table.
It is not the conjecture (not called), not the persona (not scored), and not the coherence evaluator. Only the nine nodes and get_auris_coherence are real functions exposed here. Label: cited, aureon/utils/aureon_queen_hive_mind.py AURIS_NODES. """
from aureon.utils.aureon_queen_hive_mind import AURIS_NODES
return _dumps( { "auris": "nine nodes", "label": "cited. AURIS_NODES.", "nodes": AURIS_NODES, "which_auris": AURIS_FOUR, } )
@quietdef organism_seats_resource() -> str: """circulation_seats(). Names only. Circulation is not started. Label: cited."""
from aureon.core.organism_circulation import circulation_seats
return _dumps({"label": "cited", "seats": list(circulation_seats())})
@quietdef organism_nodes_resource() -> str: """list_nodes(). Names only. Label: cited."""
from aureon.core.algorithmic_nodes import list_nodes
return _dumps({"label": "cited", "nodes": list_nodes()})
@quietdef organism_systems_resource() -> str: """list_systems(). The rule strings are the source text. Label: cited."""
from aureon.core.deterministic_systems import list_systems
return _dumps({"label": "cited", "systems": list_systems()})
def holds_resource() -> str: """HOLD lines from huggingface/README.md. Label: cited-unverified until a new run."""
readme = _text(paths.holds_readme) return _dumps( { "hold": HOLD_LINE, "label": "cited-unverified. huggingface/README.md", "readme": readme, } )
def replay_brain_resource() -> str: """Vendored brain replay. Two paths. Class default is multiverse on. Label: cited."""
return _text(paths.brain_json)
def replay_qgita_resource() -> str: """Vendored QGITA adapter record. Detection rate stays HOLD. Label: cited."""
return _text(paths.qgita_json)
def replay_organism_resource() -> str: """Vendored circulation replay. The fault block in the file is seeded synthetic, not telemetry. Label: cited."""
return _text(paths.organism_json)
def replay_auris_resource() -> str: """Committed coherence-evaluator replay with no market series.
This resource is the coherence evaluator record. It is not the conjecture (not called), not a persona score (not scored), and it does not publish nine-node values. Only the nine nodes and get_auris_coherence are real functions exposed here. Label: cited, huggingface/fixed-seed-reproducible-runs/auris_nodes.json. """
body = json.loads(_text(paths.auris_json)) if isinstance(body, dict): body = { "auris": "coherence evaluator", "record": body, "which_auris": AURIS_FOUR, } return json.dumps(body, ensure_ascii=False, sort_keys=True)
@quietdef explain_two_lambda_implementations() -> str: """HarmonicRealityField and LambdaEngine are different code with different defaults.
A number from one is not a number from the other. The formulas below are the docstrings already in the repo. Label: cited. """
from aureon.core import hnc_params from aureon.harmonic.aureon_harmonic_reality import HarmonicRealityField
reality = " ".join( line.strip() for line in (HarmonicRealityField.__doc__ or "").splitlines() if "Λ" in line and "=" in line ) params = " ".join( line.strip() for line in (hnc_params.__doc__ or "").splitlines() if "Λ" in line and "=" in line ) return ( "HarmonicRealityField and LambdaEngine are different implementations. " "A number from one is not a number from the other. " "The class default HarmonicRealityField() sets enable_multiverse=True (multiverse on). " f"HarmonicRealityField docstring: {reality} " f"hnc_params docstring: {params} " "Label: cited. No formula was added here." )
def explain_auris_four_meanings() -> str: """Name the four Auris meanings. Only two functions are exposed.
This prompt is the four-way split. The conjecture is not called. The nine nodes are read_auris_nodes and AURIS_NODES. The persona is not scored. The coherence evaluator is get_auris_coherence. Auris-to-Lambda link: HOLD. """
return ( f"{AURIS_FOUR} " "auris_nodes calls read_auris_nodes. " "aureon://auris/nodes is the AURIS_NODES table. " "auris_coherence calls get_auris_coherence. " "Whenever any node has no reading, that tool returns status no_data and coherence null. " "Trade readiness: HOLD. Auris-to-Lambda link: HOLD." )
def explain_qgita_adapter() -> str: """QGITA events are the adapter return. Detection rate is HOLD. signals are not shown.
Label: cited, QGITAMarketAnalyzer.analyze. The bundled series is cited-unverified and is not public market data. """
return ( "QGITA events are the return of QGITAMarketAnalyzer.analyze. " "They are not a detection rate. Detection rate: HOLD. False-alarm rate: HOLD. " "The signals object is not shown. " "The bundled Lambda column is cited-unverified and is not public market data." )
def explain_organism_replay() -> str: """The organism replay is a file. Catalog names are not a running circulation.
The fault block is seeded synthetic input, not telemetry. Label: cited. """
return ( f"{SERVER_PLAIN} " "The organism replay is a file. " "Seats in the catalog are names. Circulation is not started. " "The fault block is seeded synthetic input, not telemetry. " "A claim that those faults are recorded seat faults is HOLD." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516"""Block sockets, process starts, and writes outside the sweep sandbox.
Installed only in a sweep child. The public server refuses to start when``AUREON_PUBLIC_SWEEP`` is set, and this module does not start a server."""
from __future__ import annotations
import builtinsimport ioimport osimport subprocessfrom pathlib import Pathfrom typing import Any
_INSTALLED = False_SOCKETS: list[str] = []_PROCESSES: list[str] = []_WRITES: list[str] = []_SANDBOX_WRITES: list[str] = []_REAL: dict[str, Any] = {}_USER_DIR_NAMES = ( "HOME", "USERPROFILE", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_STATE_HOME",)
def declare_sandbox() -> Path: """Point temp files at a directory inside the sweep parent.
Python probes ``/tmp`` when ``TMPDIR`` is unset. Those probes are not the module writing. The sandbox stays the temp parent, and ``TMPDIR`` is a directory inside it. """
from aureon_public.sweep_layout import beside
sandbox = beside() scratch = sandbox / "sweep-scratch" home = sandbox / "home" dirs = { "HOME": home, "USERPROFILE": home, "XDG_CACHE_HOME": home / ".cache", "XDG_CONFIG_HOME": home / ".config", "XDG_DATA_HOME": home / ".local" / "share", "XDG_RUNTIME_DIR": sandbox / "runtime", "XDG_STATE_HOME": home / ".local" / "state", } for path in (scratch, *dirs.values()): path.mkdir(parents=True, exist_ok=True) os.environ["AUREON_PUBLIC_SANDBOX"] = str(sandbox) os.environ["TMPDIR"] = str(scratch) os.environ["TEMP"] = str(scratch) os.environ["TMP"] = str(scratch) for name, path in dirs.items(): os.environ[name] = str(path) try: import tempfile
tempfile.tempdir = None except Exception: pass return sandbox
def snapshot() -> dict[str, list[str]]: """Copies of the attempts recorded since install."""
return { "processes": list(_PROCESSES), "sandbox_writes": list(_SANDBOX_WRITES), "sockets": list(_SOCKETS), "writes": list(_WRITES), }
def _sandbox() -> Path | None: raw = os.environ.get("AUREON_PUBLIC_SANDBOX", "").strip() if not raw: return None return Path(raw).resolve()
def _outside(path: object) -> bool: sandbox = _sandbox() try: resolved = Path(os.fspath(path)).resolve() except (OSError, TypeError, ValueError): return True if sandbox is None: return True return resolved != sandbox and sandbox not in resolved.parents
def _harmless_device(path: object) -> bool: """``/dev/null`` is the pin check's stderr sink, not a module write."""
try: text = os.fspath(path) except TypeError: return False return str(text) in {"/dev/null", "/dev/zero", "/dev/stdout", "/dev/stderr"}
def _record_inside(path: object) -> None: """Remember a write under the sandbox that is not the temp scratch dir."""
sandbox = _sandbox() if sandbox is None or _harmless_device(path): return try: resolved = Path(os.fspath(path)).resolve() except (OSError, TypeError, ValueError): return scratch = (sandbox / "sweep-scratch").resolve() if resolved == scratch or scratch in resolved.parents: return if resolved != sandbox and sandbox not in resolved.parents: return text = str(resolved)[:200] if text not in _SANDBOX_WRITES: _SANDBOX_WRITES.append(text)
def _guard_path(path: object) -> None: """Block a path outside the sandbox. Record one inside it."""
if _harmless_device(path): return if _outside(path): _note_write(path) _record_inside(path)
def _note_write(path: object) -> None: text = str(path)[:200] if text not in _WRITES: _WRITES.append(text) raise OSError("write blocked outside sandbox")
def _pin_git(command: object) -> bool: """True for the loader's ``git rev-parse <pin>:<path>`` and nothing else."""
if not isinstance(command, (list, tuple)) or len(command) < 3: return False if Path(str(command[0])).name != "git" or str(command[1]) != "rev-parse": return False spec = str(command[2]) pin = "8aa6a2d971cc529484e2a5e261e28afafab4e4f4" return spec.startswith(pin + ":") and " " not in spec
def _note_process(kind: str, detail: object) -> None: text = f"{kind} {detail}"[:200] if text not in _PROCESSES: _PROCESSES.append(text) raise OSError("process blocked")
def _write_mode(mode: object) -> bool: text = str(mode or "r") return any(flag in text for flag in ("w", "a", "x", "+"))
def install_sweep_guard() -> None: """Replace socket, process, and write entry points. Idempotent."""
global _INSTALLED if _INSTALLED: return import shutil import socket
_SOCKETS.clear() _PROCESSES.clear() _WRITES.clear() _SANDBOX_WRITES.clear()
class _Guard(socket.socket): def connect(self, address: object, *args: object, **kwargs: object) -> None: text = str(address)[:160] if text not in _SOCKETS: _SOCKETS.append(text) raise OSError("socket blocked")
def connect_ex(self, address: object, *args: object, **kwargs: object) -> int: text = str(address)[:160] if text not in _SOCKETS: _SOCKETS.append(text) raise OSError("socket blocked")
def _create_connection(*args: object, **kwargs: object) -> object: if "create_connection" not in _SOCKETS: _SOCKETS.append("create_connection") raise OSError("socket blocked")
def _open(file: object, mode: object = "r", *args: object, **kwargs: object) -> object: if _write_mode(mode): _guard_path(file) return _REAL["open"](file, mode, *args, **kwargs)
def _os_open(path: object, flags: int, *args: object, **kwargs: object) -> int: writing = flags & (os.O_WRONLY | os.O_RDWR | os.O_APPEND) if writing: _guard_path(path) return _REAL["os_open"](path, flags, *args, **kwargs)
def _mkdir(path: object, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["mkdir"](path, *args, **kwargs)
def _makedirs(path: object, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["makedirs"](path, *args, **kwargs)
def _unlink(path: object, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["unlink"](path, *args, **kwargs)
def _remove(path: object, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["remove"](path, *args, **kwargs)
def _rename(src: object, dst: object, *args: object, **kwargs: object) -> None: _guard_path(src) _guard_path(dst) return _REAL["rename"](src, dst, *args, **kwargs)
def _replace(src: object, dst: object, *args: object, **kwargs: object) -> None: _guard_path(src) _guard_path(dst) return _REAL["replace"](src, dst, *args, **kwargs)
def _rmdir(path: object, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["rmdir"](path, *args, **kwargs)
def _truncate(path: object, length: int) -> None: _guard_path(path) return _REAL["truncate"](path, length)
def _chmod(path: object, mode: int, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["chmod"](path, mode, *args, **kwargs)
def _lchmod(path: object, mode: int) -> None: _guard_path(path) return _REAL["lchmod"](path, mode)
def _chown(path: object, uid: int, gid: int, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["chown"](path, uid, gid, *args, **kwargs)
def _symlink(src: object, dst: object, *args: object, **kwargs: object) -> None: _guard_path(dst) return _REAL["symlink"](src, dst, *args, **kwargs)
def _link(src: object, dst: object, *args: object, **kwargs: object) -> None: _guard_path(src) _guard_path(dst) return _REAL["link"](src, dst, *args, **kwargs)
def _utime(path: object, times: object = None, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["utime"](path, times, *args, **kwargs)
def _fd_path(fd: object) -> str | None: try: return os.readlink(f"/proc/self/fd/{int(fd)}") except (OSError, TypeError, ValueError): return None
def _guard_fd(fd: object) -> None: path = _fd_path(fd) if path is None: _note_write(f"fd:{fd}") _guard_path(path)
def _ftruncate(fd: object, length: int) -> None: _guard_fd(fd) return _REAL["ftruncate"](fd, length)
def _fchmod(fd: object, mode: int) -> None: _guard_fd(fd) return _REAL["fchmod"](fd, mode)
def _rmtree(path: object, *args: object, **kwargs: object) -> None: _guard_path(path) return _REAL["rmtree"](path, *args, **kwargs)
def _move(src: object, dst: object, *args: object, **kwargs: object) -> object: _guard_path(src) _guard_path(dst) return _REAL["move"](src, dst, *args, **kwargs)
def _fork(*args: object, **kwargs: object) -> int: _note_process("fork", args or "fork") raise AssertionError("unreachable")
def _forkpty(*args: object, **kwargs: object) -> object: _note_process("forkpty", args or "forkpty") raise AssertionError("unreachable")
def _posix_spawn(path: object, *args: object, **kwargs: object) -> int: _note_process("posix_spawn", path) raise AssertionError("unreachable")
def _posix_spawnp(path: object, *args: object, **kwargs: object) -> int: _note_process("posix_spawnp", path) raise AssertionError("unreachable")
def _spawn(name: str): def inner(*args: object, **kwargs: object) -> int: _note_process(name, args[0] if args else name) raise AssertionError("unreachable")
return inner
def _popen(*args: object, **kwargs: object) -> object: command = args[0] if args else kwargs.get("args") # The pinned loader reads blob ids with git rev-parse. That is the # server's pin check, not the module starting a process. if _pin_git(command): return _REAL["subprocess_popen"](*args, **kwargs) _note_process("Popen", command) raise AssertionError("unreachable")
def _system(command: object) -> int: _note_process("system", command) raise AssertionError("unreachable")
def _popen_os(command: object, *args: object, **kwargs: object) -> object: _note_process("popen", command) raise AssertionError("unreachable")
def _exec(path: object, *args: object, **kwargs: object) -> None: _note_process("exec", path) raise AssertionError("unreachable")
_REAL.update( { "create_connection": socket.create_connection, "execv": os.execv, "execve": os.execve, "chmod": os.chmod, "chown": os.chown, "fchmod": getattr(os, "fchmod", None), "fork": getattr(os, "fork", None), "ftruncate": getattr(os, "ftruncate", None), "lchmod": getattr(os, "lchmod", None), "link": os.link, "forkpty": getattr(os, "forkpty", None), "makedirs": os.makedirs, "mkdir": os.mkdir, "move": shutil.move, "open": builtins.open, "os_open": os.open, "popen": os.popen, "posix_spawn": getattr(os, "posix_spawn", None), "posix_spawnp": getattr(os, "posix_spawnp", None), "remove": os.remove, "rename": os.rename, "replace": os.replace, "rmdir": os.rmdir, "rmtree": shutil.rmtree, "symlink": os.symlink, "truncate": getattr(os, "truncate", None), "utime": os.utime, "socket": socket.socket, "subprocess_popen": subprocess.Popen, "system": os.system, "unlink": os.unlink, } ) for name in ( "spawnl", "spawnle", "spawnlp", "spawnlpe", "spawnv", "spawnve", "spawnvp", "spawnvpe", ): if hasattr(os, name): _REAL[name] = getattr(os, name) builtins.open = _open # type: ignore[assignment] io.open = _open # type: ignore[assignment] os.open = _os_open # type: ignore[assignment] os.mkdir = _mkdir # type: ignore[assignment] os.makedirs = _makedirs # type: ignore[assignment] os.unlink = _unlink # type: ignore[assignment] os.remove = _remove # type: ignore[assignment] os.rename = _rename # type: ignore[assignment] os.replace = _replace # type: ignore[assignment] os.rmdir = _rmdir # type: ignore[assignment] os.chmod = _chmod # type: ignore[assignment] os.chown = _chown # type: ignore[assignment] os.symlink = _symlink # type: ignore[assignment] os.link = _link # type: ignore[assignment] os.utime = _utime # type: ignore[assignment] if _REAL.get("truncate") is not None: os.truncate = _truncate # type: ignore[assignment] if _REAL.get("ftruncate") is not None: os.ftruncate = _ftruncate # type: ignore[assignment] if _REAL.get("fchmod") is not None: os.fchmod = _fchmod # type: ignore[assignment] if _REAL.get("lchmod") is not None: os.lchmod = _lchmod # type: ignore[assignment] shutil.rmtree = _rmtree # type: ignore[assignment] shutil.move = _move # type: ignore[assignment] if _REAL.get("fork") is not None: os.fork = _fork # type: ignore[assignment] if _REAL.get("forkpty") is not None: os.forkpty = _forkpty # type: ignore[assignment] if _REAL.get("posix_spawn") is not None: os.posix_spawn = _posix_spawn # type: ignore[assignment] if _REAL.get("posix_spawnp") is not None: os.posix_spawnp = _posix_spawnp # type: ignore[assignment] for name in ( "spawnl", "spawnle", "spawnlp", "spawnlpe", "spawnv", "spawnve", "spawnvp", "spawnvpe", ): if name in _REAL: setattr(os, name, _spawn(name)) os.system = _system # type: ignore[assignment] os.popen = _popen_os # type: ignore[assignment] os.execv = _exec # type: ignore[assignment] os.execve = _exec # type: ignore[assignment] subprocess.Popen = _popen # type: ignore[misc, assignment] socket.socket = _Guard # type: ignore[misc] socket.create_connection = _create_connection # type: ignore[assignment] try: import multiprocessing
def _start(self: object, *args: object, **kwargs: object) -> None: _note_process("Process.start", getattr(self, "name", "process")) raise AssertionError("unreachable")
_REAL["process_start"] = multiprocessing.Process.start multiprocessing.Process.start = _start # type: ignore[method-assign] except Exception: _REAL["process_start"] = None _INSTALLED = True
def uninstall_sweep_guard() -> None: """Restore the process-wide functions. Tests use this."""
global _INSTALLED if not _INSTALLED: return import shutil import socket
builtins.open = _REAL["open"] io.open = _REAL["open"] os.open = _REAL["os_open"] os.mkdir = _REAL["mkdir"] os.makedirs = _REAL["makedirs"] os.unlink = _REAL["unlink"] os.remove = _REAL["remove"] os.rename = _REAL["rename"] os.replace = _REAL["replace"] os.rmdir = _REAL["rmdir"] os.chmod = _REAL["chmod"] os.chown = _REAL["chown"] os.symlink = _REAL["symlink"] os.link = _REAL["link"] os.utime = _REAL["utime"] for name in ("truncate", "ftruncate", "fchmod", "lchmod"): if _REAL.get(name) is not None: setattr(os, name, _REAL[name]) shutil.rmtree = _REAL["rmtree"] shutil.move = _REAL["move"] for name in ( "fork", "forkpty", "posix_spawn", "posix_spawnp", "spawnl", "spawnle", "spawnlp", "spawnlpe", "spawnv", "spawnve", "spawnvp", "spawnvpe", ): if _REAL.get(name) is not None: setattr(os, name, _REAL[name]) os.system = _REAL["system"] os.popen = _REAL["popen"] os.execv = _REAL["execv"] os.execve = _REAL["execve"] subprocess.Popen = _REAL["subprocess_popen"] socket.socket = _REAL["socket"] socket.create_connection = _REAL["create_connection"] if _REAL.get("process_start") is not None: import multiprocessing
multiprocessing.Process.start = _REAL["process_start"] _INSTALLED = False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Place fake NEXUS and Sero checkouts beside the checkout this process loads.
The sweep scripts copy the checkout under an ordinary temp parent and run thismodule from that copy, so the parent is not the filesystem root. There is noprivilege escalation. A sibling that already exists is left in place."""
from __future__ import annotations
import jsonimport shutilfrom pathlib import Path
from aureon_public.paths import repo_root
SIBLING_NAMES = ("NEXUS-LIVE-FEED-", "Aureon-Trading--Project-Sero")_MARKER = ".aureon-sweep-planted"
def beside() -> Path: return repo_root().resolve().parent
def _state_path() -> Path: return beside() / ".sweep_siblings.json"
def _fake_source() -> str: return ( "import socket\n" "socket.create_connection(('203.0.113.1', 9), timeout=1)\n" )
def _write(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8")
def plant() -> list[str]: """Create any missing sibling. Return the names this process created."""
created: list[str] = [] root = beside() files = { "NEXUS-LIVE-FEED-": "organism/public_field.py", "Aureon-Trading--Project-Sero": "organism/public_market.py", } for name, relative in files.items(): folder = root / name if folder.exists(): continue _write(folder / relative, _fake_source()) _write(folder / _MARKER, "planted by aureon public sweep\n") created.append(name) return created
def cleanup(created: list[str]) -> None: """Remove only siblings this process planted."""
root = beside() for name in created: folder = root / name marker = folder / _MARKER if not marker.is_file(): continue shutil.rmtree(folder)
def created_names() -> list[str]: path = _state_path() if not path.is_file(): return [] loaded = json.loads(path.read_text(encoding="utf-8")) if not isinstance(loaded, list): return [] return [str(item) for item in loaded]
def layout_record(created: list[str] | None = None) -> dict[str, object]: root = beside() names = created_names() if created is None else created return { "beside": str(root), "created": names, "siblings": [ { "name": name, "present": (root / name).is_dir(), } for name in SIBLING_NAMES ], }
def main() -> None: import argparse
parser = argparse.ArgumentParser(prog="aureon-public-sweep-layout") parser.add_argument("--plant", action="store_true") parser.add_argument("--cleanup", action="store_true") args = parser.parse_args() state = _state_path() if args.plant: created = plant() state.write_text(json.dumps(created), encoding="utf-8") return if args.cleanup and state.is_file(): created = json.loads(state.read_text(encoding="utf-8")) cleanup([str(item) for item in created]) state.unlink()
if __name__ == "__main__": main()12345678# Test install for the measured venv. Not the public server runtime.# measured/aureon_public_stage1_run.sh installs this after requirements.txt.# The server runtime stays mcp/aureon_public/requirements.txt.pytest>=8.0pytest-timeout>=2.3flask>=3.0pandas>=2.1.0scipy>=1.111234567891011121314151617181920212223242526"""Descriptions shared by tools, resources, prompts, and the README."""
from __future__ import annotations
AURIS_FOUR = ( "Four meanings stay separate. " "The conjecture is the five symbolic-life markers in LambdaEngine and is not called. " "The nine nodes are QueenHiveMind.read_auris_nodes and AURIS_NODES. " "The persona on QueenHiveMind is not scored. " "The coherence evaluator is QueenHiveMind.get_auris_coherence. " "Only the nine nodes and get_auris_coherence are real functions exposed here.")
HOLD_LINE = ( "Trade readiness: HOLD. " "Auris-to-Lambda link: HOLD. " "QGITA detection rate: HOLD. " "False-alarm rate: HOLD. " "Schumann f0: null. HOLD.")
SERVER_PLAIN = ( "MCP lets outside models call Aureon's tools. " "No outside model or API becomes Aureon's reasoning. " "The cognition runs in Aureon's own code.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805"""The nine public tools. Each returns JSON text. No orders and no state/ writes."""
from __future__ import annotations
import csvimport jsonimport mathimport osimport tempfilefrom pathlib import Pathfrom typing import Any
from aureon_public import pathsfrom aureon_public.guard_loader import aureon_sourcefrom aureon_public.quiet import quietfrom aureon_public.text import AURIS_FOUR, HOLD_LINE
_AURIS_FIELDS = ("volatility", "momentum", "volume", "spread")
def _plain(value: Any) -> Any: if isinstance(value, dict): return {str(key): _plain(item) for key, item in value.items()} if isinstance(value, (list, tuple)): return [_plain(item) for item in value] if isinstance(value, bool) or value is None or isinstance(value, str): return value if isinstance(value, int): return int(value) if isinstance(value, float): return float(value) item = getattr(value, "item", None) if callable(item): try: return _plain(item()) except Exception: pass return str(value)
_OMITTED_PUBLIC_KEYS = ("consciousness_level", "consciousness_psi")
def _omit_public_keys(body: dict[str, Any]) -> dict[str, Any]: for key in _OMITTED_PUBLIC_KEYS: body.pop(key, None) return body
def _strip_consciousness(value: Any) -> Any: if isinstance(value, dict): return { str(key): _strip_consciousness(item) for key, item in value.items() if not str(key).startswith("consciousness_") } if isinstance(value, list): return [_strip_consciousness(item) for item in value] return value
def _dumps(payload: dict[str, Any]) -> str: body = _strip_consciousness(_plain(payload)) body["aureon_source"] = aureon_source() return json.dumps(body, ensure_ascii=False, allow_nan=False, sort_keys=True)
def _load(path: Path) -> dict[str, Any]: loaded = json.loads(path.read_text(encoding="utf-8")) if not isinstance(loaded, dict): raise TypeError(path.name) return loaded
def _finite(value: object) -> float | None: if isinstance(value, bool) or value is None: return None if not isinstance(value, (int, float)): return None number = float(value) if not math.isfinite(number): return None return number
def _brain() -> dict[str, Any]: return _load(paths.brain_json())
def _path_block(brain: dict[str, Any], enable_multiverse: bool) -> dict[str, Any]: hnc = brain.get("hnc") if not isinstance(hnc, dict): raise KeyError("hnc") if enable_multiverse: block = hnc.get("multiverse_extension") else: block = hnc if not isinstance(block, dict): raise KeyError("brain path") return block
def _cap(enable_multiverse: bool) -> int: steps = _path_block(_brain(), enable_multiverse).get("steps") if isinstance(steps, bool) or not isinstance(steps, int) or steps < 1: raise ValueError("committed step count is missing") return steps
def _hnc_doc() -> str: brain = _brain() on = json.dumps(_path_block(brain, True)["coherence"]) off = json.dumps(_path_block(brain, False)["coherence"]) return f"""Call HarmonicRealityField.step. Label: inferred. This is a rerun in this process.
The class default HarmonicRealityField() sets enable_multiverse=True (multiverse on). This tool's default is that class default. The output field enable_multiverse is the value used for this call.
Do not mix the two committed brain paths. Cited, huggingface/hnc-field/replay/brain.json: multiverse on coherence is {on}; multiverse off coherence is {off}.
steps is capped at the committed steps field for the selected path. There is no frequencies argument. Trade readiness: HOLD. {HOLD_LINE}
Args: alpha: Observer gain passed to HarmonicRealityField. Label: cited, DEFAULT_ALPHA in aureon/harmonic/aureon_harmonic_reality.py. beta: Echo gain passed to HarmonicRealityField. Label: cited, DEFAULT_BETA. tau: Echo delay passed to HarmonicRealityField. Label: cited, DEFAULT_TAU. g: Observer nonlinearity passed to HarmonicRealityField. Label: cited, DEFAULT_G. delta_t: Observer window passed to HarmonicRealityField. Label: cited, DEFAULT_DELTA_T. sample_rate: Samples per second. Signature default 1000.0. Label: cited, HarmonicRealityField.__init__. enable_multiverse: Class default is True (multiverse on). False selects the other committed brain path. Reported in the output. Label: cited. steps: Step count. Omitted uses the committed steps for the selected path. Values above that cap are unavailable. Label: cited, vendored brain.json steps."""
@quietdef hnc_reality_step( alpha: float = 0.85, beta: float = 0.9, tau: float = 0.05, g: float = 1.5, delta_t: float = 0.01, sample_rate: float = 1000.0, enable_multiverse: bool = True, steps: int | None = None,) -> str: turned_on = enable_multiverse is True if not isinstance(enable_multiverse, bool): return _dumps( { "class_default_enable_multiverse": True, "enable_multiverse": None, "label": "cited", "reason": "enable_multiverse is missing", "status": "unavailable", } ) try: cap = _cap(turned_on) except (OSError, ValueError, KeyError, TypeError): return _dumps( { "class_default_enable_multiverse": True, "enable_multiverse": turned_on, "label": "cited", "reason": "The committed step count is missing.", "status": "unavailable", } ) chosen: int | None if steps is None: chosen = cap elif isinstance(steps, bool) or not isinstance(steps, int) or steps < 1: chosen = None elif steps > cap: return _dumps( { "class_default_enable_multiverse": True, "enable_multiverse": turned_on, "label": "cited. The cap is the steps field on the selected brain path.", "reason": "steps is above the committed replay length for this path", "status": "unavailable", "steps_cap": cap, } ) else: chosen = steps numbers = { "alpha": _finite(alpha), "beta": _finite(beta), "tau": _finite(tau), "g": _finite(g), "delta_t": _finite(delta_t), "sample_rate": _finite(sample_rate), } if ( chosen is None or any(value is None for value in numbers.values()) or numbers["sample_rate"] is None or numbers["sample_rate"] <= 0 ): return _dumps( { "class_default_enable_multiverse": True, "enable_multiverse": turned_on, "label": "cited", "reason": "A parameter is missing.", "status": "unavailable", "steps_cap": cap, } ) from aureon.harmonic.aureon_harmonic_reality import HarmonicRealityField
field = HarmonicRealityField( alpha=float(numbers["alpha"]), beta=float(numbers["beta"]), tau=float(numbers["tau"]), g=float(numbers["g"]), delta_t=float(numbers["delta_t"]), sample_rate=float(numbers["sample_rate"]), enable_multiverse=turned_on, ) series = [float(field.step()) for _ in range(chosen)] payload: dict[str, Any] = { "class_default_enable_multiverse": True, "coherence": float(field.coherence), "committed_replay_match": None, "committed_replay_path": "multiverse_extension" if turned_on else "hnc", "enable_multiverse": bool(field.enable_multiverse), "get_state": field.get_state(), "label": "inferred. Rerun of HarmonicRealityField.step in this process.", "lambda_last": series[-1], "series": series, "state_name": field.state.name, "state_value": field.state.value, "status": "inferred", "steps": chosen, "steps_cap": cap, } payload["committed_replay_match"] = _committed_match( payload, {key: float(value) for key, value in numbers.items()}, turned_on, ) return _dumps(payload)
def _committed_match(payload: dict[str, Any], numbers: dict[str, float], enable_multiverse: bool) -> bool | None: brain = _brain() parameters = brain.get("hnc", {}).get("parameters") if not isinstance(parameters, dict): return None expected = { "alpha": parameters.get("alpha"), "beta": parameters.get("beta"), "delta_t": parameters.get("delta_t"), "g": parameters.get("g"), "sample_rate": parameters.get("sample_rate"), "tau": parameters.get("tau"), } if any(numbers[key] != expected[key] for key in expected): return None block = _path_block(brain, enable_multiverse) if payload["steps"] != block.get("steps"): return None fresh = { "coherence": payload["coherence"], "lambda_last": payload["lambda_last"], "series": payload["series"], } rounded = json.loads(json.dumps(fresh)) return ( rounded["coherence"] == block.get("coherence") and rounded["lambda_last"] == block.get("lambda_last") and rounded["series"] == block.get("series") and payload["state_value"] == block.get("state") )
hnc_reality_step.__doc__ = _hnc_doc()
@quietdef hnc_canonical_read(envelope_jsonl: str | None = None) -> str: """Read CanonicalField. An empty envelope does not touch state/.
The public JSON drops consciousness_level and consciousness_psi. Those fields have defaults on CanonicalField, so CanonicalField(**public_dict) still constructs and does not raise. It is not a full to_dict() round-trip: the rebuilt fields are the defaults, not whatever to_dict() would have carried.
Label: inferred when an envelope was supplied and available is true. Otherwise the field is unavailable. Cited: read_canonical_field does not run unless a temp trace was set. The bundled brain replay is a formula record, not a canonical envelope.
Args: envelope_jsonl: Optional JSONL text for one canonical envelope. Empty or omitted returns the unavailable field and does not read state/. Label: cited, aureon/core/hnc_field.py read_canonical_field. """
if envelope_jsonl is None or not str(envelope_jsonl).strip(): from aureon.core.hnc_field import CanonicalField
body = CanonicalField().to_dict() body["label"] = ( "cited. No envelope was supplied, so state/ was not read. " "The bundled brain replay is a formula record, not a canonical envelope." ) body["status"] = "unavailable" return _dumps(_omit_public_keys(body)) return _dumps(_omit_public_keys(_with_envelope(str(envelope_jsonl), blend=False)))
@quietdef hnc_blend_read(envelope_jsonl: str | None = None) -> str: """Read BlendedField. Does not call publish_subfield. An empty envelope does not touch state/.
BlendedField.to_dict does not include consciousness_level or consciousness_psi. The same two keys are dropped if they appear. That drop does not change a BlendedField round-trip.
Label: inferred when an envelope was supplied and available is true. Otherwise unavailable.
Args: envelope_jsonl: Optional JSONL text. Empty or omitted returns the unavailable blend and does not read state/. Label: cited, aureon/core/hnc_field.py blend_field. """
if envelope_jsonl is None or not str(envelope_jsonl).strip(): from aureon.core.hnc_field import BlendedField
body = BlendedField().to_dict() body["label"] = "cited. No envelope was supplied, so state/ was not read." body["status"] = "unavailable" return _dumps(_omit_public_keys(body)) return _dumps(_omit_public_keys(_with_envelope(str(envelope_jsonl), blend=True)))
def _with_envelope(text: str, *, blend: bool) -> dict[str, Any]: from aureon.core.hnc_field import blend_field, read_canonical_field
previous_trace = os.environ.get("AUREON_HNC_TRACE_PATH") previous_bus = os.environ.get("AUREON_BUS_TRACE_DIR") directory = Path(tempfile.mkdtemp(prefix="aureon-public-field-")) trace = directory / "envelope.jsonl" bus_dir = directory / "bus" bus_dir.mkdir() try: payload = text if text.endswith("\n") else text + "\n" trace.write_text(payload, encoding="utf-8") os.environ["AUREON_HNC_TRACE_PATH"] = str(trace) os.environ["AUREON_BUS_TRACE_DIR"] = str(bus_dir) field = read_canonical_field(bus=object()) if blend: body = blend_field(bus=object()).to_dict() else: body = field.to_dict() finally: if previous_trace is None: os.environ.pop("AUREON_HNC_TRACE_PATH", None) else: os.environ["AUREON_HNC_TRACE_PATH"] = previous_trace if previous_bus is None: os.environ.pop("AUREON_BUS_TRACE_DIR", None) else: os.environ["AUREON_BUS_TRACE_DIR"] = previous_bus trace.unlink(missing_ok=True) for child in bus_dir.glob("*"): child.unlink(missing_ok=True) bus_dir.rmdir() directory.rmdir() body["label"] = "inferred. Read from the envelope supplied to this process." body["status"] = "inferred" if body.get("available") is True else "unavailable" return body
@quietdef lambda_engine_step( volatility: float | None = None, readings: list[dict[str, Any]] | None = None,) -> str: """Run LambdaEngine.step, or return status unavailable.
This is not HarmonicRealityField and it is not the committed brain replay. The committed replay ships no readings. A missing or short reading list returns status unavailable and does not fill lambda or coherence with 0. Auris-to-Lambda link: HOLD.
Args: volatility: Finite volatility. Omitted is unavailable, not 0. Label: cited, LambdaEngine.step. readings: Objects with name, value, confidence, and state. Fewer than two returns status unavailable. Label: cited, huggingface/hnc-field/app.py. Auris-to-Lambda link: HOLD. """
parsed, reason = _parse_readings(readings) vol = _finite(volatility) if parsed is None or vol is None: why = reason or "volatility is missing" return _dumps( { "auris_to_lambda": "HOLD", "label": ( "cited. The committed brain replay ships no LambdaEngine readings. " "This is not HarmonicRealityField. Auris-to-Lambda link: HOLD." ), "lambda_t": None, "reason": why, "status": "unavailable", } ) fd, name = tempfile.mkstemp(prefix="aureon-public-lambda-", suffix=".json") os.close(fd) path = Path(name) try: from aureon.core.aureon_lambda_engine import LambdaEngine, SubsystemReading
engine = LambdaEngine(state_path=path) state = engine.step(parsed_readings(parsed, SubsystemReading), volatility=vol, auto_persist=False) body = state.to_dict() finally: path.unlink(missing_ok=True) body["auris_to_lambda"] = "HOLD" body["label"] = ( "inferred. LambdaEngine.step on the supplied readings. " "Not HarmonicRealityField. Not the committed brain replay. " "Field names are the keys LambdaState.to_dict already returns. " "Auris-to-Lambda link: HOLD." ) body["status"] = "inferred" return _dumps(body)
def parsed_readings(rows: list[dict[str, Any]], reading_type: Any) -> list[Any]: return [ reading_type( name=row["name"], value=row["value"], confidence=row["confidence"], state=row["state"], ) for row in rows ]
def _parse_readings(readings: list[dict[str, Any]] | None) -> tuple[list[dict[str, Any]] | None, str | None]: if readings is None: return None, "LambdaEngine path: unavailable. No readings were supplied." if not isinstance(readings, list) or len(readings) < 2: return None, "LambdaEngine path: unavailable. At least two readings are required." parsed: list[dict[str, Any]] = [] for row in readings: if not isinstance(row, dict): return None, "LambdaEngine path: unavailable. A reading is missing fields." name = row.get("name") value = _finite(row.get("value")) confidence = _finite(row.get("confidence")) state = row.get("state") if not isinstance(name, str) or not name.strip() or value is None or confidence is None: return None, "LambdaEngine path: unavailable. A reading is missing fields." if not isinstance(state, str) or not state.strip(): return None, "LambdaEngine path: unavailable. A reading is missing fields." parsed.append( { "name": name.strip(), "value": value, "confidence": confidence, "state": state.strip(), } ) return parsed, None
def _texture( volatility: float | None, momentum: float | None, volume: float | None, spread: float | None,) -> dict[str, float] | None: supplied: dict[str, float] = {} for key, raw in ( ("volatility", volatility), ("momentum", momentum), ("volume", volume), ("spread", spread), ): if raw is None: continue number = _finite(raw) if number is None: continue supplied[key] = number return supplied or None
def _queen() -> Any: from aureon.utils.aureon_queen_hive_mind import QueenHiveMind
return QueenHiveMind.__new__(QueenHiveMind)
@quietdef auris_nodes( volatility: float | None = None, momentum: float | None = None, volume: float | None = None, spread: float | None = None,) -> str: """Nine nodes. Real function: QueenHiveMind.read_auris_nodes.
This tool is the nine nodes. It is not the conjecture (not called), not the persona (not scored), and not the coherence evaluator. The coherence evaluator is auris_coherence. Only the nine nodes and get_auris_coherence are real functions exposed here.
A missing field is omitted. Nothing is filled with zero. Label: inferred.
Args: volatility: Optional Tiger and related input. Omitted stays omitted. Label: cited, _auris_input. momentum: Optional Falcon and Dolphin input. Omitted stays omitted. Label: cited, _auris_input. volume: Optional Falcon and CargoShip input. Omitted stays omitted. Label: cited, _auris_input. spread: Optional Deer input. Omitted stays omitted. Label: cited, _auris_input. """
market = _texture(volatility, momentum, volume, spread) nodes = _queen().read_auris_nodes(market) missing = sorted(name for name, row in nodes.items() if row.get("value") is None) return _dumps( { "auris": "nine nodes", "label": "inferred. QueenHiveMind.read_auris_nodes. A missing field is not filled.", "missing_nodes": missing, "nodes": nodes, "which_auris": AURIS_FOUR, } )
@quietdef auris_coherence( volatility: float | None = None, momentum: float | None = None, volume: float | None = None, spread: float | None = None,) -> str: """Coherence evaluator. Real function: QueenHiveMind.get_auris_coherence.
This tool is the coherence evaluator. It is not the conjecture (not called), not the nine nodes (those are read_auris_nodes and AURIS_NODES on auris_nodes), and not the persona (not scored). Only the nine nodes and get_auris_coherence are real functions exposed here.
Whenever any of the nine nodes has no reading, status is no_data and coherence is null. The missing node names are listed. Nothing is filled with zero. Auris-to-Lambda link: HOLD. Trade readiness: HOLD.
Args: volatility: Optional. Omitted is not filled with zero. Label: cited, _auris_input. momentum: Optional. Omitted is not filled with zero. Label: cited, _auris_input. volume: Optional. Omitted is not filled with zero. Label: cited, _auris_input. spread: Optional. Omitted is not filled with zero. Label: cited, _auris_input. """
market = _texture(volatility, momentum, volume, spread) queen = _queen() nodes = queen.read_auris_nodes(market) coherence, status = queen.get_auris_coherence(market) missing = sorted(name for name, row in nodes.items() if row.get("value") is None) if missing or coherence is None: return _dumps( { "auris": "coherence evaluator", "auris_to_lambda": "HOLD", "coherence": None, "label": "inferred. get_auris_coherence returned no complete nine-node reading. Auris-to-Lambda link: HOLD.", "missing_nodes": missing, "status": "no_data", "trade_readiness": "HOLD", "which_auris": AURIS_FOUR, } ) return _dumps( { "auris": "coherence evaluator", "auris_to_lambda": "HOLD", "coherence": coherence, "label": "inferred. This is the evaluator return, not a track record. Auris-to-Lambda link: HOLD.", "missing_nodes": missing, "status": status, "trade_readiness": "HOLD", "which_auris": AURIS_FOUR, } )
def _lambda_column() -> list[float]: path = paths.qgita_series() values: list[float] = [] with path.open(encoding="utf-8", newline="") as handle: reader = csv.DictReader(handle) if reader.fieldnames is None or "Lambda" not in reader.fieldnames: return [] for row in reader: try: values.append(float(row["Lambda"])) except (TypeError, ValueError): continue return values
def _event_record(item: Any, kind: str) -> dict[str, Any]: if kind == "ftcp": return { "adapter": "QGITAMarketAnalyzer.analyze", "curvature": float(item.curvature), "is_valid": bool(item.is_valid), "kind": "FTCP", "knot_index": int(item.knot_index), "timestamp": float(item.timestamp), } return { "adapter": "QGITAMarketAnalyzer.analyze", "event_type": str(item.event_type.value), "kind": "lighthouse", "lighthouse_intensity": float(item.lighthouse_intensity), "timestamp": float(item.timestamp), }
@quietdef qgita_analyze( values: list[float] | None = None, timestamps: list[float] | None = None,) -> str: """Run QGITAMarketAnalyzer.analyze and drop the signals object.
Events are the adapter return, not a detection rate. Detection rate: HOLD. False-alarm rate: HOLD. The bundled series is cited-unverified and is not public market data.
Args: values: Optional series. Omitted loads the vendored de440 Lambda column. A supplied series is inferred and is not the committed replay. Length must be at least 10. Label: cited for the file, inferred for a pasted series. timestamps: Optional clocks, one per value. Omitted uses the sample index. Label: cited, the Space clock. """
supplied = values is not None series = list(values) if supplied else _lambda_column() if supplied: cleaned: list[float] = [] for item in series: number = _finite(item) if number is None: return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "label": "inferred", "reason": "A value is missing.", "status": "unavailable", } ) cleaned.append(number) series = cleaned if len(series) < 10: return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "label": "cited. analyze returns insufficient_data below 10 samples.", "reason": "At least ten values are required.", "status": "unavailable", } ) if timestamps is None: clocks = [float(index) for index in range(len(series))] clock_label = "cited. Sample index, the Space clock." else: if len(timestamps) != len(series): return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "label": "inferred", "reason": "timestamps and values differ in length.", "status": "unavailable", } ) clocks = [] for item in timestamps: number = _finite(item) if number is None: return _dumps( { "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "label": "inferred", "reason": "A timestamp is missing.", "status": "unavailable", } ) clocks.append(number) clock_label = "inferred. Caller-supplied clocks." from aureon.wisdom.aureon_qgita_framework import QGITAMarketAnalyzer
analyzer = QGITAMarketAnalyzer() for index, value in enumerate(series): analyzer.feed_price(float(value), timestamp=clocks[index]) raw = analyzer.analyze() stage1 = raw.get("stage1") if isinstance(raw.get("stage1"), dict) else {} stage2 = raw.get("stage2") if isinstance(raw.get("stage2"), dict) else {} valid = list(stage1.get("valid_ftcps") or []) events = list(stage2.get("lighthouse_events") or []) body: dict[str, Any] = { "clock": clock_label, "coherence": raw.get("coherence"), "detection_rate": "HOLD", "false_alarm_rate": "HOLD", "ftcp_count": stage1.get("ftcp_count"), "ftcps": [_event_record(item, "ftcp") for item in valid], "label": ( "cited-unverified bundled series. Not public market data." if not supplied else "inferred. Adapter run on the supplied series. Not the committed replay." ), "lhe_count": stage2.get("lhe_count"), "lighthouse_events": [_event_record(item, "lhe") for item in events], "regime": raw.get("regime"), "samples_fed": len(series), "status": raw.get("status", "unavailable"), } return _dumps(body)
@quietdef organism_replay_read() -> str: """Read the committed circulation replay file. This does not start a seat.
Connectivity figures are cited from the file. The fault block is seeded synthetic input, not telemetry. A claim that those faults are recorded seat faults is HOLD.
Args: none: This tool takes no inputs. Label: cited, huggingface/organism-replay/replay/organism.json. """
record = _load(paths.organism_json()) connectivity = record.get("connectivity") if isinstance(record.get("connectivity"), dict) else {} self_model = record.get("self_model") if isinstance(record.get("self_model"), dict) else {} prediction = self_model.get("prediction") if isinstance(self_model.get("prediction"), dict) else {} fault = self_model.get("fault") if isinstance(self_model.get("fault"), dict) else {} seats = connectivity.get("seats") if isinstance(connectivity.get("seats"), dict) else {} isolated = connectivity.get("isolated") topics = _dashboard_topics() return _dumps( { "cited": { "connected": connectivity.get("connected"), "connectivity_score": connectivity.get("score"), "http_seat_bound": connectivity.get("http_seat_bound"), "isolated": isolated, "label": "cited, huggingface/organism-replay/replay/organism.json", "prediction_accuracy": prediction.get("accuracy"), "prediction_baseline_accuracy": prediction.get("baseline_accuracy"), "roster": connectivity.get("roster"), "seats": seats, "verdict": connectivity.get("verdict"), }, "dashboard_topics": topics, "label": "cited replay file. Circulation was not started.", "seeded_synthetic_fault": { "detection_rate_in_file": fault.get("detection_rate"), "false_alarm_rate_in_file": fault.get("false_alarm_rate"), "hold": ( "A claim that these are recorded seat faults is HOLD. " "These figures are not a QGITA detection rate and not telemetry." ), "label": "Seeded synthetic input, not telemetry.", "origin": fault.get("origin"), "seed": fault.get("seed"), }, } )
def _dashboard_topics() -> list[str]: topics = ( "ics.body.state", "ics.mind.state", "ics.source.state", "ics.soul.state", "ics.hnc.state", "ics.monologue", ) try: from aureon.core.aureon_thought_bus import ThoughtBus from aureon.core.cognitive_dashboard import CognitiveDashboard
bus = ThoughtBus(persist_path=None) CognitiveDashboard(thought_bus=bus) except Exception: return [f"Dashboard topic {topic}: unavailable" for topic in topics] lines = [] for topic in topics: found = bus.recall(topic, limit=1) if found: lines.append(f"Dashboard topic {topic}: present in the replay") else: lines.append(f"Dashboard topic {topic}: unavailable") return lines
@quietdef organism_catalog() -> str: """List circulation seats, algorithmic nodes, and deterministic systems.
These are names in source. This tool does not start circulation, self-repair, or self-code. Label: cited.
Args: none: This tool takes no inputs. Label: cited, circulation_seats, list_nodes, and list_systems. """
from aureon.core.algorithmic_nodes import list_nodes from aureon.core.deterministic_systems import list_systems from aureon.core.organism_circulation import circulation_seats
return _dumps( { "label": "cited. Names in source. Seats are not running.", "nodes": list_nodes(), "seats": list(circulation_seats()), "systems": list_systems(), } ).dockerignoreAdded+9
COVERAGE_PLAN.mdAdded+225
DockerfileAdded+65
README.mdAdded+199
__init__.pyAdded+11
__main__.pyAdded+4
alignment_layer.pyAdded+387
alignment_measure.pyAdded+119
body.pyAdded+1405
body_sweep.pyAdded+43
call_sweep.pyAdded+359
call_worker.pyAdded+243
coverage_plan.pyAdded+506
guard_loader.pyAdded+181
http_guard.pyAdded+454
inventory_scan.pyAdded+405
layers.pyAdded+594
measure.pyAdded+202
measurement_stamp.pyAdded+81
more_layers.pyAdded+632
paths.pyAdded+50
pin_blob.pyAdded+350
protocol_measure.pyAdded+258
quiet.pyAdded+23
requirements.txtAdded+7
server.pyAdded+185
space.pyAdded+106
space_measure.pyAdded+240
stage1_measure.pyAdded+119
stage1_rest.pyAdded+531
stage2_arguments.pyAdded+306
stage2_import_sweep.pyAdded+226
stage2_layer.pyAdded+782
surfaces.pyAdded+279
sweep_guard.pyAdded+516
sweep_layout.pyAdded+116
test-requirements.txtAdded+8
text.pyAdded+26
tools.pyAdded+805