diff --git a/.cargo/audit.toml b/.cargo/audit.toml index 71b6cbeacb..89d8098765 100644 --- a/.cargo/audit.toml +++ b/.cargo/audit.toml @@ -2,13 +2,22 @@ # `ignore` is a list of advisory IDs. The schema has no reason field; # the reason and tracking issue live in the comment and in `deny.toml`. # -# Vulnerability IDs below have no upgrade that keeps the current parents. -# Unmaintained IDs have no patched release. Each one has a tracking issue. # zip 1.1.4 is gone. third_party/candle-core is crates.io candle-core 0.8.4 -# pinned to zip 9.0.3, the patched line for RUSTSEC-2026-0367, 0368, and 0369. +# pinned to zip 9.7.0, patched for the advisories it addresses. # Drop that directory and the [patch.crates-io] entry once candle upstream # depends on zip >= 9. No published candle release does, through 0.11.0. # https://github.com/lazyxeon/AstraWeave/issues/324 +# url is 2.5.9. form_urlencoded is 1.2.3, which that url release requires. +# quinn-udp is 0.5.16. chrono is not in the lock. zip is 9.7.0. +# PR #758. https://github.com/lazyxeon/AstraWeave/pull/758 +# #756 tracks the main audit failure. +# https://github.com/lazyxeon/AstraWeave/issues/756 +# privilege escalation, RUSTSEC-2026-0548 (zip) +# denial of service, RUSTSEC-2026-0538 (quinn-udp) +# unmaintained, RUSTSEC-2026-0543 (chrono) +# url 2.5.9 also fixes stack overflow, RUSTSEC-2026-0592, a later advisory. None of these is an ignore. +# The IDs in the ignore array below are unmaintained. There is no patched release. +# Each one has a tracking issue. [advisories] ignore = [ diff --git a/.github/workflows/aw-editor-tests.yml b/.github/workflows/aw-editor-tests.yml index 60e58557f7..127a3902b4 100644 --- a/.github/workflows/aw-editor-tests.yml +++ b/.github/workflows/aw-editor-tests.yml @@ -25,9 +25,7 @@ jobs: test: name: Test AW Editor (${{ matrix.os }}) runs-on: ${{ matrix.os }} - timeout-minutes: 45 - # Skip if editor has known compilation issues - allows CI to pass while editor is being fixed - continue-on-error: true + timeout-minutes: 75 strategy: fail-fast: false matrix: @@ -62,7 +60,17 @@ jobs: # Run library unit tests (headless tests work everywhere) - name: Run Unit Tests run: cargo test -p aw_editor --lib --all-features -- --nocapture - continue-on-error: true # Don't fail CI on test failures (89% pass rate acceptable) + continue-on-error: true # Kept from the previous policy. The bin step fails the job. + + # Bin harness for aw_editor only (`--bin aw_editor`). ci.yml job + # Test (ubuntu, build archive) runs + # `cargo test --locked -p aw_editor --all-features --bins`, which also + # builds the aw_game_runtime harness. That harness has no tests. + # This workflow is not on pull_request. PR Rust checks needs the + # archive job. Ruleset enforcement is PR #702 + # (https://github.com/lazyxeon/AstraWeave/pull/702). + - name: Run editor bin tests + run: cargo test -p aw_editor --all-features --bin aw_editor -- --nocapture # Run integration tests (require headless environment) - name: Run Integration Tests @@ -73,11 +81,11 @@ jobs: # Code quality checks - name: Check Formatting run: cargo fmt -p aw_editor -- --check - continue-on-error: true # Don't block on format issues + continue-on-error: true # Kept from the previous policy. - name: Run Clippy run: cargo clippy -p aw_editor --all-features -- -D warnings - continue-on-error: true # Don't block on lints (52 warnings exist) + continue-on-error: true # Kept from the previous policy. editor-ci.yml enforces clippy -D warnings. # Generate test report - name: Generate Test Summary @@ -88,13 +96,10 @@ jobs: echo "**Platform**: ${{ matrix.os }}" >> $GITHUB_STEP_SUMMARY echo "**Rust Version**: $(rustc --version)" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - echo "### Test Coverage" >> $GITHUB_STEP_SUMMARY - echo "- **Unit Tests**: 146/164 passing (89%)" >> $GITHUB_STEP_SUMMARY - echo "- **Integration Tests**: 9 test files (ui_gizmo_smoke, play_mode, prefab_workflow, etc.)" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "### Known Issues" >> $GITHUB_STEP_SUMMARY - echo "- 18 unit test failures (gizmo math, undo stack, scene serialization)" >> $GITHUB_STEP_SUMMARY - echo "- 52 warnings (dead code, unused fields - tracked in Known Issues)" >> $GITHUB_STEP_SUMMARY + echo "### Steps" >> $GITHUB_STEP_SUMMARY + echo "- Bin tests: cargo test -p aw_editor --all-features --bin aw_editor fails the job. The harness includes the library modules redeclared by src/main.rs, not only recovery_tests and voxel_tools." >> $GITHUB_STEP_SUMMARY + echo "- The test job keeps continue-on-error on --lib, integration, fmt, and clippy. The coverage job keeps it on Generate Coverage Report and Upload Coverage to Codecov." >> $GITHUB_STEP_SUMMARY + echo "- A pull request that is not docs-only, and whose affected set is the full workspace or at least one package, runs cargo test --locked -p aw_editor --all-features --bins in ci.yml, job Test (ubuntu, build archive). PR Rust checks needs that job. Ruleset enforcement is PR #702, https://github.com/lazyxeon/AstraWeave/pull/702. The step has no continue-on-error. --bins also builds the aw_game_runtime harness, which has no tests." >> $GITHUB_STEP_SUMMARY # Coverage job (optional - Linux only for speed) coverage: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb9763c784..0cf64246c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,15 @@ name: Comprehensive CI Pipeline # Determinism Replay, which is a separate workflow with no path filter. # Heavy optional workflows (PBR, editor, AW Editor tests) are not on # pull_request, so they do not occupy runners ahead of this workflow. +# The aw_editor bin harness is a step of Test (ubuntu, build archive), +# which the PR Rust checks job needs. Ruleset enforcement is tracked in +# PR #702, https://github.com/lazyxeon/AstraWeave/pull/702. That job is skipped +# on a docs-only pull request and when no crate is selected +# (`full` is not set and the package list is empty). +# The step runs `cargo test --locked -p aw_editor --all-features --bins` +# with no continue-on-error. `--bins` builds every bin harness, including +# aw_game_runtime (test = false, and that harness has no tests). +# editor-ci.yml and aw-editor-tests.yml stay off pull_request. # # Main, schedule, and workflow_dispatch: the same gate against the full # workspace, then the 3-OS test matrix and a release build. Sanitizers, @@ -141,10 +150,11 @@ jobs: # 60, not 45. Run 40235303264 compiled the test profile in 24m 12s and # then spent 6m 05s running 31672 tests. A dev-profile aw_audio_probe # before that compile took another 7m 15s and could not be reused. - # This job compiles once (debuginfo off, same as the Windows archive), - # builds the probe with the test profile, and uploads both. Partition - # jobs do not compile. The archive is not built inside the gate: that - # would hold the Windows archive until this compile finished. + # The nextest archive is one compile (debuginfo off). The editor bin + # step compiles aw_editor again with --all-features. Run 44916883830 + # spent 6m 06s on that step and 37m 24s on this job. Partition jobs do + # not compile. The archive is not built inside the gate: that would + # hold the Windows archive until this compile finished. timeout-minutes: 60 if: >- github.event_name == 'pull_request' && @@ -240,6 +250,28 @@ jobs: echo "Model crates are not in the affected set; skipping the ollama feature tests" fi + - name: Feature-gated tests + # After the archive upload so a feature rebuild does not hold the artifact. + # The default archive does not pass --features bevy or --features metrics. + env: + CARGO_PROFILE_TEST_DEBUG: "0" + AW_CI_FULL: ${{ needs.changes.outputs.full }} + AW_CI_PACKAGES: ${{ needs.changes.outputs.packages }} + AW_CI_PROFILE: ci-pr + run: bash scripts/ci/feature-gated-tests.sh + + - name: Editor bin tests + # aw_editor stays in EXCLUDED_PACKAGES, so the archive does not run + # these. recovery_tests and voxel_tools compile only in this bin. + # --all-features matches editor-ci. The feature set is fixed in the + # lock (including profiling/tracy-client). It is not a replay hash. + # `--bins` builds every bin harness. aw_game_runtime has test = false + # and no #[test], so its harness runs 0 tests. Cargo 1.89 does not + # skip test = false when --bins selects the target. + env: + CARGO_PROFILE_TEST_DEBUG: "0" + run: cargo test --locked -p aw_editor --all-features --bins + test-linux: name: Test (ubuntu, ${{ matrix.partition }}/3) runs-on: ubuntu-latest @@ -360,6 +392,16 @@ jobs: echo "Model crates are not in the affected set; skipping the model HTTP probes" fi + - name: Feature-gated tests + # After the archive upload. Keep the archive profile so this does not + # rebuild with debug info. + env: + CARGO_PROFILE_TEST_DEBUG: "0" + AW_CI_FULL: ${{ needs.changes.outputs.full }} + AW_CI_PACKAGES: ${{ needs.changes.outputs.packages }} + AW_CI_PROFILE: ci + run: bash scripts/ci/feature-gated-tests.sh + test-windows: name: Test (windows, ${{ matrix.partition }}/3) runs-on: windows-latest @@ -528,6 +570,12 @@ jobs: AW_CI_EXCLUDES: ${{ env.EXCLUDED_PACKAGES }} run: bash scripts/ci/run-tests.sh + - name: Feature-gated tests + env: + AW_CI_FULL: "true" + AW_CI_PROFILE: ci + run: bash scripts/ci/feature-gated-tests.sh + - name: Report GPU skips if: always() shell: bash @@ -595,6 +643,13 @@ jobs: cargo nextest run --locked --profile ci -p astraweave-llm --features ollama --test loopback_http_proxy --test ollama_chat_probe cargo nextest run --locked --profile ci -p astraweave-llm --features ollama --lib ollama_assembled + - name: Feature-gated tests + env: + CARGO_PROFILE_TEST_DEBUG: "0" + AW_CI_FULL: "true" + AW_CI_PROFILE: ci + run: bash scripts/ci/feature-gated-tests.sh + test-full-windows-part: name: Test full (windows, ${{ matrix.partition }}/3) runs-on: windows-latest diff --git a/.github/workflows/editor-ci.yml b/.github/workflows/editor-ci.yml index 2d05fdac7b..6c02871484 100644 --- a/.github/workflows/editor-ci.yml +++ b/.github/workflows/editor-ci.yml @@ -27,9 +27,7 @@ jobs: editor-ci: name: editor-ci runs-on: ubuntu-latest - timeout-minutes: 45 - # Skip if editor has known compilation issues - continue-on-error: true + timeout-minutes: 75 steps: - name: Checkout repository @@ -53,6 +51,15 @@ jobs: - name: Unit tests run: cargo test -p aw_editor --all-features --lib -- --nocapture + - name: Editor bin tests + # This workflow stays off pull_request. ci.yml job + # Test (ubuntu, build archive) runs + # `cargo test --locked -p aw_editor --all-features --bins`. + # `--bins` also builds the aw_game_runtime harness, which has no + # tests. PR Rust checks needs that job. Ruleset enforcement is + # PR #702, https://github.com/lazyxeon/AstraWeave/pull/702. + run: cargo test -p aw_editor --all-features --bin aw_editor -- --nocapture + - name: Headless smoke tests run: > cargo test -p aw_editor --all-features diff --git a/.github/workflows/toolchain-management.yml b/.github/workflows/toolchain-management.yml index d556b4230b..2f0dd511cb 100644 --- a/.github/workflows/toolchain-management.yml +++ b/.github/workflows/toolchain-management.yml @@ -155,9 +155,17 @@ jobs: # runner's libvulkan1 is new enough (#434). # aw_headless also builds InstanceDescriptor::default() and forbids # unsafe, so it cannot include that constructor. Its lib tests run - # below with RUST_TEST_THREADS=1. aw_editor is in EXCLUDED_PACKAGES; - # editor-ci.yml still runs its tests with continue-on-error, so this - # hook is not workspace-wide. + # below with RUST_TEST_THREADS=1. aw_editor stays in EXCLUDED_PACKAGES, + # so this hook does not run it. Pull requests run + # `cargo test --locked -p aw_editor --all-features --bins` in ci.yml + # job Test (ubuntu, build archive), with no continue-on-error. + # `--bins` also builds the aw_game_runtime harness (test = false, + # no tests). PR Rust checks needs that job. Ruleset enforcement + # is PR #702, https://github.com/lazyxeon/AstraWeave/pull/702. The job + # is skipped on a docs-only pull request and when no crate + # is selected (`full` is not set and the package list is empty). + # editor-ci.yml has no continue-on-error. It runs on push to main, + # the 06:50 UTC schedule, and workflow_dispatch, not on pull_request. # runner.os, not `uname`: windows-latest runs this file under # PowerShell, which does not evaluate a bash `if`. cargo test --locked --workspace --lib ${{ env.EXCLUDED_PACKAGES }} --exclude aw_headless diff --git a/Cargo.lock b/Cargo.lock index 842a44af20..b8dfbe4588 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -52,6 +52,7 @@ dependencies = [ "cipher", "cpubits", "cpufeatures 0.3.1", + "zeroize", ] [[package]] @@ -572,7 +573,6 @@ dependencies = [ "anyhow", "assert_fs", "async-trait", - "chrono", "clap", "futures-util", "hex", @@ -587,6 +587,7 @@ dependencies = [ "sha2 0.10.9", "tempfile", "thiserror 2.0.17", + "time", "tokio", "toml 0.8.23", "wiremock", @@ -746,11 +747,11 @@ version = "0.1.0" dependencies = [ "anyhow", "astraweave-context", + "astraweave-embeddings", "astraweave-llm", "astraweave-prompts", "astraweave-rag", "async-trait", - "chrono", "criterion 0.5.1", "dashmap", "futures", @@ -758,6 +759,7 @@ dependencies = [ "rand 0.9.5", "serde", "serde_json", + "time", "tokio", "tracing", "uuid", @@ -969,7 +971,6 @@ dependencies = [ "candle-core", "candle-nn", "candle-transformers", - "chrono", "criterion 0.7.0", "dashmap", "env_logger", @@ -982,6 +983,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "time", "tokenizers", "tokio", "tracing", @@ -1050,13 +1052,13 @@ dependencies = [ "astraweave-rag", "async-trait", "bevy_ecs", - "chrono", "criterion 0.7.0", "dashmap", "futures", "rusqlite", "serde", "serde_json", + "time", "tokio", "tracing", "uuid", @@ -1138,7 +1140,6 @@ dependencies = [ "anyhow", "astraweave-ecs", "async-trait", - "chrono", "criterion 0.5.1", "dashmap", "hdrhistogram", @@ -1150,6 +1151,7 @@ dependencies = [ "serde_json", "tempfile", "thiserror 2.0.17", + "time", "tokio", "tracing", "tracing-subscriber", @@ -1163,13 +1165,13 @@ dependencies = [ "anyhow", "astraweave-llm", "async-trait", - "chrono", "criterion 0.5.1", "dashmap", "futures", "lru", "serde", "serde_json", + "time", "tokio", "tokio-util", "tracing", @@ -1215,13 +1217,13 @@ name = "astraweave-persistence-player" version = "0.1.0" dependencies = [ "anyhow", - "chrono", "criterion 0.5.1", "postcard", "serde", "serde_bytes", "serde_json", "tempfile", + "time", "toml 0.8.23", ] @@ -1238,12 +1240,12 @@ dependencies = [ "astraweave-prompts", "astraweave-rag", "async-trait", - "chrono", "criterion 0.7.0", "rand 0.9.5", "serde", "serde_json", "tempfile", + "time", "tokio", "toml 0.9.8", "uuid", @@ -1291,7 +1293,6 @@ dependencies = [ "anyhow", "astraweave-core", "astraweave-llm", - "chrono", "criterion 0.7.0", "handlebars", "jsonschema", @@ -1302,6 +1303,7 @@ dependencies = [ "serde_json", "tempfile", "thiserror 2.0.17", + "time", "tokio-test", "toml 0.9.8", "uuid", @@ -1318,7 +1320,6 @@ dependencies = [ "astraweave-llm", "astraweave-prompts", "astraweave-rag", - "chrono", "criterion 0.5.1", "futures", "rand 0.9.5", @@ -1340,7 +1341,6 @@ dependencies = [ "astraweave-llm", "astraweave-prompts", "async-trait", - "chrono", "criterion 0.7.0", "dashmap", "fuzzy-matcher", @@ -1349,6 +1349,7 @@ dependencies = [ "rand 0.9.5", "serde", "serde_json", + "time", "tokio", "tokio-test", "uuid", @@ -1842,7 +1843,6 @@ dependencies = [ "astraweave-asset", "astraweave-security", "base64 0.22.1", - "chrono", "clap", "flate2", "glob", @@ -1855,6 +1855,7 @@ dependencies = [ "serde_json", "sha2 0.10.9", "thiserror 2.0.17", + "time", "toml 0.9.8", "uuid", "walkdir", @@ -1958,7 +1959,6 @@ dependencies = [ "astraweave-security", "astraweave-terrain", "bytemuck", - "chrono", "clap", "crc32fast", "criterion 0.5.1", @@ -1989,6 +1989,7 @@ dependencies = [ "sha2 0.10.9", "tempfile", "thiserror 2.0.17", + "time", "tokio", "toml 0.9.8", "tracing", @@ -2823,20 +2824,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", -] - [[package]] name = "ciborium" version = "0.2.2" @@ -4629,9 +4616,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -5550,16 +5537,17 @@ dependencies = [ "astraweave-terrain", "astraweave-ui", "bytemuck", - "chrono", "egui", "egui-wgpu", "egui-winit", "glam 0.30.8", + "mutants", "pollster", "rand 0.9.5", "reqwest", "serde", "serde_json", + "time", "tokio", "wgpu", "winit", @@ -5782,30 +5770,6 @@ dependencies = [ "windows-registry", ] -[[package]] -name = "iana-time-zone" -version = "0.1.64" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core 0.62.2", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.0.0" @@ -6656,9 +6620,9 @@ dependencies = [ [[package]] name = "lzma-rust2" -version = "0.21.0" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fde178a3caf126c440fa15628147772d8ee590a39477d711353fbe2e58a73a5b" +checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890" dependencies = [ "sha2 0.11.1", ] @@ -6923,6 +6887,12 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "mutants" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add0ac067452ff1aca8c5002111bd6b1c895baee6e45fcbc44e0193aea17be56" + [[package]] name = "naga" version = "25.0.1" @@ -7368,6 +7338,15 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + [[package]] name = "objc" version = "0.2.7" @@ -8564,9 +8543,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.14" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", @@ -10387,7 +10366,9 @@ checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", "js-sys", + "libc", "num-conv", + "num_threads", "powerfmt", "serde_core", "time-core", @@ -10930,9 +10911,9 @@ dependencies = [ [[package]] name = "typed-path" -version = "0.12.3" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" [[package]] name = "typeid" @@ -11085,9 +11066,9 @@ checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" [[package]] name = "url" -version = "2.5.7" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -11963,19 +11944,6 @@ dependencies = [ "windows-strings 0.4.2", ] -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement 0.60.2", - "windows-interface 0.59.3", - "windows-link 0.2.1", - "windows-result 0.4.1", - "windows-strings 0.5.1", -] - [[package]] name = "windows-future" version = "0.2.1" @@ -12091,15 +12059,6 @@ dependencies = [ "windows-link 0.1.3", ] -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link 0.2.1", -] - [[package]] name = "windows-strings" version = "0.1.0" @@ -12119,15 +12078,6 @@ dependencies = [ "windows-link 0.1.3", ] -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link 0.2.1", -] - [[package]] name = "windows-sys" version = "0.45.0" @@ -12782,9 +12732,23 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] [[package]] name = "zerotrie" @@ -12821,9 +12785,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.0.3" +version = "9.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2d98561b612a84ae525331a7a094429ef8a5772514ed507ff6db5f54badc971" +checksum = "08687262e7c0f1284b259686f322805a8adaa8ef4d7210e76448950b3f083bf7" dependencies = [ "aes", "bzip2", @@ -12834,6 +12798,7 @@ dependencies = [ "getrandom 0.4.3", "hmac 0.13.0", "indexmap", + "libc", "lzma-rust2", "memchr", "nix 0.31.3", @@ -12842,6 +12807,7 @@ dependencies = [ "sha1 0.11.0", "time", "typed-path", + "windows-sys 0.61.2", "zeroize", "zopfli", "zstd", diff --git a/Cargo.toml b/Cargo.toml index 96e99cf609..e70590d9c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -181,7 +181,7 @@ thiserror = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "0.9" -zip = "9.0" +zip = "9.7.0" rand = "0.9" rand_chacha = "0.9" approx = "0.5" @@ -303,10 +303,9 @@ debug = false incremental = false # third_party/candle-core exists because candle-core 0.8.4, candle 0.11.0, -# and current candle main all depend on zip < 9. RUSTSEC-2026-0367, 0368, -# and 0369 are patched only in zip >= 9.0.0. This copy is crates.io 0.8.4 -# pinned to the workspace zip 9.0.3. Delete this directory and the patch -# below once candle upstream depends on zip >= 9. Asset packs stay on 9.0.3. +# and current candle main all depend on zip < 9. This copy is crates.io 0.8.4 +# pinned to workspace zip 9.7.0, patched for the advisories it addresses. Delete this +# directory and the patch below once candle upstream depends on zip >= 9. # # Rapier 0.22 `PhysicsPipeline::step` takes the modified-body and # modified-collider Vecs and drops them. The next step then grows a new diff --git a/astraweave-coordination/Cargo.toml b/astraweave-coordination/Cargo.toml index 2514e9e7db..8983af19b8 100644 --- a/astraweave-coordination/Cargo.toml +++ b/astraweave-coordination/Cargo.toml @@ -20,11 +20,12 @@ tokio = { workspace = true } tracing = { workspace = true } futures = "0.3" uuid = { version = "1.0", features = ["v4"] } -chrono = { version = "0.4", features = ["serde"] } +time = { version = "0.3", features = ["parsing"] } dashmap = "6.0" petgraph = "0.6" async-trait = "0.1" rand = { workspace = true } [dev-dependencies] -criterion = { version = "0.5", features = ["html_reports"] } \ No newline at end of file +astraweave-embeddings = { path = "../astraweave-embeddings" } +criterion = { version = "0.5", features = ["html_reports"] } diff --git a/astraweave-coordination/src/agent.rs b/astraweave-coordination/src/agent.rs index 8aab6e528a..203b1e8019 100644 --- a/astraweave-coordination/src/agent.rs +++ b/astraweave-coordination/src/agent.rs @@ -1,6 +1,5 @@ use anyhow::Result; use async_trait::async_trait; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::Arc; @@ -77,7 +76,8 @@ pub struct AgentMessage { pub to: String, pub message_type: MessageType, pub content: serde_json::Value, - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, pub priority: MessagePriority, pub reply_to: Option, } @@ -114,7 +114,8 @@ pub struct AgentGoal { pub priority: f32, pub target_value: Option, pub current_value: f32, - pub deadline: Option>, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub deadline: Option, pub dependencies: Vec, // Goal IDs this depends on pub status: GoalStatus, } @@ -150,7 +151,8 @@ pub struct Task { pub parameters: HashMap, pub priority: f32, pub estimated_duration: Option, // milliseconds - pub deadline: Option>, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub deadline: Option, pub required_capabilities: Vec, pub resource_requirements: ResourceRequirements, } @@ -186,13 +188,26 @@ pub struct SideEffect { } /// Current resource usage by an agent -#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ResourceUsage { pub llm_calls_per_minute: u32, pub memory_mb: u32, pub active_tasks: u32, pub queue_size: u32, - pub last_activity: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_activity: time::OffsetDateTime, +} + +impl Default for ResourceUsage { + fn default() -> Self { + Self { + llm_calls_per_minute: 0, + memory_mb: 0, + active_tasks: 0, + queue_size: 0, + last_activity: time::OffsetDateTime::UNIX_EPOCH, + } + } } /// World event that agents can react to @@ -204,7 +219,8 @@ pub struct WorldEvent { pub location: Option, pub participants: Vec, pub event_data: serde_json::Value, - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, pub severity: EventSeverity, } @@ -240,8 +256,10 @@ pub struct CoordinationContext { pub participants: Vec, // Agent IDs pub shared_state: HashMap, pub coordination_goals: Vec, - pub start_time: DateTime, - pub last_update: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub start_time: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_update: time::OffsetDateTime, pub status: CoordinationStatus, } @@ -319,7 +337,7 @@ impl BaseAgent { to: original.from.clone(), message_type: MessageType::Response, content, - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: original.priority.clone(), reply_to: Some(original.id.clone()), } @@ -338,7 +356,7 @@ impl BaseAgent { to, message_type: MessageType::Notification, content, - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority, reply_to: None, } @@ -347,7 +365,7 @@ impl BaseAgent { /// Update resource usage pub fn update_resource_usage(&mut self, usage: ResourceUsage) { self.resource_usage = usage; - self.resource_usage.last_activity = Utc::now(); + self.resource_usage.last_activity = time::OffsetDateTime::now_utc(); } /// Check if agent is available for new tasks @@ -370,7 +388,7 @@ impl BaseAgent { let mut ctx = context.write().await; if !ctx.participants.contains(&self.id) { ctx.participants.push(self.id.clone()); - ctx.last_update = Utc::now(); + ctx.last_update = time::OffsetDateTime::now_utc(); } self.coordination_context = Some(context.clone()); info!( @@ -385,7 +403,7 @@ impl BaseAgent { if let Some(context) = &self.coordination_context { let mut ctx = context.write().await; ctx.participants.retain(|id| id != &self.id); - ctx.last_update = Utc::now(); + ctx.last_update = time::OffsetDateTime::now_utc(); info!( "Agent {} left coordination session {}", self.id, ctx.session_id @@ -400,7 +418,7 @@ impl BaseAgent { if let Some(context) = &self.coordination_context { let mut ctx = context.write().await; ctx.shared_state.insert(key, value); - ctx.last_update = Utc::now(); + ctx.last_update = time::OffsetDateTime::now_utc(); } Ok(()) } @@ -466,8 +484,12 @@ impl AgentGoal { /// Check if goal is overdue pub fn is_overdue(&self) -> bool { + self.is_overdue_at(time::OffsetDateTime::now_utc()) + } + + pub fn is_overdue_at(&self, now: time::OffsetDateTime) -> bool { if let Some(deadline) = &self.deadline { - Utc::now() > *deadline && self.status != GoalStatus::Completed + now > *deadline && self.status != GoalStatus::Completed } else { false } @@ -510,8 +532,12 @@ impl Task { /// Check if task is overdue pub fn is_overdue(&self) -> bool { + self.is_overdue_at(time::OffsetDateTime::now_utc()) + } + + pub fn is_overdue_at(&self, now: time::OffsetDateTime) -> bool { if let Some(deadline) = &self.deadline { - Utc::now() > *deadline + now > *deadline } else { false } @@ -564,7 +590,7 @@ mod tests { to: agent.id.clone(), message_type: MessageType::Request, content: serde_json::json!({"test": "data"}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: MessagePriority::Normal, reply_to: None, }; @@ -585,8 +611,8 @@ mod tests { participants: Vec::new(), shared_state: HashMap::new(), coordination_goals: Vec::new(), - start_time: Utc::now(), - last_update: Utc::now(), + start_time: time::OffsetDateTime::now_utc(), + last_update: time::OffsetDateTime::now_utc(), status: CoordinationStatus::Planning, })); @@ -661,8 +687,8 @@ mod tests { participants: Vec::new(), shared_state: HashMap::new(), coordination_goals: Vec::new(), - start_time: Utc::now(), - last_update: Utc::now(), + start_time: time::OffsetDateTime::now_utc(), + last_update: time::OffsetDateTime::now_utc(), status: CoordinationStatus::Planning, })); @@ -772,7 +798,7 @@ mod tests { // Targets: agent.rs L470 > → >= in is_overdue // Past deadline + Active → true let mut goal = AgentGoal::new("g".into(), GoalType::Achieve, 0.5); - goal.deadline = Some(Utc::now() - chrono::Duration::hours(1)); + goal.deadline = Some(time::OffsetDateTime::now_utc() - time::Duration::hours(1)); goal.status = GoalStatus::Active; assert!( goal.is_overdue(), @@ -788,7 +814,7 @@ mod tests { // Future deadline + Active → false let mut goal2 = AgentGoal::new("g2".into(), GoalType::Achieve, 0.5); - goal2.deadline = Some(Utc::now() + chrono::Duration::hours(1)); + goal2.deadline = Some(time::OffsetDateTime::now_utc() + time::Duration::hours(1)); goal2.status = GoalStatus::Active; assert!(!goal2.is_overdue(), "Future deadline should NOT be overdue"); @@ -802,16 +828,46 @@ mod tests { // Targets: agent.rs L514 > → >= in Task::is_overdue // Past deadline → true let mut task = Task::new("t".into(), "d".into()); - task.deadline = Some(Utc::now() - chrono::Duration::hours(1)); + task.deadline = Some(time::OffsetDateTime::now_utc() - time::Duration::hours(1)); assert!(task.is_overdue(), "Past deadline should be overdue"); // Future deadline → false let mut task2 = Task::new("t2".into(), "d".into()); - task2.deadline = Some(Utc::now() + chrono::Duration::hours(1)); + task2.deadline = Some(time::OffsetDateTime::now_utc() + time::Duration::hours(1)); assert!(!task2.is_overdue(), "Future deadline should NOT be overdue"); // No deadline → false let task3 = Task::new("t3".into(), "d".into()); assert!(!task3.is_overdue(), "No deadline should NOT be overdue"); } + + #[test] + fn deadline_equal_to_now_is_not_overdue() { + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(1_700_000_000); + let mut goal = AgentGoal::new("g".into(), GoalType::Achieve, 0.5); + goal.deadline = Some(now); + goal.status = GoalStatus::Active; + assert!(!goal.is_overdue_at(now)); + assert!(goal.is_overdue_at(now + time::Duration::nanoseconds(1))); + assert!(!goal.is_overdue_at(now - time::Duration::seconds(1))); + goal.status = GoalStatus::Completed; + assert!(!goal.is_overdue_at(now + time::Duration::hours(1))); + goal.deadline = None; + goal.status = GoalStatus::Active; + assert!(!goal.is_overdue_at(now + time::Duration::hours(1))); + + let mut task = Task::new("t".into(), "d".into()); + task.deadline = Some(now); + assert!(!task.is_overdue_at(now)); + assert!(task.is_overdue_at(now + time::Duration::nanoseconds(1))); + assert!(!task.is_overdue_at(now - time::Duration::seconds(1))); + task.deadline = None; + assert!(!task.is_overdue_at(now + time::Duration::hours(1))); + + goal.deadline = Some(time::OffsetDateTime::UNIX_EPOCH); + goal.status = GoalStatus::Active; + assert!(goal.is_overdue()); + task.deadline = Some(time::OffsetDateTime::now_utc() + time::Duration::hours(48)); + assert!(!task.is_overdue()); + } } diff --git a/astraweave-coordination/src/coordination.rs b/astraweave-coordination/src/coordination.rs index 366506ec27..ed7b56102c 100644 --- a/astraweave-coordination/src/coordination.rs +++ b/astraweave-coordination/src/coordination.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::Arc; @@ -124,8 +123,10 @@ pub struct ResourceAllocation { pub llm_calls_used: u32, pub memory_allocated: u32, pub memory_used: u32, - pub allocated_at: DateTime, - pub expires_at: Option>, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub allocated_at: time::OffsetDateTime, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub expires_at: Option, } /// System-wide resource limits @@ -368,8 +369,8 @@ impl AgentCoordinator { participants: participant_ids.clone(), shared_state: HashMap::new(), coordination_goals: goals, - start_time: Utc::now(), - last_update: Utc::now(), + start_time: time::OffsetDateTime::now_utc(), + last_update: time::OffsetDateTime::now_utc(), status: CoordinationStatus::Planning, })); @@ -418,7 +419,7 @@ impl AgentCoordinator { { let mut ctx = context.write().await; ctx.status = CoordinationStatus::Completed; - ctx.last_update = Utc::now(); + ctx.last_update = time::OffsetDateTime::now_utc(); } // Remove agents from session @@ -560,7 +561,7 @@ impl AgentCoordinator { let mut ctx = context.write().await; if ctx.participants.contains(&agent_id.to_string()) { ctx.participants.retain(|id| id != agent_id); - ctx.last_update = Utc::now(); + ctx.last_update = time::OffsetDateTime::now_utc(); debug!("Removed agent {} from session {}", agent_id, session_id); } } @@ -590,14 +591,14 @@ impl AgentCoordinator { /// Clean up expired coordination sessions async fn cleanup_expired_sessions(&self) { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut sessions = self.coordination_sessions.write().await; sessions.retain(|session_id, context| { let ctx = context.try_read(); if let Ok(ctx) = ctx { let duration = now - ctx.start_time; - let keep = duration.to_std().unwrap_or(Duration::ZERO) + let keep = crate::utc_stamp::saturating_std(duration, Duration::ZERO) < self.config.max_coordination_duration; if !keep { debug!("Cleaning up expired coordination session {}", session_id); @@ -753,7 +754,7 @@ impl ResourceManager { llm_calls_used: 0, memory_allocated: self.limits.total_memory_mb / 10, memory_used: 0, - allocated_at: Utc::now(), + allocated_at: time::OffsetDateTime::now_utc(), expires_at: None, }; @@ -802,11 +803,11 @@ impl ResourceManager { async fn update_allocations(&self) { // Reset usage counters periodically - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut allocations = self.allocations.write().await; for allocation in allocations.values_mut() { - if (now - allocation.allocated_at).num_minutes() >= 1 { + if (now - allocation.allocated_at).whole_minutes() >= 1 { allocation.llm_calls_used = 0; allocation.allocated_at = now; } @@ -997,7 +998,7 @@ mod tests { to: "b".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1024,7 +1025,7 @@ mod tests { to: "target".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1041,7 +1042,7 @@ mod tests { to: "target".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({"hello": true}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1060,7 +1061,7 @@ mod tests { to: "nonexistent".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1085,7 +1086,7 @@ mod tests { to: "player".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1095,7 +1096,7 @@ mod tests { to: "npc-guard".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1114,7 +1115,7 @@ mod tests { to: "t".into(), message_type: crate::agent::MessageType::Notification, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Low, reply_to: None, }; @@ -1227,7 +1228,7 @@ mod tests { location: None, participants: vec![], event_data: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: crate::agent::EventSeverity::Minor, }; let interested = ed.get_interested_agents(&event).await; @@ -1248,7 +1249,7 @@ mod tests { location: None, participants: vec![], event_data: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: crate::agent::EventSeverity::Trivial, }; let interested = ed.get_interested_agents(&event).await; @@ -1268,7 +1269,7 @@ mod tests { location: None, participants: vec![], event_data: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: crate::agent::EventSeverity::Major, }; let interested = ed.get_interested_agents(&event).await; @@ -1285,7 +1286,7 @@ mod tests { location: Some("town".into()), participants: vec!["hero".into()], event_data: serde_json::json!({"x": 1}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: crate::agent::EventSeverity::Moderate, }; ed.store_event(event).await; @@ -1407,7 +1408,7 @@ mod tests { location: None, participants: vec![], event_data: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: crate::agent::EventSeverity::Major, }; coordinator.dispatch_event(event).await.unwrap(); @@ -1469,7 +1470,7 @@ mod tests { to: agent_id, message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1506,7 +1507,7 @@ mod tests { to: "target".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1532,7 +1533,7 @@ mod tests { to: "nonexistent".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1769,7 +1770,7 @@ mod tests { .expect("expired session") .write() .await; - ctx.start_time = Utc::now() - chrono::Duration::seconds(60); + ctx.start_time = time::OffsetDateTime::now_utc() - time::Duration::seconds(60); } // A session started now stays inside the 30s window. A 1ms window @@ -1879,7 +1880,7 @@ mod tests { location: None, participants: vec![], event_data: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: crate::agent::EventSeverity::Major, }; @@ -1952,7 +1953,7 @@ mod tests { to: "npc-guard".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1962,7 +1963,7 @@ mod tests { to: "merchant".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -1992,7 +1993,7 @@ mod tests { to: "b".into(), message_type: crate::agent::MessageType::Request, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -2002,7 +2003,7 @@ mod tests { to: "b".into(), message_type: crate::agent::MessageType::Response, content: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: crate::agent::MessagePriority::Normal, reply_to: None, }; @@ -2074,7 +2075,7 @@ mod tests { location: None, participants: vec![], event_data: serde_json::json!({}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: crate::agent::EventSeverity::Trivial, }; ed.store_event(event).await; @@ -2116,4 +2117,35 @@ mod tests { "Recent allocation usage should NOT be reset (kills >= → <)" ); } + + #[tokio::test] + async fn update_allocations_clears_usage_after_a_minute() { + let coordinator = AgentCoordinator::new(CoordinatorConfig::default()); + let agent = TestAgent { + base: BaseAgent::new("old".into(), vec![]), + }; + let agent_id = agent.agent_id().to_string(); + coordinator.register_agent(Box::new(agent)).await.unwrap(); + let req = crate::agent::ResourceRequirements { + llm_calls: 7, + memory_mb: 1, + compute_units: 0, + exclusive_resources: vec![], + }; + coordinator + .resource_manager + .allocate_resources(&agent_id, &req) + .await + .unwrap(); + { + let mut allocs = coordinator.resource_manager.allocations.write().await; + let alloc = allocs.get_mut(&agent_id).unwrap(); + alloc.allocated_at = time::OffsetDateTime::now_utc() - time::Duration::minutes(2); + } + coordinator.resource_manager.update_allocations().await; + let allocs = coordinator.resource_manager.allocations.read().await; + let alloc = allocs.get(&agent_id).unwrap(); + assert_eq!(alloc.llm_calls_used, 0); + assert!(alloc.allocated_at > time::OffsetDateTime::now_utc() - time::Duration::seconds(30)); + } } diff --git a/astraweave-coordination/src/lib.rs b/astraweave-coordination/src/lib.rs index f5c7328964..22aa7ab0dc 100644 --- a/astraweave-coordination/src/lib.rs +++ b/astraweave-coordination/src/lib.rs @@ -5,6 +5,8 @@ //! including NPCs, directors, dialogue systems, and quest generators. It handles //! coordination, resource sharing, and emergent group behaviors. +mod utc_stamp; + pub mod agent; pub use agent::*; diff --git a/astraweave-coordination/src/narrative_coherence.rs b/astraweave-coordination/src/narrative_coherence.rs index 878afe3d90..a07cceef8c 100644 --- a/astraweave-coordination/src/narrative_coherence.rs +++ b/astraweave-coordination/src/narrative_coherence.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::Arc; @@ -79,8 +78,10 @@ pub struct PlotPoint { pub related_characters: Vec, pub prerequisites: Vec, pub consequences: Vec, - pub introduced_at: DateTime, - pub deadline: Option>, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub introduced_at: time::OffsetDateTime, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub deadline: Option, } /// Types of plot points @@ -137,7 +138,8 @@ pub struct EmotionalChange { pub from_emotion: String, pub to_emotion: String, pub cause: String, - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, } /// Relationship between characters @@ -175,7 +177,8 @@ pub struct NarrativeEvent { pub participants: Vec, pub consequences: Vec, pub narrative_impact: f32, - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, pub location: Option, pub related_plot_points: Vec, } @@ -183,8 +186,10 @@ pub struct NarrativeEvent { /// Game timeline for temporal consistency #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Timeline { - pub current_time: DateTime, - pub game_start_time: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub current_time: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub game_start_time: time::OffsetDateTime, pub significant_dates: Vec, pub temporal_anchors: Vec, } @@ -192,7 +197,8 @@ pub struct Timeline { /// Significant event in the timeline #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TimelineEvent { - pub date: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub date: time::OffsetDateTime, pub title: String, pub description: String, pub importance: f32, @@ -204,7 +210,8 @@ pub struct TimelineEvent { pub struct TemporalAnchor { pub id: String, pub description: String, - pub fixed_date: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub fixed_date: time::OffsetDateTime, pub cannot_change: bool, pub related_events: Vec, } @@ -270,7 +277,8 @@ pub struct RuleViolation { pub violation_id: String, pub description: String, pub severity: ViolationSeverity, - pub detected_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub detected_at: time::OffsetDateTime, pub resolved: bool, pub resolution_notes: Option, } @@ -295,7 +303,8 @@ pub struct StoryThread { pub characters_involved: Vec, pub current_status: ThreadStatus, pub importance: f32, - pub estimated_resolution_time: Option>, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub estimated_resolution_time: Option, pub branching_possibilities: Vec, } @@ -329,7 +338,8 @@ pub struct CharacterArc { pub struct ArcMilestone { pub description: String, pub achieved: bool, - pub achievement_date: Option>, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub achievement_date: Option, pub impact_on_character: String, } @@ -349,7 +359,8 @@ pub struct EstablishedFact { pub id: String, pub description: String, pub category: String, - pub established_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub established_at: time::OffsetDateTime, pub immutable: bool, pub supporting_evidence: Vec, pub contradictions: Vec, @@ -372,7 +383,8 @@ pub struct LocationChange { pub change_type: String, pub description: String, pub cause: String, - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, pub reversible: bool, } @@ -573,8 +585,8 @@ Ensure character development feels natural and earned. character_states: HashMap::new(), world_events: Vec::new(), timeline: Timeline { - current_time: Utc::now(), - game_start_time: Utc::now(), + current_time: time::OffsetDateTime::now_utc(), + game_start_time: time::OffsetDateTime::now_utc(), significant_dates: Vec::new(), temporal_anchors: Vec::new(), }, @@ -1080,7 +1092,7 @@ Ensure character development feels natural and earned. .contains(&milestone.description) { milestone.achieved = true; - milestone.achievement_date = Some(Utc::now()); + milestone.achievement_date = Some(time::OffsetDateTime::now_utc()); } } } @@ -1289,10 +1301,98 @@ mod tests { related_characters: vec!["character1".to_string()], prerequisites: Vec::new(), consequences: Vec::new(), - introduced_at: Utc::now(), + introduced_at: time::OffsetDateTime::now_utc(), deadline: None, }; assert_eq!(plot_point.plot_type, PlotType::MainQuest); } + + fn engine() -> NarrativeCoherenceEngine { + let embeddings = Arc::new(astraweave_embeddings::MockEmbeddingClient::new()); + let store = Arc::new(astraweave_rag::VectorStoreWrapper::new( + astraweave_embeddings::VectorStore::new(384), + )); + let rag = Arc::new(RagPipeline::new( + embeddings, + store, + None, + astraweave_rag::RagConfig::default(), + )); + NarrativeCoherenceEngine::new( + Arc::new(astraweave_llm::MockLlm), + rag, + CoherenceConfig::default(), + ) + .unwrap() + } + + #[tokio::test] + async fn character_arc_records_guidance_progress_and_milestone() { + let engine = engine(); + { + let mut arcs = engine.character_arcs.write().await; + arcs.insert( + "hero".into(), + CharacterArc { + character_id: "hero".into(), + arc_type: "growth".into(), + starting_state: "lost".into(), + desired_end_state: "found".into(), + current_progress: 0.0, + milestones: vec![ + ArcMilestone { + description: "met the mentor".into(), + achieved: false, + achievement_date: None, + impact_on_character: "hope".into(), + }, + ArcMilestone { + description: "met the mentor".into(), + achieved: true, + achievement_date: Some(time::OffsetDateTime::UNIX_EPOCH), + impact_on_character: "already".into(), + }, + ArcMilestone { + description: "left home".into(), + achieved: false, + achievement_date: None, + impact_on_character: "later".into(), + }, + ], + obstacles: Vec::new(), + growth_catalysts: Vec::new(), + }, + ); + } + let guidance = CharacterGuidance { + arc_progress_assessment: ArcProgressAssessment { + current_milestone: "met the mentor".into(), + progress_percentage: 0.4, + next_development_needed: "leave home".into(), + timeline_appropriateness: 0.5, + }, + suggested_developments: Vec::new(), + consistency_concerns: Vec::new(), + relationship_dynamics: RelationshipDynamics { + strongest_bond: String::new(), + most_tension: String::new(), + development_opportunities: Vec::new(), + }, + }; + engine + .update_character_arc("hero", &guidance) + .await + .unwrap(); + let arcs = engine.character_arcs.read().await; + let arc = arcs.get("hero").unwrap(); + assert!((arc.current_progress - 0.4).abs() < f32::EPSILON); + assert!(arc.milestones[0].achieved); + assert!(arc.milestones[0].achievement_date.is_some()); + assert_eq!( + arc.milestones[1].achievement_date, + Some(time::OffsetDateTime::UNIX_EPOCH) + ); + assert!(!arc.milestones[2].achieved); + } } diff --git a/astraweave-coordination/src/utc_stamp.rs b/astraweave-coordination/src/utc_stamp.rs new file mode 100644 index 0000000000..0ec4f7a1df --- /dev/null +++ b/astraweave-coordination/src/utc_stamp.rs @@ -0,0 +1,400 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Negative years through `-9999` keep a +//! sign and four digits. A year outside `-9999..=9999` is rejected; `large-dates` +//! is not enabled. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. A negative year keeps a sign and four +/// digits. Values outside `-9999..=9999` are not stored. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> Result { + let utc = dt + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year)?; + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + Ok(out) +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +fn invalid_year() -> time::error::Parse { + time::error::Parse::ParseFromDescription(time::error::ParseFromDescription::InvalidComponent( + "year", + )) +} + +pub(crate) fn parse_utc_rfc3339(text: &str) -> Result { + let rfc3339 = &time::format_description::well_known::Rfc3339; + if text.starts_with('+') || text.starts_with('-') { + parse_signed_year(text, rfc3339) + } else { + OffsetDateTime::parse(text, rfc3339).and_then(|dt| { + dt.checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) + }) + } +} + +/// A leading sign is outside `time`'s RFC 3339 year. The magnitude is at least +/// four digits. The remainder is parsed as year 2000 so a leap day survives, +/// then the result is stored as UTC. +fn parse_signed_year( + text: &str, + rfc3339: &time::format_description::well_known::Rfc3339, +) -> Result { + let negative = text.starts_with('-'); + let rest = &text[1..]; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + if digits < 4 { + return Err(invalid_year()); + } + let magnitude: i32 = rest[..digits].parse().map_err(|_| invalid_year())?; + let year = if negative { + magnitude.checked_neg().ok_or_else(invalid_year)? + } else { + magnitude + }; + let parsed = OffsetDateTime::parse(&format!("2000{}", &rest[digits..]), rfc3339)?; + let date = time::Date::from_calendar_date(year, parsed.month(), parsed.day()) + .map_err(|_| invalid_year())?; + OffsetDateTime::new_in_offset(date, parsed.time(), parsed.offset()) + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) +} + +pub(crate) mod serde_rfc3339 { + use super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize(dt: &OffsetDateTime, serializer: S) -> Result { + let text = format_utc(*dt, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_str(&text) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result { + let text = String::deserialize(deserializer)?; + parse_utc_rfc3339(&text).map_err(serde::de::Error::custom) + } + + #[allow(dead_code)] + pub mod option { + use super::super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize( + dt: &Option, + serializer: S, + ) -> Result { + match dt { + Some(value) => { + let text = format_utc(*value, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_some(&text) + } + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let text = Option::::deserialize(deserializer)?; + text.map(|value| parse_utc_rfc3339(&value).map_err(serde::de::Error::custom)) + .transpose() + } + } +} + +pub(crate) fn saturating_std( + duration: time::Duration, + fallback: std::time::Duration, +) -> std::time::Duration { + std::time::Duration::try_from(duration).unwrap_or(fallback) +} + +#[cfg(test)] +mod tests { + use super::*; + fn fmt_utc(dt: OffsetDateTime, zulu: bool) -> String { + format_utc(dt, zulu).unwrap() + } + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(fmt_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + fmt_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!(fmt_utc(at(100_000_000), true), "2020-01-02T03:04:05.100Z"); + assert_eq!( + fmt_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(fmt_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + fmt_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(fmt_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!(fmt_utc(at(1), false), "2020-01-02T03:04:05.000000001+00:00"); + assert_eq!(fmt_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + fmt_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + fmt_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + fmt_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + fmt_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + } + + #[test] + fn parsed_offsets_become_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T08:04:05+05:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05.100Z").unwrap(), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000100+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.000100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000000001Z").unwrap(), + true + ), + "2020-01-02T03:04:05.000000001Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123400Z").unwrap(), + true + ), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123456789+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.123456789Z" + ); + } + + #[test] + fn serde_json_matches_pinned_zulu_string() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Row { + #[serde(with = "super::serde_rfc3339")] + timestamp: OffsetDateTime, + } + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let row = Row { + timestamp: at(100_000_000), + }; + assert_eq!( + serde_json::to_string(&row).unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05.100Z\"}" + ); + let back: Row = + serde_json::from_str("{\"timestamp\":\"2020-01-02T08:04:05+05:00\"}").unwrap(); + assert_eq!(fmt_utc(back.timestamp, true), "2020-01-02T03:04:05Z"); + assert_eq!( + serde_json::to_string(&Opt { timestamp: None }).unwrap(), + "{\"timestamp\":null}" + ); + assert_eq!( + serde_json::to_string(&Opt { + timestamp: Some(at(0)) + }) + .unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05Z\"}" + ); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(fmt_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + } + + #[test] + fn signed_years_parse_back_to_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0001-01-02T03:04:05Z").unwrap(), true), + "-0001-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("-0001-01-01T01:00:00+05:00").unwrap(), + true + ), + "-0002-12-31T20:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+0000-01-02T03:04:05Z").unwrap(), true), + "0000-01-02T03:04:05Z" + ); + assert!(parse_utc_rfc3339("-001-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn option_timestamp_reads_a_present_string_null_and_omission() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(default, with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let present: Opt = + serde_json::from_str("{\"timestamp\":\"2020-01-02T03:04:05Z\"}").unwrap(); + assert_eq!(present.timestamp, Some(at(0))); + let null: Opt = serde_json::from_str("{\"timestamp\":null}").unwrap(); + assert!(null.timestamp.is_none()); + let omitted: Opt = serde_json::from_str("{}").unwrap(); + assert!(omitted.timestamp.is_none()); + } + + #[test] + fn saturating_std_keeps_a_nonzero_duration() { + assert_eq!( + saturating_std( + time::Duration::seconds(2), + std::time::Duration::from_secs(9) + ), + std::time::Duration::from_secs(2) + ); + assert_eq!( + saturating_std( + time::Duration::seconds(-1), + std::time::Duration::from_secs(9) + ), + std::time::Duration::from_secs(9) + ); + } + + #[test] + fn signed_leap_day_round_trips_and_a_non_leap_day_is_rejected() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0004-02-29T00:00:00Z").unwrap(), true), + "-0004-02-29T00:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-02-29T00:00:00Z").unwrap(), true), + "2020-02-29T00:00:00Z" + ); + assert!(parse_utc_rfc3339("-0001-02-29T00:00:00Z").is_err()); + } + + #[test] + fn years_outside_the_stored_range_are_rejected() { + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn out_of_range_offset_fails_closed() { + assert!(parse_utc_rfc3339("9999-12-31T23:59:59-01:00").is_err()); + let date = time::Date::from_calendar_date(9999, time::Month::December, 31).unwrap(); + let clock = time::Time::from_hms(23, 59, 59).unwrap(); + let offset = time::UtcOffset::from_hms(-1, 0, 0).unwrap(); + let dt = time::OffsetDateTime::new_in_offset(date, clock, offset); + assert!(format_utc(dt, true).is_err()); + assert!(format_utc(dt, false).is_err()); + } +} diff --git a/astraweave-coordination/src/world_events.rs b/astraweave-coordination/src/world_events.rs index 1644317ad1..314497612c 100644 --- a/astraweave-coordination/src/world_events.rs +++ b/astraweave-coordination/src/world_events.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::Arc; @@ -138,7 +137,8 @@ pub struct EntitySpawn { /// Current state of the world for event generation #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WorldState { - pub current_time: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub current_time: time::OffsetDateTime, pub active_locations: Vec, pub player_data: PlayerData, pub npc_states: HashMap, @@ -208,7 +208,8 @@ pub struct EventGenerationContext { pub world_state_snapshot: String, // Serialized state pub generation_reasoning: String, pub coherence_score: f32, - pub generated_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub generated_at: time::OffsetDateTime, } /// Outcome of an executed event @@ -220,7 +221,8 @@ pub struct EventOutcome { pub spawned_entities: Vec, // Entity IDs pub narrative_consequences: Vec, pub follow_up_events_triggered: Vec, - pub completed_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub completed_at: time::OffsetDateTime, } /// Ongoing storyline connecting multiple events @@ -234,8 +236,10 @@ pub struct Storyline { pub current_phase: u32, pub total_phases: u32, pub participants: Vec, - pub start_time: DateTime, - pub estimated_end_time: Option>, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub start_time: time::OffsetDateTime, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub estimated_end_time: Option, pub status: StorylineStatus, pub branching_points: Vec, } @@ -417,7 +421,7 @@ Focus on narrative consistency, logical causation, and player engagement opportu )); let world_state = WorldState { - current_time: Utc::now(), + current_time: time::OffsetDateTime::now_utc(), active_locations: vec!["town_square".to_string(), "forest_path".to_string()], player_data: PlayerData { level: 1, @@ -504,7 +508,7 @@ Focus on narrative consistency, logical causation, and player engagement opportu world_state_snapshot: serde_json::to_string(&world_context)?, generation_reasoning: format!("Generated via {:?} trigger", trigger_type), coherence_score, - generated_at: Utc::now(), + generated_at: time::OffsetDateTime::now_utc(), }; let generated_event = GeneratedEvent { @@ -589,6 +593,12 @@ Focus on narrative consistency, logical causation, and player engagement opportu let storyline_data: StorylineData = astraweave_llm::parse_bounded_model_json(&response) .map_err(|e| anyhow!("Failed to parse storyline: {}", e))?; + let start_time = time::OffsetDateTime::now_utc(); + let estimated_end_time = Some(Self::estimated_storyline_end( + start_time, + storyline_data.total_phases, + )?); + let storyline = Storyline { id: Uuid::new_v4().to_string(), title: storyline_data.title, @@ -598,10 +608,8 @@ Focus on narrative consistency, logical causation, and player engagement opportu current_phase: 1, total_phases: storyline_data.total_phases, participants: Vec::new(), - start_time: Utc::now(), - estimated_end_time: Some( - Utc::now() + Duration::hours(storyline_data.total_phases as i64), - ), + start_time, + estimated_end_time, status: StorylineStatus::Planning, branching_points: Vec::new(), // Would be parsed from storyline_data }; @@ -646,7 +654,7 @@ Focus on narrative consistency, logical causation, and player engagement opportu } } - world_state.current_time = Utc::now(); + world_state.current_time = time::OffsetDateTime::now_utc(); debug!("Updated world state"); Ok(()) } @@ -685,6 +693,11 @@ Focus on narrative consistency, logical causation, and player engagement opportu /// Check if event generation should occur async fn should_generate_event(&self) -> bool { + self.should_generate_event_at(time::OffsetDateTime::now_utc()) + .await + } + + async fn should_generate_event_at(&self, now: time::OffsetDateTime) -> bool { let world_state = self.world_state.read().await; let event_history = self.event_history.read().await; @@ -695,8 +708,10 @@ Focus on narrative consistency, logical causation, and player engagement opportu // Check time since last event if let Some(last_event) = event_history.last() { - let time_since_last = Utc::now() - last_event.generation_context.generated_at; - if time_since_last.num_milliseconds() < self.config.generation_interval_ms as i64 { + let time_since_last = now - last_event.generation_context.generated_at; + if time_since_last.whole_milliseconds() + < i128::from(self.config.generation_interval_ms as i64) + { return false; } } @@ -705,6 +720,15 @@ Focus on narrative consistency, logical causation, and player engagement opportu !world_state.player_data.recent_actions.is_empty() } + fn estimated_storyline_end( + start: time::OffsetDateTime, + phases: u32, + ) -> Result { + start + .checked_add(time::Duration::hours(i64::from(phases))) + .ok_or_else(|| anyhow!("storyline span is out of range")) + } + /// Determine the type of trigger for the next event async fn determine_trigger_type(&self) -> TriggerType { let mut rng = rand::rng(); @@ -733,7 +757,10 @@ Focus on narrative consistency, logical causation, and player engagement opportu context.insert( "current_time".to_string(), - serde_json::to_value(&world_state.current_time)?, + serde_json::Value::String(crate::utc_stamp::format_utc( + world_state.current_time, + true, + )?), ); context.insert( "player_level".to_string(), @@ -843,7 +870,7 @@ Focus on narrative consistency, logical causation, and player engagement opportu location: event_data.location, participants: event_data.participants, event_data: event_data.event_data, - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity, }; @@ -1074,3 +1101,168 @@ mod cap_tests { assert!(format!("{err:#}").contains("64 KiB")); } } + +#[cfg(test)] +mod survivor_tests { + use super::*; + use crate::agent::EventSeverity; + use std::sync::Arc; + + fn generator() -> WorldEventGenerator { + let embeddings = Arc::new(astraweave_embeddings::MockEmbeddingClient::new()); + let store = Arc::new(astraweave_rag::VectorStoreWrapper::new( + astraweave_embeddings::VectorStore::new(384), + )); + let rag = Arc::new(RagPipeline::new( + embeddings, + store, + None, + astraweave_rag::RagConfig::default(), + )); + WorldEventGenerator::new( + Arc::new(astraweave_llm::MockLlm), + rag, + EventGenerationConfig::default(), + ) + .unwrap() + } + + fn history_event(when: time::OffsetDateTime) -> GeneratedEvent { + GeneratedEvent { + event: WorldEvent { + id: "e".into(), + event_type: "travel".into(), + description: "d".into(), + location: None, + participants: Vec::new(), + event_data: serde_json::json!({}), + timestamp: when, + severity: EventSeverity::Minor, + }, + generation_context: EventGenerationContext { + template_used: None, + trigger_type: TriggerType::Time, + world_state_snapshot: String::new(), + generation_reasoning: String::new(), + coherence_score: 0.0, + generated_at: when, + }, + outcome: None, + related_events: Vec::new(), + storyline_id: None, + } + } + + #[test] + fn storyline_end_is_start_plus_phase_hours() { + let start = time::OffsetDateTime::UNIX_EPOCH; + let end = WorldEventGenerator::estimated_storyline_end(start, 4).expect("four phases"); + assert_eq!(end, start + time::Duration::hours(4)); + assert_eq!( + WorldEventGenerator::estimated_storyline_end(start, 0).expect("zero phases"), + start + ); + } + + #[test] + fn a_storyline_span_past_the_clock_range_is_rejected() { + let start = time::OffsetDateTime::UNIX_EPOCH; + assert!(WorldEventGenerator::estimated_storyline_end(start, 80_000_000).is_err()); + } + + #[tokio::test] + async fn world_updates_and_context_keep_player_fields() { + let generator = generator(); + let mut updates = HashMap::new(); + updates.insert("player_level".into(), serde_json::json!(9)); + updates.insert("player_location".into(), serde_json::json!("harbor")); + updates.insert("storm".into(), serde_json::json!(true)); + updates.insert( + "weather".into(), + serde_json::json!({ + "condition": "rain", + "intensity": 0.4, + "duration_hours": 2, + "effects": [] + }), + ); + generator.update_world_state(updates).await.unwrap(); + + let state = generator.world_state.read().await; + assert_eq!(state.player_data.level, 9); + assert_eq!(state.player_data.location, "harbor"); + assert_eq!(state.world_flags.get("storm"), Some(&true)); + assert_eq!(state.weather.condition, "rain"); + drop(state); + + let context = generator.build_world_context().await.unwrap(); + assert_eq!( + context.get("player_level").and_then(|v| v.as_u64()), + Some(9) + ); + assert_eq!( + context.get("player_location").and_then(|v| v.as_str()), + Some("harbor") + ); + let stamp = context + .get("current_time") + .and_then(|v| v.as_str()) + .unwrap(); + assert!(stamp.contains('T')); + assert!(!context.contains_key("xyzzy")); + assert!(context.len() > 2); + } + + #[tokio::test] + async fn event_generation_respects_capacity_actions_and_interval() { + let generator = generator(); + { + let mut state = generator.world_state.write().await; + state.ongoing_events = vec!["a".into(), "b".into(), "c".into(), "d".into(), "e".into()]; + state.player_data.recent_actions.push("walk".into()); + } + assert!(!generator.should_generate_event().await); + + { + let mut state = generator.world_state.write().await; + state.ongoing_events.pop(); + } + assert!(generator.should_generate_event().await); + + { + let mut state = generator.world_state.write().await; + state.ongoing_events.clear(); + } + assert!(generator.should_generate_event().await); + + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(10_000); + let interval = i64::try_from(generator.config.generation_interval_ms).unwrap(); + { + let mut history = generator.event_history.write().await; + history.push(history_event(now - time::Duration::milliseconds(interval))); + } + assert!(generator.should_generate_event_at(now).await); + + { + let mut history = generator.event_history.write().await; + history.clear(); + history.push(history_event( + now - time::Duration::milliseconds(interval - 1), + )); + } + assert!(!generator.should_generate_event_at(now).await); + + { + let mut history = generator.event_history.write().await; + history.clear(); + history.push(history_event(now - time::Duration::seconds(120))); + } + assert!(generator.should_generate_event_at(now).await); + + { + let mut state = generator.world_state.write().await; + state.player_data.recent_actions.clear(); + } + assert!(!generator.should_generate_event_at(now).await); + } +} diff --git a/astraweave-coordination/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-coordination/tests/mutation_resistant_comprehensive_tests.rs index 036d611501..72b22e6515 100644 --- a/astraweave-coordination/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-coordination/tests/mutation_resistant_comprehensive_tests.rs @@ -9,7 +9,6 @@ use astraweave_coordination::agent::*; use astraweave_coordination::coordination::*; use astraweave_coordination::narrative_coherence::*; use astraweave_coordination::world_events::*; -use chrono::{Duration as ChronoDuration, Utc}; use serde_json::json; use std::time::Duration; @@ -168,21 +167,21 @@ fn agent_goal_is_overdue_no_deadline() { #[test] fn agent_goal_is_overdue_future_deadline() { let mut g = AgentGoal::new("x".into(), GoalType::Achieve, 1.0); - g.deadline = Some(Utc::now() + ChronoDuration::hours(1)); + g.deadline = Some(time::OffsetDateTime::now_utc() + time::Duration::hours(1)); assert!(!g.is_overdue()); } #[test] fn agent_goal_is_overdue_past_deadline_active() { let mut g = AgentGoal::new("x".into(), GoalType::Achieve, 1.0); - g.deadline = Some(Utc::now() - ChronoDuration::hours(1)); + g.deadline = Some(time::OffsetDateTime::now_utc() - time::Duration::hours(1)); assert!(g.is_overdue()); } #[test] fn agent_goal_is_overdue_past_deadline_completed_not_overdue() { let mut g = AgentGoal::new("x".into(), GoalType::Achieve, 1.0); - g.deadline = Some(Utc::now() - ChronoDuration::hours(1)); + g.deadline = Some(time::OffsetDateTime::now_utc() - time::Duration::hours(1)); g.status = GoalStatus::Completed; // completed goals are NOT overdue even if past deadline assert!(!g.is_overdue()); @@ -249,14 +248,14 @@ fn task_is_overdue_no_deadline() { #[test] fn task_is_overdue_past_deadline() { let mut t = Task::new("x".into(), "y".into()); - t.deadline = Some(Utc::now() - ChronoDuration::hours(1)); + t.deadline = Some(time::OffsetDateTime::now_utc() - time::Duration::hours(1)); assert!(t.is_overdue()); } #[test] fn task_is_overdue_future_deadline() { let mut t = Task::new("x".into(), "y".into()); - t.deadline = Some(Utc::now() + ChronoDuration::hours(1)); + t.deadline = Some(time::OffsetDateTime::now_utc() + time::Duration::hours(1)); assert!(!t.is_overdue()); } @@ -385,7 +384,7 @@ fn base_agent_create_response_swaps_from_to() { to: a.id.clone(), message_type: MessageType::Request, content: json!({"q": "hello"}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: MessagePriority::High, reply_to: None, }; @@ -421,7 +420,7 @@ fn base_agent_update_resource_usage() { memory_mb: 200, active_tasks: 3, queue_size: 5, - last_activity: Utc::now(), + last_activity: time::OffsetDateTime::now_utc(), }; a.update_resource_usage(usage.clone()); assert_eq!(a.resource_usage.llm_calls_per_minute, 10); @@ -541,6 +540,7 @@ fn resource_usage_default_all_zero() { assert_eq!(u.memory_mb, 0); assert_eq!(u.active_tasks, 0); assert_eq!(u.queue_size, 0); + assert_eq!(u.last_activity.unix_timestamp(), 0); } // ========================================================================= @@ -675,7 +675,7 @@ fn plot_point_serde_roundtrip() { related_characters: vec!["hero".into()], prerequisites: vec![], consequences: vec!["world peace".into()], - introduced_at: Utc::now(), + introduced_at: time::OffsetDateTime::now_utc(), deadline: None, }; let json = serde_json::to_string(&pp).unwrap(); @@ -828,7 +828,7 @@ fn world_event_serde_roundtrip() { location: Some("riverside".into()), participants: vec!["hero".into(), "orcs".into()], event_data: json!({"intensity": 0.9}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), severity: EventSeverity::Major, }; let json = serde_json::to_string(&we).unwrap(); @@ -846,8 +846,8 @@ fn coordination_context_serde_roundtrip() { participants: vec!["a1".into(), "a2".into()], shared_state: std::collections::HashMap::new(), coordination_goals: vec![], - start_time: Utc::now(), - last_update: Utc::now(), + start_time: time::OffsetDateTime::now_utc(), + last_update: time::OffsetDateTime::now_utc(), status: CoordinationStatus::Active, }; let json = serde_json::to_string(&ctx).unwrap(); @@ -923,7 +923,7 @@ fn agent_message_serde_roundtrip() { to: "receiver".into(), message_type: MessageType::Question, content: json!({"q": "where?"}), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: MessagePriority::Normal, reply_to: None, }; @@ -944,7 +944,7 @@ fn agent_message_with_reply_to() { to: "b".into(), message_type: MessageType::Response, content: json!(null), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), priority: MessagePriority::Low, reply_to: Some("m-1".into()), }; @@ -1001,7 +1001,7 @@ fn resource_allocation_serde_roundtrip() { llm_calls_used: 42, memory_allocated: 512, memory_used: 256, - allocated_at: Utc::now(), + allocated_at: time::OffsetDateTime::now_utc(), expires_at: None, }; let json = serde_json::to_string(&ra).unwrap(); @@ -1034,3 +1034,103 @@ fn routing_rule_serde_roundtrip() { assert_eq!(back.to_pattern, None); assert_eq!(back.priority, 10); } + +fn assert_optional_stamp(value: &T, key: &str, is_none: impl Fn(&T) -> bool) +where + T: serde::Serialize + for<'de> serde::Deserialize<'de>, +{ + let mut omitted = serde_json::to_value(value).unwrap(); + assert!( + omitted.as_object_mut().unwrap().remove(key).is_some(), + "{key}" + ); + let back: T = serde_json::from_value(omitted).unwrap(); + assert!(is_none(&back), "{key} omitted"); + + let mut explicit_null = serde_json::to_value(value).unwrap(); + explicit_null[key] = serde_json::Value::Null; + let back: T = serde_json::from_value(explicit_null).unwrap(); + assert!(is_none(&back), "{key} null"); + + let mut present = serde_json::to_value(value).unwrap(); + present[key] = serde_json::json!("2020-01-02T03:04:05Z"); + let back: T = serde_json::from_value(present).unwrap(); + assert!(!is_none(&back), "{key} present"); +} + +#[test] +fn omitted_optional_timestamps_load_as_none() { + let goal = AgentGoal::new("goal".into(), GoalType::Achieve, 1.0); + assert_optional_stamp(&goal, "deadline", |goal| goal.deadline.is_none()); + + let task = Task::new("act".into(), "do".into()); + assert_optional_stamp(&task, "deadline", |task| task.deadline.is_none()); + + let allocation = ResourceAllocation { + agent_id: "a".into(), + llm_calls_allocated: 0, + llm_calls_used: 0, + memory_allocated: 0, + memory_used: 0, + allocated_at: time::OffsetDateTime::UNIX_EPOCH, + expires_at: None, + }; + assert_optional_stamp(&allocation, "expires_at", |row| row.expires_at.is_none()); + + let plot = PlotPoint { + id: "p".into(), + description: "d".into(), + plot_type: PlotType::MainQuest, + importance: 1.0, + status: PlotStatus::Active, + related_characters: vec![], + prerequisites: vec![], + consequences: vec![], + introduced_at: time::OffsetDateTime::UNIX_EPOCH, + deadline: None, + }; + assert_optional_stamp(&plot, "deadline", |row| row.deadline.is_none()); + + let thread = StoryThread { + id: "t".into(), + title: "title".into(), + theme: "theme".into(), + related_plot_points: vec![], + characters_involved: vec![], + current_status: ThreadStatus::Introduced, + importance: 1.0, + estimated_resolution_time: None, + branching_possibilities: vec![], + }; + assert_optional_stamp(&thread, "estimated_resolution_time", |row| { + row.estimated_resolution_time.is_none() + }); + + let milestone = ArcMilestone { + description: "m".into(), + achieved: false, + achievement_date: None, + impact_on_character: "i".into(), + }; + assert_optional_stamp(&milestone, "achievement_date", |row| { + row.achievement_date.is_none() + }); + + let storyline = Storyline { + id: "s".into(), + title: "title".into(), + description: "d".into(), + category: "c".into(), + events: vec![], + current_phase: 0, + total_phases: 1, + participants: vec![], + start_time: time::OffsetDateTime::UNIX_EPOCH, + estimated_end_time: None, + status: StorylineStatus::Planning, + branching_points: vec![], + }; + assert_optional_stamp(&storyline, "estimated_end_time", |row| { + row.estimated_end_time.is_none() + }); +} diff --git a/astraweave-llm/Cargo.toml b/astraweave-llm/Cargo.toml index 1329bff19f..30237b6e97 100644 --- a/astraweave-llm/Cargo.toml +++ b/astraweave-llm/Cargo.toml @@ -16,7 +16,7 @@ async-trait = "0.1" tokio = { workspace = true } futures-util = { workspace = true } uuid = { version = "1.0", features = ["v4"] } -chrono = { version = "0.4", features = ["serde"] } +time = { version = "0.3", features = ["parsing"] } tracing = "0.1" dashmap = "6.1" rand = "0.9" diff --git a/astraweave-llm/src/ab_testing.rs b/astraweave-llm/src/ab_testing.rs index 90162da065..7339d7eeb9 100644 --- a/astraweave-llm/src/ab_testing.rs +++ b/astraweave-llm/src/ab_testing.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -52,9 +51,12 @@ pub struct Experiment { pub name: String, pub description: String, pub status: ExperimentStatus, - pub created_at: DateTime, - pub started_at: Option>, - pub ended_at: Option>, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub created_at: time::OffsetDateTime, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub started_at: Option, + #[serde(default, with = "crate::utc_stamp::serde_rfc3339::option")] + pub ended_at: Option, pub duration_hours: u64, pub traffic_percentage: f32, // 0.0 to 1.0 pub control_variant: Variant, @@ -139,7 +141,8 @@ pub struct ExperimentResults { pub statistical_analysis: Option, pub winner: Option, // Variant ID pub confidence_level: f64, - pub last_updated: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_updated: time::OffsetDateTime, } /// Status of experiment results @@ -199,7 +202,8 @@ pub struct Outcome { pub user_id: String, pub experiment_id: String, pub variant_id: String, - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, pub metrics: HashMap, pub success: bool, pub metadata: HashMap, @@ -211,7 +215,7 @@ pub struct VariantAssignment { pub experiment_id: String, pub variant_id: String, pub variant: Variant, - pub assigned_at: DateTime, + pub assigned_at: time::OffsetDateTime, } impl ABTestFramework { @@ -239,7 +243,7 @@ impl ABTestFramework { } experiment.status = ExperimentStatus::Draft; - experiment.created_at = Utc::now(); + experiment.created_at = time::OffsetDateTime::now_utc(); // Check concurrent experiment limit { @@ -272,7 +276,7 @@ impl ABTestFramework { statistical_analysis: None, winner: None, confidence_level: 0.0, - last_updated: Utc::now(), + last_updated: time::OffsetDateTime::now_utc(), }, ); } @@ -294,7 +298,7 @@ impl ABTestFramework { } experiment.status = ExperimentStatus::Running; - experiment.started_at = Some(Utc::now()); + experiment.started_at = Some(time::OffsetDateTime::now_utc()); info!( "Started experiment: {} ({})", @@ -316,7 +320,7 @@ impl ABTestFramework { } experiment.status = ExperimentStatus::Stopped; - experiment.ended_at = Some(Utc::now()); + experiment.ended_at = Some(time::OffsetDateTime::now_utc()); info!( "Stopped experiment: {} ({})", @@ -353,7 +357,7 @@ impl ABTestFramework { experiment_id: experiment_id.to_string(), variant_id: variant.id.clone(), variant, - assigned_at: Utc::now(), + assigned_at: time::OffsetDateTime::now_utc(), })) } else { Err(anyhow!("Experiment {} not found", experiment_id)) @@ -379,7 +383,7 @@ impl ABTestFramework { let mut results = self.results.write().await; if let Some(experiment_results) = results.get_mut(&outcome.experiment_id) { self.update_variant_results(experiment_results, &outcome); - experiment_results.last_updated = Utc::now(); + experiment_results.last_updated = time::OffsetDateTime::now_utc(); // Perform statistical analysis if we have enough data if self.has_sufficient_data(experiment_results) { @@ -574,7 +578,7 @@ impl ABTestFramework { /// Round-robin variant assignment (simplified) fn assign_variant_round_robin(&self, experiment: &Experiment) -> Result { // For simplicity, use time-based round robin - let now = Utc::now().timestamp() as usize; + let now = time::OffsetDateTime::now_utc().unix_timestamp() as usize; let total_variants = 1 + experiment.test_variants.len(); let variant_index = now % total_variants; @@ -720,7 +724,7 @@ mod tests { name: "Test Experiment".to_string(), description: "A test experiment".to_string(), status: ExperimentStatus::Draft, - created_at: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), started_at: None, ended_at: None, duration_hours: 24, @@ -816,7 +820,7 @@ mod tests { user_id: "user123".to_string(), experiment_id: experiment_id.clone(), variant_id: "control".to_string(), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), metrics, success: true, metadata: HashMap::new(), @@ -1191,7 +1195,7 @@ mod tests { user_id: "user123".to_string(), experiment_id: experiment_id.clone(), variant_id: "control".to_string(), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), metrics: HashMap::new(), success: true, metadata: HashMap::new(), @@ -1210,7 +1214,7 @@ mod tests { user_id: "user123".to_string(), experiment_id: "nonexistent".to_string(), variant_id: "control".to_string(), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), metrics: HashMap::new(), success: true, metadata: HashMap::new(), @@ -1404,7 +1408,7 @@ mod tests { statistical_analysis: None, winner: None, confidence_level: 0.0, - last_updated: Utc::now(), + last_updated: time::OffsetDateTime::now_utc(), }; assert_eq!(results.experiment_id, "exp-1"); @@ -1418,7 +1422,7 @@ mod tests { user_id: "user456".to_string(), experiment_id: "exp-1".to_string(), variant_id: "control".to_string(), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), metrics: { let mut m = HashMap::new(); m.insert("success_rate".to_string(), 0.8); @@ -1448,7 +1452,7 @@ mod tests { experiment_id: "exp-1".to_string(), variant_id: "test".to_string(), variant, - assigned_at: Utc::now(), + assigned_at: time::OffsetDateTime::now_utc(), }; assert_eq!(assignment.experiment_id, "exp-1"); @@ -1518,7 +1522,7 @@ mod tests { user_id: format!("user{}", i), experiment_id: experiment_id.clone(), variant_id: "control".to_string(), - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), metrics, success: i % 2 == 0, metadata: HashMap::new(), @@ -1530,4 +1534,31 @@ mod tests { let results = framework.get_results(&experiment_id).await.unwrap(); assert_eq!(results.variant_results["control"].sample_size, 5); } + + fn assert_optional_stamp(key: &str, is_none: impl Fn(&Experiment) -> bool) { + let experiment = create_test_experiment(); + let mut omitted = serde_json::to_value(&experiment).unwrap(); + assert!( + omitted.as_object_mut().unwrap().remove(key).is_some(), + "{key}" + ); + let back: Experiment = serde_json::from_value(omitted).unwrap(); + assert!(is_none(&back), "{key} omitted"); + + let mut explicit_null = serde_json::to_value(&experiment).unwrap(); + explicit_null[key] = serde_json::Value::Null; + let back: Experiment = serde_json::from_value(explicit_null).unwrap(); + assert!(is_none(&back), "{key} null"); + + let mut present = serde_json::to_value(&experiment).unwrap(); + present[key] = serde_json::json!("2020-01-02T03:04:05Z"); + let back: Experiment = serde_json::from_value(present).unwrap(); + assert!(!is_none(&back), "{key} present"); + } + + #[test] + fn omitted_optional_timestamps_load_as_none() { + assert_optional_stamp("started_at", |experiment| experiment.started_at.is_none()); + assert_optional_stamp("ended_at", |experiment| experiment.ended_at.is_none()); + } } diff --git a/astraweave-llm/src/backpressure.rs b/astraweave-llm/src/backpressure.rs index 86a425ea7c..e82b1cb3ce 100644 --- a/astraweave-llm/src/backpressure.rs +++ b/astraweave-llm/src/backpressure.rs @@ -427,7 +427,8 @@ impl BackpressureManager { .insert(priority, queues.queued_by_priority(priority)); } - metrics.last_updated = chrono::Utc::now().to_rfc3339(); + metrics.last_updated = + crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()); metrics } diff --git a/astraweave-llm/src/lib.rs b/astraweave-llm/src/lib.rs index 800fd3ade6..e8f63d6737 100644 --- a/astraweave-llm/src/lib.rs +++ b/astraweave-llm/src/lib.rs @@ -140,6 +140,7 @@ pub async fn read_capped_text_limited(response: reqwest::Response, limit: usize) } /// How long the next body read may block, and which deadline a timeout is. +#[cfg(feature = "ollama")] struct ReadWait { wait: std::time::Duration, on_timeout: &'static str, @@ -1148,6 +1149,8 @@ use astraweave_core::{ActionStep, PlanIntent, ToolRegistry, WorldSnapshot}; use tracing::{debug, info}; // --- Core modules (always available) --- +mod utc_stamp; + pub mod ab_testing; pub mod backpressure; pub mod batch_executor; diff --git a/astraweave-llm/src/production_hardening.rs b/astraweave-llm/src/production_hardening.rs index 9909b47b29..2b3362d1c7 100644 --- a/astraweave-llm/src/production_hardening.rs +++ b/astraweave-llm/src/production_hardening.rs @@ -187,7 +187,9 @@ impl HealthChecker { component.to_string(), ComponentHealth { status: HealthStatus::Healthy, - last_check: chrono::Utc::now().to_rfc3339(), + last_check: crate::utc_stamp::format_utc_rfc3339( + time::OffsetDateTime::now_utc(), + ), consecutive_failures: 0, consecutive_successes: 0, last_error: None, @@ -217,7 +219,7 @@ impl HealthChecker { .entry(component.to_string()) .or_insert_with(|| ComponentHealth { status: HealthStatus::Healthy, - last_check: chrono::Utc::now().to_rfc3339(), + last_check: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), consecutive_failures: 0, consecutive_successes: 0, last_error: None, @@ -268,7 +270,8 @@ impl HealthChecker { } } - component_health.last_check = chrono::Utc::now().to_rfc3339(); + component_health.last_check = + crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()); } fn get_overall_health(&self) -> SystemHealth { @@ -294,7 +297,7 @@ impl HealthChecker { SystemHealth { overall_status, components: self.components.clone(), - last_check: chrono::Utc::now().to_rfc3339(), + last_check: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), uptime_seconds: self.start_time.elapsed().as_secs(), } } @@ -589,7 +592,7 @@ impl ProductionHardeningLayer { circuit_breakers: circuit_breaker_status, backpressure: backpressure_metrics, telemetry: telemetry_metrics, - last_updated: chrono::Utc::now().to_rfc3339(), + last_updated: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), } } diff --git a/astraweave-llm/src/tool_guard.rs b/astraweave-llm/src/tool_guard.rs index 2a29ea559b..7ef08398b3 100644 --- a/astraweave-llm/src/tool_guard.rs +++ b/astraweave-llm/src/tool_guard.rs @@ -74,7 +74,8 @@ impl ValidationResult { /// Audit log entry for tool invocations #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuditEntry { - pub timestamp: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, pub action_type: String, // "MoveTo", "CoverFire", etc. pub result: String, // "valid", "invalid", "denied" pub reason: Option, @@ -257,7 +258,7 @@ impl ToolGuard { let action_type = Self::action_name(action).to_string(); let entry = AuditEntry { - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), action_type, result: match result { ValidationResult::Valid => "valid".to_string(), @@ -577,7 +578,7 @@ mod tests { #[test] fn test_audit_entry_serialization() { let entry = AuditEntry { - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), action_type: "MoveTo".to_string(), result: "valid".to_string(), reason: None, @@ -591,7 +592,7 @@ mod tests { #[test] fn test_audit_entry_with_reason() { let entry = AuditEntry { - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), action_type: "Attack".to_string(), result: "invalid".to_string(), reason: Some("Target out of range".to_string()), @@ -604,7 +605,7 @@ mod tests { #[test] fn test_audit_entry_clone() { let entry = AuditEntry { - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), action_type: "Wait".to_string(), result: "valid".to_string(), reason: None, diff --git a/astraweave-llm/src/utc_stamp.rs b/astraweave-llm/src/utc_stamp.rs new file mode 100644 index 0000000000..d07aa6d859 --- /dev/null +++ b/astraweave-llm/src/utc_stamp.rs @@ -0,0 +1,388 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Negative years through `-9999` keep a +//! sign and four digits. A year outside `-9999..=9999` is rejected; `large-dates` +//! is not enabled. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. A negative year keeps a sign and four +/// digits. Values outside `-9999..=9999` are not stored. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub(crate) fn format_utc_rfc3339(dt: OffsetDateTime) -> String { + format_utc(dt, false).unwrap_or_else(|error| error.to_string()) +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> Result { + let utc = dt + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year)?; + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + Ok(out) +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +fn invalid_year() -> time::error::Parse { + time::error::Parse::ParseFromDescription(time::error::ParseFromDescription::InvalidComponent( + "year", + )) +} + +pub(crate) fn parse_utc_rfc3339(text: &str) -> Result { + let rfc3339 = &time::format_description::well_known::Rfc3339; + if text.starts_with('+') || text.starts_with('-') { + parse_signed_year(text, rfc3339) + } else { + OffsetDateTime::parse(text, rfc3339).and_then(|dt| { + dt.checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) + }) + } +} + +/// A leading sign is outside `time`'s RFC 3339 year. The magnitude is at least +/// four digits. The remainder is parsed as year 2000 so a leap day survives, +/// then the result is stored as UTC. +fn parse_signed_year( + text: &str, + rfc3339: &time::format_description::well_known::Rfc3339, +) -> Result { + let negative = text.starts_with('-'); + let rest = &text[1..]; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + if digits < 4 { + return Err(invalid_year()); + } + let magnitude: i32 = rest[..digits].parse().map_err(|_| invalid_year())?; + let year = if negative { + magnitude.checked_neg().ok_or_else(invalid_year)? + } else { + magnitude + }; + let parsed = OffsetDateTime::parse(&format!("2000{}", &rest[digits..]), rfc3339)?; + let date = time::Date::from_calendar_date(year, parsed.month(), parsed.day()) + .map_err(|_| invalid_year())?; + OffsetDateTime::new_in_offset(date, parsed.time(), parsed.offset()) + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) +} + +pub(crate) mod serde_rfc3339 { + use super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize(dt: &OffsetDateTime, serializer: S) -> Result { + let text = format_utc(*dt, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_str(&text) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result { + let text = String::deserialize(deserializer)?; + parse_utc_rfc3339(&text).map_err(serde::de::Error::custom) + } + + #[allow(dead_code)] + pub mod option { + use super::super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize( + dt: &Option, + serializer: S, + ) -> Result { + match dt { + Some(value) => { + let text = format_utc(*value, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_some(&text) + } + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let text = Option::::deserialize(deserializer)?; + text.map(|value| parse_utc_rfc3339(&value).map_err(serde::de::Error::custom)) + .transpose() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn fmt_utc(dt: OffsetDateTime, zulu: bool) -> String { + format_utc(dt, zulu).unwrap() + } + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(fmt_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + fmt_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!(fmt_utc(at(100_000_000), true), "2020-01-02T03:04:05.100Z"); + assert_eq!( + fmt_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(fmt_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + fmt_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(fmt_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!(fmt_utc(at(1), false), "2020-01-02T03:04:05.000000001+00:00"); + assert_eq!(fmt_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + fmt_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + fmt_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + fmt_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + fmt_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + format_utc_rfc3339(at(100_000_000)), + "2020-01-02T03:04:05.100+00:00" + ); + } + + #[test] + fn parsed_offsets_become_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T08:04:05+05:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05.100Z").unwrap(), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000100+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.000100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000000001Z").unwrap(), + true + ), + "2020-01-02T03:04:05.000000001Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123400Z").unwrap(), + true + ), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123456789+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.123456789Z" + ); + } + + #[test] + fn serde_json_matches_pinned_zulu_string() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Row { + #[serde(with = "super::serde_rfc3339")] + timestamp: OffsetDateTime, + } + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let row = Row { + timestamp: at(100_000_000), + }; + assert_eq!( + serde_json::to_string(&row).unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05.100Z\"}" + ); + let back: Row = + serde_json::from_str("{\"timestamp\":\"2020-01-02T08:04:05+05:00\"}").unwrap(); + assert_eq!(fmt_utc(back.timestamp, true), "2020-01-02T03:04:05Z"); + assert_eq!( + serde_json::to_string(&Opt { timestamp: None }).unwrap(), + "{\"timestamp\":null}" + ); + assert_eq!( + serde_json::to_string(&Opt { + timestamp: Some(at(0)) + }) + .unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05Z\"}" + ); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(fmt_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + assert_eq!(format_utc_rfc3339(civil(-1)), "-0001-01-02T03:04:05+00:00"); + } + + #[test] + fn signed_years_parse_back_to_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0001-01-02T03:04:05Z").unwrap(), true), + "-0001-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("-0001-01-01T01:00:00+05:00").unwrap(), + true + ), + "-0002-12-31T20:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+0000-01-02T03:04:05Z").unwrap(), true), + "0000-01-02T03:04:05Z" + ); + assert!(parse_utc_rfc3339("-001-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn option_timestamp_reads_a_present_string_null_and_omission() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(default, with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let present: Opt = + serde_json::from_str("{\"timestamp\":\"2020-01-02T03:04:05Z\"}").unwrap(); + assert_eq!(present.timestamp, Some(at(0))); + let null: Opt = serde_json::from_str("{\"timestamp\":null}").unwrap(); + assert!(null.timestamp.is_none()); + let omitted: Opt = serde_json::from_str("{}").unwrap(); + assert!(omitted.timestamp.is_none()); + } + + #[test] + fn signed_leap_day_round_trips_and_a_non_leap_day_is_rejected() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0004-02-29T00:00:00Z").unwrap(), true), + "-0004-02-29T00:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-02-29T00:00:00Z").unwrap(), true), + "2020-02-29T00:00:00Z" + ); + assert!(parse_utc_rfc3339("-0001-02-29T00:00:00Z").is_err()); + } + + #[test] + fn years_outside_the_stored_range_are_rejected() { + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn out_of_range_offset_fails_closed() { + assert!(parse_utc_rfc3339("9999-12-31T23:59:59-01:00").is_err()); + let date = time::Date::from_calendar_date(9999, time::Month::December, 31).unwrap(); + let clock = time::Time::from_hms(23, 59, 59).unwrap(); + let offset = time::UtcOffset::from_hms(-1, 0, 0).unwrap(); + let dt = time::OffsetDateTime::new_in_offset(date, clock, offset); + assert!(format_utc(dt, true).is_err()); + assert!(format_utc(dt, false).is_err()); + assert_eq!( + format_utc_rfc3339(dt), + format_utc(dt, false).unwrap_err().to_string() + ); + } +} diff --git a/astraweave-memory/Cargo.toml b/astraweave-memory/Cargo.toml index 41e4860a10..76a1118a3c 100644 --- a/astraweave-memory/Cargo.toml +++ b/astraweave-memory/Cargo.toml @@ -15,7 +15,7 @@ tokio = { workspace = true } tracing = { workspace = true } futures = "0.3" uuid = { version = "1.0", features = ["v4"] } -chrono = { version = "0.4", features = ["serde"] } +time = { version = "0.3", features = ["parsing"] } dashmap = "6.1" async-trait = "0.1" # 0.41.0 is the first rusqlite that depends on libsqlite3-sys 0.39 diff --git a/astraweave-memory/benches/memory_benchmarks.rs b/astraweave-memory/benches/memory_benchmarks.rs index 5d675f8e64..0e5a9926d5 100644 --- a/astraweave-memory/benches/memory_benchmarks.rs +++ b/astraweave-memory/benches/memory_benchmarks.rs @@ -2,7 +2,6 @@ use astraweave_memory::{ Memory, MemoryContent, MemoryManager, MemoryMetadata, MemorySource, MemoryType, SpatialTemporalContext, }; -use chrono::Utc; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use std::hint::black_box; @@ -25,8 +24,8 @@ fn create_test_memory(id: &str) -> Memory { }, }, metadata: MemoryMetadata { - created_at: Utc::now(), - last_accessed: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_accessed: time::OffsetDateTime::now_utc(), access_count: 0, importance: 0.5, confidence: 0.8, diff --git a/astraweave-memory/src/components.rs b/astraweave-memory/src/components.rs index b11ebf2925..b80caae8a6 100644 --- a/astraweave-memory/src/components.rs +++ b/astraweave-memory/src/components.rs @@ -73,7 +73,8 @@ pub struct ExperienceBuffer { /// Description of the experience pub description: String, /// When the experience occurred - pub timestamp: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, /// Participants in the experience pub participants: Vec, /// Location of the experience @@ -119,7 +120,8 @@ pub struct WorkingMemoryTask { /// Task description pub description: String, /// When the task was added to working memory - pub added_at: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub added_at: time::OffsetDateTime, /// Priority level (0.0 to 1.0) pub priority: f32, /// Associated data @@ -163,9 +165,11 @@ pub struct SocialRelationship { /// Trust level (0.0 to 1.0) pub trust: f32, /// When this relationship was first established - pub established_at: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub established_at: time::OffsetDateTime, /// Last interaction time - pub last_interaction: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_interaction: time::OffsetDateTime, /// Number of interactions pub interaction_count: u32, } @@ -203,7 +207,8 @@ pub struct SocialInteraction { /// Type of interaction pub interaction_type: InteractionType, /// When it occurred - pub timestamp: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, /// Brief description pub description: String, /// Emotional valence of the interaction @@ -263,16 +268,19 @@ pub struct LearningDomain { /// Practice sessions in this domain pub practice_sessions: Vec, /// When this domain was first encountered - pub first_encountered: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub first_encountered: time::OffsetDateTime, /// Last practice time - pub last_practice: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_practice: time::OffsetDateTime, } /// Record of a practice session #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PracticeSession { /// When the session occurred - pub timestamp: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, /// Duration in seconds pub duration: f32, /// Performance score in this session @@ -289,7 +297,8 @@ pub struct PerformanceRecord { /// Performance score pub score: f32, /// When this performance was recorded - pub timestamp: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, /// Context or conditions pub context: String, } @@ -324,7 +333,8 @@ pub struct MemoryOperation { /// Memory ID involved pub memory_id: String, /// When the operation occurred - pub timestamp: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, /// Success status pub success: bool, /// Additional details @@ -424,7 +434,7 @@ impl WorkingMemoryComponent { let task = WorkingMemoryTask { id: task_id.clone(), description, - added_at: chrono::Utc::now(), + added_at: time::OffsetDateTime::now_utc(), priority: priority.clamp(0.0, 1.0), data, active: true, @@ -451,13 +461,28 @@ impl WorkingMemoryComponent { /// Clean up old tasks based on retention duration pub fn cleanup_old_tasks(&mut self) { - let now = chrono::Utc::now(); - let cutoff = now - chrono::Duration::seconds(self.retention_duration as i64); + self.cleanup_old_tasks_at(time::OffsetDateTime::now_utc()); + } + fn cleanup_old_tasks_at(&mut self, now: time::OffsetDateTime) { + let Some(cutoff) = retention_cutoff(now, self.retention_duration) else { + return; + }; self.active_tasks.retain(|task| task.added_at > cutoff); } } +/// Saved retention that is not a usable span leaves the task list unchanged. +fn retention_cutoff( + now: time::OffsetDateTime, + retention_duration: f32, +) -> Option { + if !retention_duration.is_finite() || retention_duration < 0.0 { + return None; + } + now.checked_sub(time::Duration::seconds(retention_duration as i64)) +} + impl SocialMemoryComponent { /// Add or update a social relationship pub fn update_relationship( @@ -475,12 +500,12 @@ impl SocialMemoryComponent { relationship_type, strength: 0.5, trust: 0.5, - established_at: chrono::Utc::now(), - last_interaction: chrono::Utc::now(), + established_at: time::OffsetDateTime::now_utc(), + last_interaction: time::OffsetDateTime::now_utc(), interaction_count: 0, }); - relationship.last_interaction = chrono::Utc::now(); + relationship.last_interaction = time::OffsetDateTime::now_utc(); relationship.interaction_count += 1; } @@ -517,35 +542,148 @@ impl LearningMemoryComponent { difficulty: f32, ) { let session = PracticeSession { - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), duration, performance_score, difficulty, }; - // Find or create the learning domain - let domain_exists = self.learning_domains.iter().any(|d| d.name == domain_name); - if !domain_exists { + let domain_index = self + .learning_domains + .iter() + .position(|domain| domain.name == domain_name); + let domain_index = if let Some(domain_index) = domain_index { + domain_index + } else { self.learning_domains.push(LearningDomain { name: domain_name.clone(), proficiency: 0.0, practice_sessions: Vec::new(), - first_encountered: chrono::Utc::now(), - last_practice: chrono::Utc::now(), + first_encountered: time::OffsetDateTime::now_utc(), + last_practice: time::OffsetDateTime::now_utc(), }); - } - - let domain = self - .learning_domains - .iter_mut() - .find(|d| d.name == domain_name) - .expect("domain was just created above"); + self.learning_domains.len() - 1 + }; + let domain = &mut self.learning_domains[domain_index]; domain.practice_sessions.push(session); - domain.last_practice = chrono::Utc::now(); + domain.last_practice = time::OffsetDateTime::now_utc(); // Update proficiency based on performance let learning_adjustment = performance_score * self.learning_rate; domain.proficiency = (domain.proficiency + learning_adjustment).clamp(0.0, 1.0); } } + +#[cfg(test)] +mod survivor_tests { + use super::*; + + #[test] + fn add_task_returns_the_id_it_stores() { + let mut memory = WorkingMemoryComponent::default(); + let id = memory.add_task("fetch water".into(), 0.4, serde_json::json!({"n": 1})); + assert_eq!(memory.active_tasks.len(), 1); + assert_eq!(memory.active_tasks[0].id, id); + assert_ne!(id, "xyzzy"); + assert!(!id.is_empty()); + assert!((memory.active_tasks[0].priority - 0.4).abs() < f32::EPSILON); + } + + #[test] + fn cleanup_drops_tasks_older_than_retention_and_keeps_new_ones() { + let mut memory = WorkingMemoryComponent { + retention_duration: 60.0, + ..WorkingMemoryComponent::default() + }; + let old = memory.add_task("old".into(), 0.2, serde_json::json!(null)); + let fresh = memory.add_task("fresh".into(), 0.8, serde_json::json!(null)); + memory.active_tasks[0].added_at = + time::OffsetDateTime::now_utc() - time::Duration::seconds(120); + memory.cleanup_old_tasks(); + let ids: Vec<_> = memory + .active_tasks + .iter() + .map(|task| task.id.as_str()) + .collect(); + assert!(!ids.contains(&old.as_str())); + assert!(ids.contains(&fresh.as_str())); + + let at = time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(10_000); + let mut boundary = WorkingMemoryComponent { + retention_duration: 60.0, + ..WorkingMemoryComponent::default() + }; + let exact = boundary.add_task("exact".into(), 0.2, serde_json::json!(null)); + let newer = boundary.add_task("newer".into(), 0.2, serde_json::json!(null)); + boundary.active_tasks[0].added_at = at; + boundary.active_tasks[1].added_at = at + time::Duration::nanoseconds(1); + boundary.cleanup_old_tasks_at(at + time::Duration::seconds(60)); + let ids: Vec<_> = boundary + .active_tasks + .iter() + .map(|task| task.id.as_str()) + .collect(); + assert!(!ids.contains(&exact.as_str())); + assert!(ids.contains(&newer.as_str())); + } + + #[test] + fn an_unusable_retention_keeps_every_task() { + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(1_700_000_000); + for retention in [ + 4e11_f32, + -4e11_f32, + f32::NAN, + f32::INFINITY, + f32::NEG_INFINITY, + -1.0, + ] { + let mut memory = WorkingMemoryComponent { + retention_duration: retention, + ..WorkingMemoryComponent::default() + }; + let id = memory.add_task("keep".into(), 0.5, serde_json::json!(null)); + memory.active_tasks[0].added_at = now; + memory.cleanup_old_tasks_at(now); + assert_eq!(memory.active_tasks.len(), 1, "{retention}"); + assert_eq!(memory.active_tasks[0].id, id); + } + + let mut zero = WorkingMemoryComponent { + retention_duration: 0.0, + ..WorkingMemoryComponent::default() + }; + zero.add_task("now".into(), 0.5, serde_json::json!(null)); + zero.active_tasks[0].added_at = now; + zero.cleanup_old_tasks_at(now); + assert!(zero.active_tasks.is_empty()); + } + + #[test] + fn update_relationship_counts_a_new_contact() { + let mut social = SocialMemoryComponent::default(); + social.update_relationship("npc".into(), "Mira".into(), RelationshipType::Friend); + let rel = social.known_entities.get("npc").unwrap(); + assert_eq!(rel.name, "Mira"); + assert_eq!(rel.interaction_count, 1); + social.update_relationship("npc".into(), "Mira".into(), RelationshipType::Friend); + assert_eq!( + social.known_entities.get("npc").unwrap().interaction_count, + 2 + ); + } + + #[test] + fn record_practice_creates_a_domain_and_raises_proficiency() { + let mut learning = LearningMemoryComponent::default(); + learning.record_practice("bow".into(), 12.0, 0.5, 0.3); + learning.record_practice("bow".into(), 4.0, 0.5, 0.3); + assert_eq!(learning.learning_domains.len(), 1); + let domain = &learning.learning_domains[0]; + assert_eq!(domain.name, "bow"); + assert_eq!(domain.practice_sessions.len(), 2); + assert!((domain.proficiency - 0.1).abs() < 1e-5); + assert!((domain.practice_sessions[0].duration - 12.0).abs() < f32::EPSILON); + } +} diff --git a/astraweave-memory/src/compression.rs b/astraweave-memory/src/compression.rs index 2ca006ff4f..8a2cd3441d 100644 --- a/astraweave-memory/src/compression.rs +++ b/astraweave-memory/src/compression.rs @@ -86,7 +86,8 @@ impl CompressionEngine { } // Check age - let age_days = (chrono::Utc::now() - memory.metadata.created_at).num_days() as f32; + let age_days = + (time::OffsetDateTime::now_utc() - memory.metadata.created_at).whole_days() as f32; if age_days < self.config.min_age_days { return Ok(false); } @@ -260,7 +261,6 @@ pub struct CompressionStats { #[cfg(test)] mod tests { use super::*; - use chrono::Utc; // ======================================================================== // CONFIG TESTS @@ -344,7 +344,7 @@ mod tests { fn test_should_not_compress_important_memory() { let engine = CompressionEngine::new(CompressionConfig::default()); let mut memory = Memory::episodic("Important event".to_string(), vec![], None); - memory.metadata.created_at = Utc::now() - chrono::Duration::days(35); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(35); memory.metadata.importance = 0.8; // High importance let should_compress = engine.should_compress(&memory).unwrap(); @@ -355,7 +355,7 @@ mod tests { fn test_should_not_compress_already_compressed() { let engine = CompressionEngine::new(CompressionConfig::default()); let mut memory = Memory::sensory("Already compressed".to_string(), None); - memory.metadata.created_at = Utc::now() - chrono::Duration::days(35); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(35); memory.metadata.importance = 0.1; memory.metadata.tags.push("compressed".to_string()); @@ -374,7 +374,7 @@ mod tests { let engine = CompressionEngine::new(config); let mut memory = Memory::sensory("Old unimportant memory".to_string(), None); - memory.metadata.created_at = Utc::now() - chrono::Duration::days(10); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); memory.metadata.importance = 0.2; let should_compress = engine.should_compress(&memory).unwrap(); @@ -394,7 +394,7 @@ mod tests { ); // Make memory old enough for compression - memory.metadata.created_at = Utc::now() - chrono::Duration::days(35); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(35); memory.metadata.importance = 0.2; // Low importance let original_length = memory.content.text.len(); @@ -471,7 +471,7 @@ mod tests { }; let mut memory = Memory::sensory("Main content".to_string(), Some(sensory)); - memory.metadata.created_at = Utc::now() - chrono::Duration::days(35); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(35); memory.metadata.importance = 0.1; engine.compress_memory(&mut memory).unwrap(); @@ -504,7 +504,7 @@ mod tests { "E4".into(), "E5".into(), ]; - memory.metadata.created_at = Utc::now() - chrono::Duration::days(35); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(35); memory.metadata.importance = 0.1; engine.compress_memory(&mut memory).unwrap(); @@ -533,13 +533,13 @@ mod tests { "Long text that should be compressed into shorter form".to_string(), None, ); - m.metadata.created_at = Utc::now() - chrono::Duration::days(5); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); m.metadata.importance = 0.2; m }, { let mut m = Memory::working("Short".to_string()); - m.metadata.created_at = Utc::now() - chrono::Duration::days(5); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); m.metadata.importance = 0.2; m }, diff --git a/astraweave-memory/src/consolidation.rs b/astraweave-memory/src/consolidation.rs index 45348cdf36..0e364144ab 100644 --- a/astraweave-memory/src/consolidation.rs +++ b/astraweave-memory/src/consolidation.rs @@ -5,7 +5,6 @@ use crate::memory_types::*; use anyhow::Result; -use chrono::Utc; use serde::{Deserialize, Serialize}; /// Configuration for memory consolidation @@ -70,7 +69,7 @@ impl ConsolidationEngine { /// Form temporal associations between memories fn form_temporal_associations(&self, memories: &mut [Memory]) -> Result { let mut associations_formed = 0; - let window_duration = chrono::Duration::hours(self.config.temporal_window_hours as i64); + let window_duration = temporal_window(self.config.temporal_window_hours); for i in 0..memories.len() { for j in (i + 1)..memories.len() { @@ -89,9 +88,7 @@ impl ConsolidationEngine { memories[i].add_association( memories[j].id.clone(), AssociationType::Temporal, - 0.5 + (1.0 - - (time_diff.num_seconds().abs() as f32 - / (window_duration.num_seconds() as f32))), + temporal_strength(time_diff, window_duration), ); associations_formed += 1; } @@ -212,7 +209,7 @@ impl ConsolidationEngine { // Update access count (consolidation acts as access) memory.metadata.access_count += 1; - memory.metadata.last_accessed = Utc::now(); + memory.metadata.last_accessed = time::OffsetDateTime::now_utc(); Ok(()) } @@ -233,6 +230,35 @@ pub struct ConsolidationResult { pub processing_time_ms: u64, } +/// A configured hour count becomes a duration the clock can represent. +/// +/// An unusable window matches no pair. A finite count that does not fit +/// the duration range uses the largest duration. A count in `[0, 1)` hour +/// is zero seconds. +fn temporal_window(hours: f32) -> time::Duration { + if !hours.is_finite() || hours < 0.0 { + return time::Duration::new(-1, 0); + } + match (hours as i64).checked_mul(3_600) { + Some(seconds) => time::Duration::seconds(seconds), + None => time::Duration::MAX, + } +} + +/// Strength of a temporal link. A zero-second window does not divide. +/// +/// An equal-time pair uses ratio 0, so the value before the association +/// clamp is 1.5. Any other pair uses the fraction of the window. +fn temporal_strength(time_diff: time::Duration, window: time::Duration) -> f32 { + let window_seconds = window.whole_seconds(); + let ratio = if window_seconds == 0 { + 0.0 + } else { + time_diff.whole_seconds().abs() as f32 / window_seconds as f32 + }; + 0.5 + (1.0 - ratio) +} + impl ConsolidationResult { /// Get total associations formed pub fn total_associations(&self) -> usize { @@ -265,6 +291,8 @@ mod tests { let result = engine.consolidate(&mut memories).unwrap(); assert!(result.total_associations() > 0); assert!(result.memories_processed == 2); + assert_eq!(memories[0].metadata.access_count, 1); + assert_eq!(memories[1].metadata.access_count, 1); } #[test] @@ -277,4 +305,144 @@ mod tests { let similarity = engine.calculate_conceptual_similarity(&memory1, &memory2); assert!(similarity > 0.5); // Should be similar due to shared words and type } + + fn temporal_count(hours: f32) -> usize { + let engine = ConsolidationEngine::new(ConsolidationConfig { + temporal_window_hours: hours, + ..ConsolidationConfig::default() + }); + let mut memories = vec![ + Memory::episodic( + "Met John at the park".to_string(), + vec!["John".to_string()], + Some("park".to_string()), + ), + Memory::episodic( + "Played with John in the park".to_string(), + vec!["John".to_string()], + Some("park".to_string()), + ), + ]; + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::days(30); + memories[0].metadata.created_at = now; + memories[1].metadata.created_at = now - time::Duration::days(10); + engine + .consolidate(&mut memories) + .expect("consolidate") + .temporal_associations + } + + #[test] + fn a_wide_temporal_window_still_links_memories() { + assert_eq!(temporal_count(3e15_f32), 1); + } + + #[test] + fn an_unusable_temporal_window_links_nothing() { + assert_eq!(temporal_count(f32::NAN), 0); + assert_eq!(temporal_count(f32::INFINITY), 0); + assert_eq!(temporal_count(f32::NEG_INFINITY), 0); + assert_eq!(temporal_count(-0.5), 0); + } + + #[test] + fn a_zero_hour_window_links_memories_from_the_same_instant() { + assert_eq!(same_instant_count(0.0), 1); + assert_eq!(same_instant_count(-0.5), 0); + } + + #[test] + fn a_zero_second_window_stores_a_finite_strength() { + for hours in [0.0_f32, 0.5] { + let engine = ConsolidationEngine::new(ConsolidationConfig { + temporal_window_hours: hours, + ..ConsolidationConfig::default() + }); + let mut memories = vec![ + Memory::episodic( + "north ridge".to_string(), + vec!["scout".to_string()], + Some("ridge".to_string()), + ), + Memory::episodic( + "south ford".to_string(), + vec!["courier".to_string()], + Some("ford".to_string()), + ), + ]; + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::days(30); + memories[0].metadata.created_at = now; + memories[1].metadata.created_at = now; + engine.consolidate(&mut memories).expect("consolidate"); + let strength = memories[0] + .associations + .iter() + .find(|assoc| assoc.association_type == AssociationType::Temporal) + .expect("temporal association") + .strength; + assert!(strength.is_finite()); + assert!((strength - 1.0).abs() < 1e-5); + assert!(memories[0] + .get_strong_associations(0.5) + .iter() + .any(|assoc| assoc.association_type == AssociationType::Temporal)); + } + } + + fn same_instant_count(hours: f32) -> usize { + let engine = ConsolidationEngine::new(ConsolidationConfig { + temporal_window_hours: hours, + ..ConsolidationConfig::default() + }); + let mut memories = vec![ + Memory::episodic( + "Met John at the park".to_string(), + vec!["John".to_string()], + Some("park".to_string()), + ), + Memory::episodic( + "Played with John in the park".to_string(), + vec!["John".to_string()], + Some("park".to_string()), + ), + ]; + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::days(30); + memories[0].metadata.created_at = now; + memories[1].metadata.created_at = now; + engine + .consolidate(&mut memories) + .expect("consolidate") + .temporal_associations + } + + #[test] + fn temporal_strength_uses_the_fraction_of_the_window() { + let engine = ConsolidationEngine::new(ConsolidationConfig { + temporal_window_hours: 24.0, + ..ConsolidationConfig::default() + }); + let mut memories = vec![ + Memory::episodic( + "north ridge".to_string(), + vec!["scout".to_string()], + Some("ridge".to_string()), + ), + Memory::episodic( + "south ford".to_string(), + vec!["courier".to_string()], + Some("ford".to_string()), + ), + ]; + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::days(30); + memories[0].metadata.created_at = now; + memories[1].metadata.created_at = now - time::Duration::hours(18); + engine.consolidate(&mut memories).expect("consolidate"); + let strength = memories[0] + .associations + .iter() + .find(|assoc| assoc.association_type == AssociationType::Temporal) + .expect("temporal association") + .strength; + assert!((strength - 0.75).abs() < 1e-5); + } } diff --git a/astraweave-memory/src/episode.rs b/astraweave-memory/src/episode.rs index e53f334250..dbc9fd7b33 100644 --- a/astraweave-memory/src/episode.rs +++ b/astraweave-memory/src/episode.rs @@ -11,7 +11,6 @@ use crate::{ EmotionalContext, Memory, MemoryContent, MemoryMetadata, MemorySource, MemoryType, SpatialTemporalContext, }; -use chrono::Utc; use serde::{Deserialize, Serialize}; use std::time::{Duration, SystemTime}; @@ -338,8 +337,8 @@ impl Episode { // Create memory metadata let metadata = MemoryMetadata { - created_at: Utc::now(), - last_accessed: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_accessed: time::OffsetDateTime::now_utc(), access_count: 0, importance, confidence: 1.0, diff --git a/astraweave-memory/src/forgetting.rs b/astraweave-memory/src/forgetting.rs index 41aed5c5d6..448625f21f 100644 --- a/astraweave-memory/src/forgetting.rs +++ b/astraweave-memory/src/forgetting.rs @@ -5,7 +5,6 @@ use crate::memory_types::*; use anyhow::Result; -use chrono::Utc; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -169,9 +168,9 @@ impl ForgettingEngine { /// Update memory strength based on decay and usage patterns fn update_memory_strength(&self, memory: &mut Memory) -> Result<()> { - let now = Utc::now(); - let age_days = (now - memory.metadata.created_at).num_days() as f32; - let _last_access_days = (now - memory.metadata.last_accessed).num_days() as f32; + let now = time::OffsetDateTime::now_utc(); + let age_days = (now - memory.metadata.created_at).whole_days() as f32; + let _last_access_days = (now - memory.metadata.last_accessed).whole_days() as f32; // Get forgetting curve for this memory type let default_curve = ForgettingCurve { @@ -300,7 +299,7 @@ impl ForgettingEngine { let avg_age_days = type_memories .iter() - .map(|m| (Utc::now() - m.metadata.created_at).num_days() as f32) + .map(|m| (time::OffsetDateTime::now_utc() - m.metadata.created_at).whole_days() as f32) .sum::() / type_memories.len() as f32; @@ -372,7 +371,7 @@ mod tests { let mut memory = Memory::sensory("Test memory".to_string(), None); // Artificially age the memory - memory.metadata.created_at = Utc::now() - chrono::Duration::days(30); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); let initial_strength = memory.metadata.strength; engine.update_memory_strength(&mut memory).unwrap(); @@ -403,7 +402,7 @@ mod tests { let mut memory2 = Memory::episodic("Test".to_string(), vec![], None); // Age both memories equally - let old_date = Utc::now() - chrono::Duration::days(10); + let old_date = time::OffsetDateTime::now_utc() - time::Duration::days(10); memory1.metadata.created_at = old_date; memory2.metadata.created_at = old_date; @@ -512,7 +511,7 @@ mod tests { let mut memory = Memory::sensory("Very old memory".to_string(), None); // Age and weaken the memory significantly - memory.metadata.created_at = Utc::now() - chrono::Duration::days(365); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); memory.metadata.strength = 0.01; // Below any threshold let mut memories = vec![memory]; @@ -529,7 +528,7 @@ mod tests { let mut memory = Memory::semantic("Important".to_string(), "facts".to_string()); memory.metadata.permanent = true; memory.metadata.strength = 0.001; // Very weak but permanent - memory.metadata.created_at = Utc::now() - chrono::Duration::days(1000); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1000); let mut memories = vec![memory]; let result = engine.apply_forgetting(&mut memories).unwrap(); @@ -549,7 +548,7 @@ mod tests { // Old weak memory (will be forgotten) let mut old = Memory::sensory("Old".to_string(), None); - old.metadata.created_at = Utc::now() - chrono::Duration::days(365); + old.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); old.metadata.strength = 0.01; // Permanent memory (won't be processed) @@ -583,7 +582,7 @@ mod tests { let mut memory = create_working_memory("Test"); // Age the memory - memory.metadata.created_at = Utc::now() - chrono::Duration::days(7); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); let initial = memory.metadata.strength; engine.update_memory_strength(&mut memory).unwrap(); @@ -598,11 +597,13 @@ mod tests { let mut low_importance = create_working_memory("Low"); low_importance.metadata.importance = 0.1; - low_importance.metadata.created_at = Utc::now() - chrono::Duration::days(5); + low_importance.metadata.created_at = + time::OffsetDateTime::now_utc() - time::Duration::days(5); let mut high_importance = create_working_memory("High"); high_importance.metadata.importance = 0.9; - high_importance.metadata.created_at = Utc::now() - chrono::Duration::days(5); + high_importance.metadata.created_at = + time::OffsetDateTime::now_utc() - time::Duration::days(5); engine.update_memory_strength(&mut low_importance).unwrap(); engine.update_memory_strength(&mut high_importance).unwrap(); @@ -617,11 +618,13 @@ mod tests { let mut never_accessed = Memory::episodic("Never".to_string(), vec![], None); never_accessed.metadata.access_count = 0; - never_accessed.metadata.created_at = Utc::now() - chrono::Duration::days(10); + never_accessed.metadata.created_at = + time::OffsetDateTime::now_utc() - time::Duration::days(10); let mut frequently_accessed = Memory::episodic("Frequent".to_string(), vec![], None); frequently_accessed.metadata.access_count = 100; - frequently_accessed.metadata.created_at = Utc::now() - chrono::Duration::days(10); + frequently_accessed.metadata.created_at = + time::OffsetDateTime::now_utc() - time::Duration::days(10); engine.update_memory_strength(&mut never_accessed).unwrap(); engine @@ -642,7 +645,7 @@ mod tests { let mut memory = Memory::episodic("Test".to_string(), vec![], None); memory.metadata.access_count = 10; - memory.metadata.created_at = Utc::now() - chrono::Duration::days(5); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); let config_enabled = ForgettingConfig { spaced_repetition: true, @@ -669,7 +672,7 @@ mod tests { // Set extreme values memory.metadata.importance = 10.0; // Unrealistically high memory.metadata.access_count = 10000; - memory.metadata.created_at = Utc::now(); // Very fresh + memory.metadata.created_at = time::OffsetDateTime::now_utc(); // Very fresh engine.update_memory_strength(&mut memory).unwrap(); @@ -682,7 +685,7 @@ mod tests { fn test_update_strength_uses_default_curve() { let engine = ForgettingEngine::new(ForgettingConfig::default()); let mut memory = create_working_memory("Test"); - memory.metadata.created_at = Utc::now() - chrono::Duration::days(30); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); // This should work with the default Working curve engine.update_memory_strength(&mut memory).unwrap(); @@ -868,10 +871,10 @@ mod tests { let engine = ForgettingEngine::new(ForgettingConfig::default()); let mut m1 = create_working_memory("W1"); - m1.metadata.created_at = Utc::now() - chrono::Duration::days(10); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); let mut m2 = create_working_memory("W2"); - m2.metadata.created_at = Utc::now() - chrono::Duration::days(20); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(20); let memories = vec![m1, m2]; let stats = engine.get_type_statistics(&MemoryType::Working, &memories); @@ -938,10 +941,10 @@ mod tests { let engine = ForgettingEngine::new(ForgettingConfig::default()); let mut m1 = create_working_memory("W1"); - m1.metadata.created_at = Utc::now() - chrono::Duration::days(30); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); let mut m2 = create_working_memory("W2"); - m2.metadata.created_at = Utc::now() - chrono::Duration::days(30); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); let initial_strength = m1.metadata.strength + m2.metadata.strength; let mut memories = vec![m1, m2]; @@ -963,13 +966,13 @@ mod tests { // Create 3 memories, mark first and third for removal let mut m1 = Memory::sensory("First".to_string(), None); m1.metadata.strength = 0.001; - m1.metadata.created_at = Utc::now() - chrono::Duration::days(100); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); let m2 = Memory::sensory("Second".to_string(), None); // Fresh, will stay let mut m3 = Memory::sensory("Third".to_string(), None); m3.metadata.strength = 0.001; - m3.metadata.created_at = Utc::now() - chrono::Duration::days(100); + m3.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); let mut memories = vec![m1, m2, m3]; engine.apply_forgetting(&mut memories).unwrap(); diff --git a/astraweave-memory/src/lib.rs b/astraweave-memory/src/lib.rs index d57666eec0..dfd0482b22 100644 --- a/astraweave-memory/src/lib.rs +++ b/astraweave-memory/src/lib.rs @@ -9,6 +9,8 @@ //! - Cross-agent memory sharing //! - Episode-based interaction recording for companion learning +mod utc_stamp; + pub mod memory_types; pub use memory_types::*; diff --git a/astraweave-memory/src/memory_manager.rs b/astraweave-memory/src/memory_manager.rs index 9d89a11040..87d438dbc3 100644 --- a/astraweave-memory/src/memory_manager.rs +++ b/astraweave-memory/src/memory_manager.rs @@ -4,7 +4,6 @@ //! including storage, retrieval, and organization of memories. use anyhow::{anyhow, Result}; -use chrono::Utc; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -68,7 +67,8 @@ pub struct MemoryStats { /// Number of clusters pub total_clusters: usize, /// Last update timestamp - pub last_updated: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_updated: time::OffsetDateTime, } impl Default for MemoryStats { @@ -78,7 +78,7 @@ impl Default for MemoryStats { memories_by_type: HashMap::new(), average_importance: 0.0, total_clusters: 0, - last_updated: Utc::now(), + last_updated: time::OffsetDateTime::now_utc(), } } } @@ -264,7 +264,7 @@ impl MemoryManager { memories_by_type, average_importance, total_clusters: self.clusters.len(), - last_updated: Utc::now(), + last_updated: time::OffsetDateTime::now_utc(), }; } @@ -664,8 +664,6 @@ mod tests { #[test] fn test_cleanup_actually_removes_weak_memories() { - use chrono::Duration; - let config = MemoryManagerConfig { importance_threshold: 0.5, // Set a reasonable threshold ..Default::default() @@ -678,8 +676,10 @@ mod tests { weak_memory.metadata.strength = 0.1; weak_memory.metadata.permanent = false; // Set created_at to a month ago to make it "old" - weak_memory.metadata.created_at = Utc::now() - Duration::days(30); - weak_memory.metadata.last_accessed = Utc::now() - Duration::days(30); + weak_memory.metadata.created_at = + time::OffsetDateTime::now_utc() - time::Duration::days(30); + weak_memory.metadata.last_accessed = + time::OffsetDateTime::now_utc() - time::Duration::days(30); manager.store_memory(weak_memory).unwrap(); assert_eq!(manager.get_stats().total_memories, 1); diff --git a/astraweave-memory/src/memory_types.rs b/astraweave-memory/src/memory_types.rs index 94b6f17a1e..3830d97bbb 100644 --- a/astraweave-memory/src/memory_types.rs +++ b/astraweave-memory/src/memory_types.rs @@ -1,4 +1,3 @@ -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use uuid::Uuid; @@ -82,9 +81,11 @@ pub struct SpatialTemporalContext { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MemoryMetadata { /// When the memory was created - pub created_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub created_at: time::OffsetDateTime, /// When the memory was last accessed - pub last_accessed: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_accessed: time::OffsetDateTime, /// How many times the memory has been accessed pub access_count: u32, /// Importance score (0.0 to 1.0) @@ -125,7 +126,8 @@ pub struct MemoryAssociation { /// Strength of the association (0.0 to 1.0) pub strength: f32, /// When this association was formed - pub formed_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub formed_at: time::OffsetDateTime, } /// Types of associations between memories @@ -157,8 +159,10 @@ pub struct MemoryCluster { pub memory_ids: Vec, pub central_concept: String, pub importance: f32, - pub created_at: DateTime, - pub last_updated: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub created_at: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_updated: time::OffsetDateTime, } /// Types of memory clusters @@ -181,7 +185,8 @@ pub struct ConsolidationState { /// Number of consolidation passes pub passes: u32, /// Last consolidation time - pub last_consolidation: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_consolidation: time::OffsetDateTime, /// Whether consolidation is needed pub needs_consolidation: bool, /// Priority for consolidation @@ -225,8 +230,10 @@ pub struct RetrievalContext { /// Time window for memory filtering #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TimeWindow { - pub start: DateTime, - pub end: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub start: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub end: time::OffsetDateTime, } /// Memory sharing permissions and metadata @@ -276,8 +283,8 @@ impl Memory { memory_type, content, metadata: MemoryMetadata { - created_at: Utc::now(), - last_accessed: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_accessed: time::OffsetDateTime::now_utc(), access_count: 0, importance: 0.5, confidence: 1.0, @@ -456,7 +463,7 @@ impl Memory { /// Update access information pub fn accessed(&mut self) { - self.metadata.last_accessed = Utc::now(); + self.metadata.last_accessed = time::OffsetDateTime::now_utc(); self.metadata.access_count += 1; // Strengthen memory through access (spaced repetition effect) @@ -475,8 +482,10 @@ impl Memory { /// Calculate current memory strength based on age and access pub fn calculate_current_strength(&self) -> f32 { - let age_days = (Utc::now() - self.metadata.created_at).num_days() as f32; - let time_since_access = (Utc::now() - self.metadata.last_accessed).num_days() as f32; + let age_days = + (time::OffsetDateTime::now_utc() - self.metadata.created_at).whole_days() as f32; + let time_since_access = + (time::OffsetDateTime::now_utc() - self.metadata.last_accessed).whole_days() as f32; // Apply forgetting curve: strength = initial * e^(-decay * time) let base_strength = @@ -499,7 +508,7 @@ impl Memory { memory_id, association_type, strength: strength.clamp(0.0, 1.0), - formed_at: Utc::now(), + formed_at: time::OffsetDateTime::now_utc(), }; self.associations.push(association); @@ -567,7 +576,8 @@ impl Memory { relevance += self.calculate_current_strength() * 0.2; // Recency bonus - let age_days = (Utc::now() - self.metadata.created_at).num_days() as f32; + let age_days = + (time::OffsetDateTime::now_utc() - self.metadata.created_at).whole_days() as f32; let recency_bonus = if age_days < 7.0 { 0.1 * (7.0 - age_days) / 7.0 } else { @@ -588,8 +598,8 @@ impl MemoryCluster { memory_ids: Vec::new(), central_concept, importance: 0.5, - created_at: Utc::now(), - last_updated: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_updated: time::OffsetDateTime::now_utc(), } } @@ -597,14 +607,14 @@ impl MemoryCluster { pub fn add_memory(&mut self, memory_id: String) { if !self.memory_ids.contains(&memory_id) { self.memory_ids.push(memory_id); - self.last_updated = Utc::now(); + self.last_updated = time::OffsetDateTime::now_utc(); } } /// Remove a memory from this cluster pub fn remove_memory(&mut self, memory_id: &str) { self.memory_ids.retain(|id| id != memory_id); - self.last_updated = Utc::now(); + self.last_updated = time::OffsetDateTime::now_utc(); } /// Calculate cluster importance based on member memories @@ -772,7 +782,7 @@ mod tests { let initial_strength = memory.calculate_current_strength(); // Simulate aging - memory.metadata.created_at = Utc::now() - chrono::Duration::days(10); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); let aged_strength = memory.calculate_current_strength(); assert!(aged_strength < initial_strength); @@ -781,8 +791,8 @@ mod tests { #[test] fn test_memory_strength_with_recent_access() { let mut memory = Memory::working("Test".to_string()); - memory.metadata.created_at = Utc::now() - chrono::Duration::days(5); - memory.metadata.last_accessed = Utc::now(); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); + memory.metadata.last_accessed = time::OffsetDateTime::now_utc(); let strength = memory.calculate_current_strength(); @@ -803,8 +813,8 @@ mod tests { fn test_should_forget_weak_memory() { let mut memory = Memory::sensory("Faint impression".to_string(), None); memory.metadata.strength = 0.1; - memory.metadata.created_at = Utc::now() - chrono::Duration::days(100); - memory.metadata.last_accessed = Utc::now() - chrono::Duration::days(100); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); + memory.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(100); // With high decay and old age, should be below threshold assert!(memory.should_forget(0.5)); @@ -982,7 +992,7 @@ mod tests { #[test] fn test_matches_context_time_window() { let mut memory = Memory::working("Test".to_string()); - memory.metadata.created_at = Utc::now() - chrono::Duration::days(5); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); let context_in_window = RetrievalContext { query: "test".to_string(), @@ -991,8 +1001,8 @@ mod tests { recent_memory_ids: Vec::new(), preferred_types: vec![], time_window: Some(TimeWindow { - start: Utc::now() - chrono::Duration::days(10), - end: Utc::now(), + start: time::OffsetDateTime::now_utc() - time::Duration::days(10), + end: time::OffsetDateTime::now_utc(), }), limit: 10, }; @@ -1006,8 +1016,8 @@ mod tests { recent_memory_ids: Vec::new(), preferred_types: vec![], time_window: Some(TimeWindow { - start: Utc::now() - chrono::Duration::days(3), - end: Utc::now(), + start: time::OffsetDateTime::now_utc() - time::Duration::days(3), + end: time::OffsetDateTime::now_utc(), }), limit: 10, }; @@ -1284,7 +1294,7 @@ mod tests { let state = ConsolidationState { consolidation_level: 0.5, passes: 3, - last_consolidation: Utc::now(), + last_consolidation: time::OffsetDateTime::now_utc(), needs_consolidation: true, priority: 0.7, }; @@ -1317,8 +1327,8 @@ mod tests { #[test] fn test_time_window() { let window = TimeWindow { - start: Utc::now() - chrono::Duration::days(7), - end: Utc::now(), + start: time::OffsetDateTime::now_utc() - time::Duration::days(7), + end: time::OffsetDateTime::now_utc(), }; let json = serde_json::to_string(&window).unwrap(); diff --git a/astraweave-memory/src/retrieval.rs b/astraweave-memory/src/retrieval.rs index 8ffe42846e..2ddbb86bd3 100644 --- a/astraweave-memory/src/retrieval.rs +++ b/astraweave-memory/src/retrieval.rs @@ -73,7 +73,8 @@ pub enum RetrievalPath { Associative { source_memory_id: String }, /// Found through temporal proximity Temporal { - reference_time: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + reference_time: time::OffsetDateTime, }, /// Found through clustering Cluster { cluster_id: String }, @@ -207,10 +208,10 @@ impl RetrievalEngine { // Calculate distance from time window let distance_start = (memory.metadata.created_at - time_window.start) - .num_days() + .whole_days() .abs(); let distance_end = (memory.metadata.created_at - time_window.end) - .num_days() + .whole_days() .abs(); let min_distance = distance_start.min(distance_end) as f32; @@ -240,9 +241,9 @@ impl RetrievalEngine { /// Calculate recency score fn calculate_recency_score(&self, memory: &Memory) -> f32 { - let now = chrono::Utc::now(); - let age_days = (now - memory.metadata.created_at).num_days() as f32; - let last_access_days = (now - memory.metadata.last_accessed).num_days() as f32; + let now = time::OffsetDateTime::now_utc(); + let age_days = (now - memory.metadata.created_at).whole_days() as f32; + let last_access_days = (now - memory.metadata.last_accessed).whole_days() as f32; // Combine creation recency and access recency let creation_recency = (-age_days / 30.0).exp(); // Decay over 30 days @@ -568,7 +569,7 @@ mod tests { #[test] fn test_retrieval_path_temporal() { - let time = chrono::Utc::now(); + let time = time::OffsetDateTime::now_utc(); let path = RetrievalPath::Temporal { reference_time: time, }; @@ -675,7 +676,7 @@ mod tests { let engine = RetrievalEngine::new(RetrievalConfig::default()); let memory = Memory::sensory("Test".to_string(), None); - let now = chrono::Utc::now(); + let now = time::OffsetDateTime::now_utc(); let context = RetrievalContext { query: "test".to_string(), emotional_state: None, @@ -683,8 +684,8 @@ mod tests { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - chrono::Duration::days(1), - end: now + chrono::Duration::days(1), + start: now - time::Duration::days(1), + end: now + time::Duration::days(1), }), limit: 10, }; diff --git a/astraweave-memory/src/sharing.rs b/astraweave-memory/src/sharing.rs index 61edb04a8e..48899806f3 100644 --- a/astraweave-memory/src/sharing.rs +++ b/astraweave-memory/src/sharing.rs @@ -67,7 +67,8 @@ pub struct SharedMemoryContent { /// Memory type pub memory_type: MemoryType, /// Timestamp - pub created_at: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub created_at: time::OffsetDateTime, /// Importance level pub importance: f32, /// Associated entities (filtered) @@ -88,7 +89,8 @@ pub struct SharingAuditEntry { /// Type of sharing pub sharing_type: SharingType, /// When the sharing occurred - pub timestamp: chrono::DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, /// Success status pub success: bool, /// Reason for sharing @@ -245,7 +247,7 @@ impl SharingEngine { SharingType::Metadata => format!( "Memory of type {:?} created on {}", memory.memory_type, - memory.metadata.created_at.format("%Y-%m-%d") + crate::utc_stamp::format_utc_date(memory.metadata.created_at) ), SharingType::Restricted => { return Err(anyhow!( @@ -323,7 +325,7 @@ impl SharingEngine { source_entity: requesting_entity.to_string(), target_entity: request.target_entity.clone(), sharing_type: request.sharing_type.clone(), - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), success, reason: if success { request.reason.clone() @@ -410,7 +412,7 @@ impl SharingEngine { source_entity: revoking_entity.to_string(), target_entity: target_entity.to_string(), sharing_type: SharingType::Restricted, - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), success: true, reason: "Access revoked".to_string(), }; @@ -1179,9 +1181,9 @@ mod tests { conditions: Vec::new(), }; - let before = chrono::Utc::now(); + let before = time::OffsetDateTime::now_utc(); engine.share_memory(&request, &memory, "owner").unwrap(); - let after = chrono::Utc::now(); + let after = time::OffsetDateTime::now_utc(); let audit = engine.get_audit_log(&memory.id); assert!(audit[0].timestamp >= before); diff --git a/astraweave-memory/src/storage.rs b/astraweave-memory/src/storage.rs index 669092287d..91deab1eb0 100644 --- a/astraweave-memory/src/storage.rs +++ b/astraweave-memory/src/storage.rs @@ -103,7 +103,7 @@ impl MemoryStorage { .collect::>() }); - let created_ts = memory.metadata.created_at.timestamp(); + let created_ts = memory.metadata.created_at.unix_timestamp(); let memory_type_str = format!("{:?}", memory.memory_type); self.conn.execute( @@ -401,7 +401,6 @@ pub struct StorageStats { mod tests { use super::*; use crate::{MemoryContent, MemoryMetadata, MemorySource, SpatialTemporalContext}; - use chrono::Utc; fn create_test_memory(id: &str, memory_type: MemoryType, importance: f32) -> Memory { Memory { @@ -421,8 +420,8 @@ mod tests { }, }, metadata: MemoryMetadata { - created_at: Utc::now(), - last_accessed: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_accessed: time::OffsetDateTime::now_utc(), access_count: 0, importance, confidence: 1.0, diff --git a/astraweave-memory/src/utc_stamp.rs b/astraweave-memory/src/utc_stamp.rs new file mode 100644 index 0000000000..d2f96cd8ed --- /dev/null +++ b/astraweave-memory/src/utc_stamp.rs @@ -0,0 +1,387 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Negative years through `-9999` keep a +//! sign and four digits. A year outside `-9999..=9999` is rejected; `large-dates` +//! is not enabled. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. A negative year keeps a sign and four +/// digits. Values outside `-9999..=9999` are not stored. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub(crate) fn format_utc_date(dt: OffsetDateTime) -> String { + let utc = dt.to_offset(UtcOffset::UTC); + format!( + "{}-{:02}-{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day() + ) +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> Result { + let utc = dt + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year)?; + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + Ok(out) +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +fn invalid_year() -> time::error::Parse { + time::error::Parse::ParseFromDescription(time::error::ParseFromDescription::InvalidComponent( + "year", + )) +} + +pub(crate) fn parse_utc_rfc3339(text: &str) -> Result { + let rfc3339 = &time::format_description::well_known::Rfc3339; + if text.starts_with('+') || text.starts_with('-') { + parse_signed_year(text, rfc3339) + } else { + OffsetDateTime::parse(text, rfc3339).and_then(|dt| { + dt.checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) + }) + } +} + +/// A leading sign is outside `time`'s RFC 3339 year. The magnitude is at least +/// four digits. The remainder is parsed as year 2000 so a leap day survives, +/// then the result is stored as UTC. +fn parse_signed_year( + text: &str, + rfc3339: &time::format_description::well_known::Rfc3339, +) -> Result { + let negative = text.starts_with('-'); + let rest = &text[1..]; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + if digits < 4 { + return Err(invalid_year()); + } + let magnitude: i32 = rest[..digits].parse().map_err(|_| invalid_year())?; + let year = if negative { + magnitude.checked_neg().ok_or_else(invalid_year)? + } else { + magnitude + }; + let parsed = OffsetDateTime::parse(&format!("2000{}", &rest[digits..]), rfc3339)?; + let date = time::Date::from_calendar_date(year, parsed.month(), parsed.day()) + .map_err(|_| invalid_year())?; + OffsetDateTime::new_in_offset(date, parsed.time(), parsed.offset()) + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) +} + +pub(crate) mod serde_rfc3339 { + use super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize(dt: &OffsetDateTime, serializer: S) -> Result { + let text = format_utc(*dt, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_str(&text) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result { + let text = String::deserialize(deserializer)?; + parse_utc_rfc3339(&text).map_err(serde::de::Error::custom) + } + + #[allow(dead_code)] + pub mod option { + use super::super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize( + dt: &Option, + serializer: S, + ) -> Result { + match dt { + Some(value) => { + let text = format_utc(*value, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_some(&text) + } + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let text = Option::::deserialize(deserializer)?; + text.map(|value| parse_utc_rfc3339(&value).map_err(serde::de::Error::custom)) + .transpose() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn fmt_utc(dt: OffsetDateTime, zulu: bool) -> String { + format_utc(dt, zulu).unwrap() + } + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(fmt_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + fmt_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!(fmt_utc(at(100_000_000), true), "2020-01-02T03:04:05.100Z"); + assert_eq!( + fmt_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(fmt_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + fmt_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(fmt_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!(fmt_utc(at(1), false), "2020-01-02T03:04:05.000000001+00:00"); + assert_eq!(fmt_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + fmt_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + fmt_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + fmt_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + fmt_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!(format_utc_date(at(123_456_789)), "2020-01-02"); + } + + #[test] + fn parsed_offsets_become_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T08:04:05+05:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05.100Z").unwrap(), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000100+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.000100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000000001Z").unwrap(), + true + ), + "2020-01-02T03:04:05.000000001Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123400Z").unwrap(), + true + ), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123456789+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.123456789Z" + ); + } + + #[test] + fn serde_json_matches_pinned_zulu_string() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Row { + #[serde(with = "super::serde_rfc3339")] + timestamp: OffsetDateTime, + } + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let row = Row { + timestamp: at(100_000_000), + }; + assert_eq!( + serde_json::to_string(&row).unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05.100Z\"}" + ); + let back: Row = + serde_json::from_str("{\"timestamp\":\"2020-01-02T08:04:05+05:00\"}").unwrap(); + assert_eq!(fmt_utc(back.timestamp, true), "2020-01-02T03:04:05Z"); + assert_eq!( + serde_json::to_string(&Opt { timestamp: None }).unwrap(), + "{\"timestamp\":null}" + ); + assert_eq!( + serde_json::to_string(&Opt { + timestamp: Some(at(0)) + }) + .unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05Z\"}" + ); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(fmt_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + assert_eq!(format_utc_date(civil(-1)), "-0001-01-02"); + } + + #[test] + fn signed_years_parse_back_to_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0001-01-02T03:04:05Z").unwrap(), true), + "-0001-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("-0001-01-01T01:00:00+05:00").unwrap(), + true + ), + "-0002-12-31T20:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+0000-01-02T03:04:05Z").unwrap(), true), + "0000-01-02T03:04:05Z" + ); + assert!(parse_utc_rfc3339("-001-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn option_timestamp_reads_a_present_string_null_and_omission() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(default, with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let present: Opt = + serde_json::from_str("{\"timestamp\":\"2020-01-02T03:04:05Z\"}").unwrap(); + assert_eq!(present.timestamp, Some(at(0))); + let null: Opt = serde_json::from_str("{\"timestamp\":null}").unwrap(); + assert!(null.timestamp.is_none()); + let omitted: Opt = serde_json::from_str("{}").unwrap(); + assert!(omitted.timestamp.is_none()); + } + + #[test] + fn signed_leap_day_round_trips_and_a_non_leap_day_is_rejected() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0004-02-29T00:00:00Z").unwrap(), true), + "-0004-02-29T00:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-02-29T00:00:00Z").unwrap(), true), + "2020-02-29T00:00:00Z" + ); + assert!(parse_utc_rfc3339("-0001-02-29T00:00:00Z").is_err()); + } + + #[test] + fn years_outside_the_stored_range_are_rejected() { + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn out_of_range_offset_fails_closed() { + assert!(parse_utc_rfc3339("9999-12-31T23:59:59-01:00").is_err()); + let date = time::Date::from_calendar_date(9999, time::Month::December, 31).unwrap(); + let clock = time::Time::from_hms(23, 59, 59).unwrap(); + let offset = time::UtcOffset::from_hms(-1, 0, 0).unwrap(); + let dt = time::OffsetDateTime::new_in_offset(date, clock, offset); + assert!(format_utc(dt, true).is_err()); + assert!(format_utc(dt, false).is_err()); + } +} diff --git a/astraweave-memory/tests/behavioral_correctness_tests.rs b/astraweave-memory/tests/behavioral_correctness_tests.rs index c1c84edb23..220843df95 100644 --- a/astraweave-memory/tests/behavioral_correctness_tests.rs +++ b/astraweave-memory/tests/behavioral_correctness_tests.rs @@ -25,7 +25,6 @@ use astraweave_memory::{ ForgettingConfig, ForgettingCurve, ForgettingEngine, Memory, MemoryContent, MemoryMetadata, MemorySource, MemoryType, SpatialTemporalContext, }; -use chrono::{Duration, Utc}; // ============================================================================ // HELPER FUNCTIONS @@ -49,8 +48,8 @@ fn create_test_memory(memory_type: MemoryType, importance: f32, strength: f32) - }, }, metadata: MemoryMetadata { - created_at: Utc::now(), - last_accessed: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_accessed: time::OffsetDateTime::now_utc(), access_count: 0, importance, confidence: 1.0, @@ -73,8 +72,9 @@ fn create_aged_memory( access_count: u32, ) -> Memory { let mut memory = create_test_memory(memory_type, importance, strength); - memory.metadata.created_at = Utc::now() - Duration::days(age_days); - memory.metadata.last_accessed = Utc::now() - Duration::days(age_days / 2); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(age_days); + memory.metadata.last_accessed = + time::OffsetDateTime::now_utc() - time::Duration::days(age_days / 2); memory.metadata.access_count = access_count; memory } diff --git a/astraweave-memory/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-memory/tests/mutation_resistant_comprehensive_tests.rs index addb152b06..e66ece5e33 100644 --- a/astraweave-memory/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-memory/tests/mutation_resistant_comprehensive_tests.rs @@ -89,7 +89,6 @@ use astraweave_memory::{ TimeWindow, ValidationResult, }; -use chrono::Utc; use std::collections::HashMap; // ============================================================================= @@ -372,7 +371,7 @@ mod memory_type_tests { memory_id: "mem_123".to_string(), association_type: AssociationType::Temporal, strength: 0.75, - formed_at: Utc::now(), + formed_at: time::OffsetDateTime::now_utc(), }; assert_eq!(assoc.memory_id, "mem_123"); assert_eq!(assoc.strength, 0.75); @@ -390,8 +389,8 @@ mod memory_type_tests { memory_ids: vec!["m1".to_string(), "m2".to_string()], central_concept: "office".to_string(), importance: 0.8, - created_at: Utc::now(), - last_updated: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_updated: time::OffsetDateTime::now_utc(), }; assert_eq!(cluster.name, "Work memories"); assert_eq!(cluster.memory_ids.len(), 2); @@ -405,7 +404,7 @@ mod memory_type_tests { let state = ConsolidationState { consolidation_level: 0.5, passes: 2, - last_consolidation: Utc::now(), + last_consolidation: time::OffsetDateTime::now_utc(), needs_consolidation: false, priority: 0.7, }; @@ -467,8 +466,8 @@ mod memory_type_tests { #[test] fn time_window_fields() { - let start = Utc::now(); - let end = Utc::now(); + let start = time::OffsetDateTime::now_utc(); + let end = time::OffsetDateTime::now_utc(); let window = TimeWindow { start, end }; assert!(window.end >= window.start); } @@ -822,7 +821,7 @@ mod retrieval_tests { source_memory_id: "m1".to_string(), }; let temporal = RetrievalPath::Temporal { - reference_time: Utc::now(), + reference_time: time::OffsetDateTime::now_utc(), }; let cluster = RetrievalPath::Cluster { cluster_id: "c1".to_string(), @@ -2486,8 +2485,8 @@ mod edge_case_tests { recent_memory_ids: vec!["r1".to_string()], preferred_types: vec![MemoryType::Episodic, MemoryType::Semantic], time_window: Some(TimeWindow { - start: Utc::now(), - end: Utc::now(), + start: time::OffsetDateTime::now_utc(), + end: time::OffsetDateTime::now_utc(), }), limit: 5, }; diff --git a/astraweave-memory/tests/mutation_tests.rs b/astraweave-memory/tests/mutation_tests.rs index c6a59f6ee9..d66b6c263a 100644 --- a/astraweave-memory/tests/mutation_tests.rs +++ b/astraweave-memory/tests/mutation_tests.rs @@ -18,7 +18,6 @@ use astraweave_memory::{ RetrievalContext, RetrievalEngine, SafetyRule, SensoryData, ShareRequest, SharingConfig, SharingEngine, SharingType, TimeWindow, ValidationResult, }; -use chrono::{Duration, Utc}; use std::collections::HashMap; // ════════════════════════════════════════════════════════════════════════════ @@ -65,8 +64,8 @@ fn mutation_calculate_current_strength_decay_factor() { // formula: base = strength * e^(-0.1 * age_days * decay_factor) let mut mem = Memory::sensory("decay".to_string(), None); mem.metadata.strength = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(10); - mem.metadata.last_accessed = Utc::now() - Duration::days(5); // no access_boost + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(5); // no access_boost // With decay_factor = 1.0: base = 1.0 * e^(-0.1 * 10 * 1.0) = e^(-1.0) ≈ 0.368 mem.metadata.decay_factor = 1.0; @@ -105,7 +104,7 @@ fn mutation_calculate_current_strength_access_boost() { let mut mem_old = Memory::sensory("old_access".to_string(), None); mem_old.metadata.strength = 0.5; mem_old.metadata.decay_factor = 1.0; - mem_old.metadata.last_accessed = Utc::now() - Duration::days(5); + mem_old.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(5); // time_since_access = 5 → boost = 0.0 let s_recent = mem_recent.calculate_current_strength(); @@ -137,8 +136,8 @@ fn mutation_calculate_relevance_weights() { mem.metadata.importance = 0.0; mem.metadata.strength = 0.0; mem.metadata.decay_factor = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(30); // no recency bonus - mem.metadata.last_accessed = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); // no recency bonus + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); // Query = "hello world" → 2 words match out of 2 query words → text_sim = 1.0 let ctx = RetrievalContext { @@ -166,8 +165,8 @@ fn mutation_calculate_relevance_importance_weight() { mem.metadata.importance = 1.0; mem.metadata.strength = 0.0; mem.metadata.decay_factor = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(30); - mem.metadata.last_accessed = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let ctx = RetrievalContext { query: "nonmatching_query".to_string(), @@ -210,8 +209,8 @@ fn mutation_calculate_relevance_recency_bonus() { let mut old_mem = Memory::sensory("unique_z_content".to_string(), None); old_mem.metadata.importance = 0.0; - old_mem.metadata.created_at = Utc::now() - Duration::days(30); - old_mem.metadata.last_accessed = Utc::now() - Duration::days(30); + old_mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + old_mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); old_mem.metadata.strength = mem.metadata.strength; old_mem.metadata.decay_factor = mem.metadata.decay_factor; @@ -443,15 +442,15 @@ fn mutation_retrieval_semantic_partial_match() { #[test] fn mutation_retrieval_temporal_inside_window() { let engine = RetrievalEngine::new(RetrievalConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut mem = Memory::sensory("temporal_in".to_string(), None); - mem.metadata.created_at = now - Duration::hours(1); + mem.metadata.created_at = now - time::Duration::hours(1); let ctx = RetrievalContext { query: "temporal_in".to_string(), preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::hours(2), + start: now - time::Duration::hours(2), end: now, }), location: None, @@ -478,8 +477,8 @@ fn mutation_retrieval_old_memory_lower_score() { let fresh = Memory::sensory("test_query_word".to_string(), None); let mut old = Memory::sensory("test_query_word".to_string(), None); - old.metadata.created_at = Utc::now() - Duration::days(60); - old.metadata.last_accessed = Utc::now() - Duration::days(30); + old.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + old.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let ctx = RetrievalContext { query: "test_query_word".to_string(), @@ -540,8 +539,8 @@ fn mutation_retrieval_recency_fresh_vs_old() { // created_at = now, last_accessed = now → recency = (e^0 + e^0)/2 = 1.0 let mut old = Memory::sensory("old_mem".to_string(), None); - old.metadata.created_at = Utc::now() - Duration::days(60); - old.metadata.last_accessed = Utc::now() - Duration::days(30); + old.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + old.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let ctx = RetrievalContext { query: "fresh_mem".to_string(), @@ -978,12 +977,12 @@ fn mutation_conceptual_similarity_type_match() { // Use identical text so text_sim is high → type_match*0.3 + text_sim*0.5 = 0.3+0.5=0.8 > 0.7 threshold // Space memories far apart so they DON'T form temporal associations first let mut m1 = Memory::sensory("shared concept text".to_string(), None); - m1.metadata.created_at = Utc::now() - Duration::days(30); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); let m2 = Memory::sensory("shared concept text".to_string(), None); let mut m3 = Memory::sensory("shared concept text".to_string(), None); m3.memory_type = MemoryType::Episodic; // different type → 0+0.5=0.5 < 0.7 - m3.metadata.created_at = Utc::now() - Duration::days(30); + m3.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); // Same type + identical text → similarity = 0.3+0.5 = 0.8 >= 0.7 → association let mut memories = vec![m1.clone(), m2.clone()]; @@ -1023,9 +1022,9 @@ fn mutation_consolidation_temporal_within_window() { let engine = ConsolidationEngine::new(config); let mut m1 = Memory::sensory("temporal_a".to_string(), None); - m1.metadata.created_at = Utc::now(); + m1.metadata.created_at = time::OffsetDateTime::now_utc(); let mut m2 = Memory::sensory("temporal_b".to_string(), None); - m2.metadata.created_at = Utc::now() - Duration::hours(12); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::hours(12); let mut memories = vec![m1, m2]; let result = engine.consolidate(&mut memories).unwrap(); @@ -1112,7 +1111,7 @@ fn mutation_compress_long_text_truncated() { let mut mem = Memory::sensory(text.clone(), None); mem.metadata.permanent = false; mem.metadata.importance = 0.2; - mem.metadata.created_at = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); let mut memories = vec![mem]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -1166,7 +1165,7 @@ fn mutation_compress_too_young_not_compressed() { let text = words.join(" "); let mut mem = Memory::sensory(text.clone(), None); mem.metadata.permanent = false; - mem.metadata.created_at = Utc::now() - Duration::days(5); // age < 10 + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); // age < 10 let mut memories = vec![mem]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -1190,7 +1189,7 @@ fn mutation_compress_too_important_not_compressed() { let mut mem = Memory::sensory(text.clone(), None); mem.metadata.permanent = false; mem.metadata.importance = 0.8; // > 0.5 threshold - mem.metadata.created_at = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); let mut memories = vec![mem]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -2219,16 +2218,16 @@ fn mutation_matches_context_type_filter() { #[test] fn mutation_matches_context_time_window() { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut mem = Memory::sensory("timed".to_string(), None); - mem.metadata.created_at = now - Duration::hours(1); + mem.metadata.created_at = now - time::Duration::hours(1); // Inside window let ctx_in = RetrievalContext { query: "".to_string(), preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::hours(2), + start: now - time::Duration::hours(2), end: now, }), location: None, @@ -2243,7 +2242,7 @@ fn mutation_matches_context_time_window() { query: "".to_string(), preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::minutes(30), + start: now - time::Duration::minutes(30), end: now, }), location: None, @@ -2414,7 +2413,8 @@ fn mutation_access_boost_exactly_one_day_boundary() { let mut mem_exactly_1day = Memory::sensory("boundary".to_string(), None); mem_exactly_1day.metadata.strength = 0.5; mem_exactly_1day.metadata.decay_factor = 1.0; - mem_exactly_1day.metadata.last_accessed = Utc::now() - Duration::days(1); + mem_exactly_1day.metadata.last_accessed = + time::OffsetDateTime::now_utc() - time::Duration::days(1); // time_since_access = 1.0 day → `1.0 < 1.0` is false → no boost let mut mem_fresh = Memory::sensory("fresh".to_string(), None); @@ -2449,8 +2449,8 @@ fn mutation_access_boost_exactly_one_day_boundary() { /// Mutant <=: `start <= start` → true → excluded → doesn't match ✗ #[test] fn mutation_matches_context_at_exact_window_start() { - let now = Utc::now(); - let window_start = now - Duration::hours(2); + let now = time::OffsetDateTime::now_utc(); + let window_start = now - time::Duration::hours(2); let mut mem = Memory::sensory("at_start".to_string(), None); mem.metadata.created_at = window_start; // Exactly at window start @@ -2481,7 +2481,7 @@ fn mutation_matches_context_at_exact_window_start() { /// Mutant ==: `end == end` → true → excluded → doesn't match ✗ #[test] fn mutation_matches_context_at_exact_window_end() { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let window_end = now; let mut mem = Memory::sensory("at_end".to_string(), None); @@ -2491,7 +2491,7 @@ fn mutation_matches_context_at_exact_window_end() { query: "".to_string(), preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::hours(2), + start: now - time::Duration::hours(2), end: window_end, }), location: None, @@ -2522,7 +2522,7 @@ fn mutation_forgetting_decay_reduces_strength() { m.memory_type = MemoryType::Working; m }; - old_mem.metadata.created_at = Utc::now() - Duration::days(5); + old_mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); old_mem.metadata.strength = 1.0; old_mem.metadata.importance = 0.5; // neutral old_mem.metadata.access_count = 0; @@ -2564,7 +2564,7 @@ fn mutation_forgetting_importance_modifier() { m.memory_type = MemoryType::Episodic; m }; - high_imp.metadata.created_at = Utc::now() - Duration::days(7); + high_imp.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); high_imp.metadata.strength = 1.0; high_imp.metadata.importance = 1.0; // modifier = 1.0 + (1.0-0.5)*0.5 = 1.25 high_imp.metadata.access_count = 0; @@ -2574,7 +2574,7 @@ fn mutation_forgetting_importance_modifier() { m.memory_type = MemoryType::Episodic; m }; - low_imp.metadata.created_at = Utc::now() - Duration::days(7); + low_imp.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); low_imp.metadata.strength = 1.0; low_imp.metadata.importance = 0.0; // modifier = 1.0 + (0.0-0.5)*0.5 = 0.75 low_imp.metadata.access_count = 0; @@ -2606,7 +2606,7 @@ fn mutation_forgetting_access_modifier() { m.memory_type = MemoryType::Episodic; m }; - accessed.metadata.created_at = Utc::now() - Duration::days(7); + accessed.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); accessed.metadata.strength = 1.0; accessed.metadata.importance = 0.5; accessed.metadata.access_count = 10; // access_frequency = 10/7 ≈ 1.43, modifier = 1+1.43*0.3=1.43 @@ -2616,7 +2616,7 @@ fn mutation_forgetting_access_modifier() { m.memory_type = MemoryType::Episodic; m }; - not_accessed.metadata.created_at = Utc::now() - Duration::days(7); + not_accessed.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); not_accessed.metadata.strength = 1.0; not_accessed.metadata.importance = 0.5; not_accessed.metadata.access_count = 0; // modifier = 1.0 @@ -2644,7 +2644,7 @@ fn mutation_forgetting_total_strength_lost() { m.memory_type = MemoryType::Episodic; m }; - mem.metadata.created_at = Utc::now() - Duration::days(7); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); mem.metadata.strength = 1.0; mem.metadata.importance = 0.5; mem.metadata.access_count = 0; @@ -2685,7 +2685,7 @@ fn mutation_forgetting_should_forget_weak_memory() { m.memory_type = MemoryType::Working; m }; - mem.metadata.created_at = Utc::now() - Duration::days(5); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(5); mem.metadata.strength = 1.0; mem.metadata.importance = 0.5; mem.metadata.access_count = 0; @@ -2722,7 +2722,7 @@ fn mutation_forgetting_spaced_repetition_bonus() { m.memory_type = MemoryType::Episodic; m }; - m.metadata.created_at = Utc::now() - Duration::days(7); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); m.metadata.strength = 1.0; m.metadata.importance = 0.5; m.metadata.access_count = 5; // >1 to trigger spaced repetition @@ -2772,7 +2772,7 @@ fn mutation_compress_at_exact_min_age_boundary() { let mut mem = Memory::sensory(text.clone(), None); mem.metadata.permanent = false; mem.metadata.importance = 0.1; - mem.metadata.created_at = Utc::now() - Duration::days(10); // EXACTLY at boundary + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); // EXACTLY at boundary let mut memories = vec![mem]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -2800,7 +2800,7 @@ fn mutation_compress_at_exact_importance_boundary() { let mut mem = Memory::sensory(text.clone(), None); mem.metadata.permanent = false; mem.metadata.importance = 0.5; // EXACTLY at threshold - mem.metadata.created_at = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); let mut memories = vec![mem]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -2828,7 +2828,7 @@ fn mutation_compress_preserves_emotional_context() { let mut mem = Memory::sensory(text.clone(), None); mem.metadata.permanent = false; mem.metadata.importance = 0.1; - mem.metadata.created_at = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); // Add sensory data that we want preserved mem.content.sensory_data = Some(SensoryData { visual: Some("detailed visual scene with many elements and textures and colors and lighting and shadows and reflections".to_string()), @@ -2868,8 +2868,8 @@ fn mutation_relevance_strength_contribution_positive() { mem.metadata.importance = 0.0; mem.metadata.strength = 1.0; mem.metadata.decay_factor = 0.0; // no decay → current_strength stays 1.0 - mem.metadata.created_at = Utc::now() - Duration::days(30); - mem.metadata.last_accessed = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let ctx = RetrievalContext { query: "completely_disjoint_query_abc".to_string(), @@ -2903,8 +2903,8 @@ fn mutation_relevance_strength_versus_zero() { mem.metadata.importance = 0.0; mem.metadata.strength = 0.0; mem.metadata.decay_factor = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(30); - mem.metadata.last_accessed = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let ctx = RetrievalContext { query: "completely_disjoint_query_abc".to_string(), @@ -2933,8 +2933,8 @@ fn mutation_relevance_recency_exact_value_3days() { mem.metadata.importance = 0.0; mem.metadata.strength = 0.0; mem.metadata.decay_factor = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(3); - mem.metadata.last_accessed = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(3); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let ctx = RetrievalContext { query: "nonmatching_zyx_999".to_string(), @@ -2964,8 +2964,8 @@ fn mutation_relevance_recency_absent_for_old_memory() { mem.metadata.importance = 0.0; mem.metadata.strength = 0.0; mem.metadata.decay_factor = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(30); - mem.metadata.last_accessed = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let ctx = RetrievalContext { query: "nonmatching_old_test".to_string(), @@ -3108,8 +3108,8 @@ fn mutation_manager_retrieve_threshold_filters_low_relevance() { mem.metadata.importance = 0.05; mem.metadata.strength = 0.1; mem.metadata.decay_factor = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(60); - mem.metadata.last_accessed = Utc::now() - Duration::days(60); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(60); mgr.store_memory(mem).unwrap(); let ctx = RetrievalContext { @@ -3176,8 +3176,8 @@ fn mutation_manager_retrieve_both_above_and_below_threshold() { bad.metadata.importance = 0.01; bad.metadata.strength = 0.01; bad.metadata.decay_factor = 1.0; - bad.metadata.created_at = Utc::now() - Duration::days(90); - bad.metadata.last_accessed = Utc::now() - Duration::days(90); + bad.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(90); + bad.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(90); mgr.store_memory(bad).unwrap(); let ctx = RetrievalContext { @@ -3258,8 +3258,8 @@ fn mutation_manager_retrieve_exactly_at_threshold() { mem.metadata.importance = 1.0; mem.metadata.strength = 0.0; // zero strength mem.metadata.decay_factor = 1.0; - mem.metadata.created_at = Utc::now() - Duration::days(30); // no recency bonus - mem.metadata.last_accessed = Utc::now() - Duration::days(30); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); // no recency bonus + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); mgr.store_memory(mem).unwrap(); // Query with no matching words → text_similarity = 0 @@ -3552,7 +3552,7 @@ fn mutation_recorder_with_flush_interval_not_default() { /// Helper: create an episodic memory at a specific timestamp with optional location and participants fn make_timed_memory( text: &str, - when: chrono::DateTime, + when: time::OffsetDateTime, location: Option<&str>, participants: Vec<&str>, ) -> Memory { @@ -3570,10 +3570,10 @@ fn mutation_consolidation_temporal_within_window_v2() { // Two memories 1 hour apart within default 24h window → temporal association formed let config = ConsolidationConfig::default(); let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event alpha", now, None, vec![]), - make_timed_memory("event beta", now - Duration::hours(1), None, vec![]), + make_timed_memory("event beta", now - time::Duration::hours(1), None, vec![]), ]; let result = engine.consolidate(&mut memories).unwrap(); assert!( @@ -3587,10 +3587,10 @@ fn mutation_consolidation_temporal_outside_window() { // Two memories 48 hours apart > 24h window → no temporal association let config = ConsolidationConfig::default(); let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event alpha", now, None, vec![]), - make_timed_memory("event beta", now - Duration::hours(48), None, vec![]), + make_timed_memory("event beta", now - time::Duration::hours(48), None, vec![]), ]; let result = engine.consolidate(&mut memories).unwrap(); assert_eq!( @@ -3604,12 +3604,17 @@ fn mutation_consolidation_temporal_strength_increases_closer() { // Two memories close together should have stronger association than far apart let config = ConsolidationConfig::default(); let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // Close pair: 30 minutes apart let mut close_memories = vec![ make_timed_memory("event close A", now, None, vec![]), - make_timed_memory("event close B", now - Duration::minutes(30), None, vec![]), + make_timed_memory( + "event close B", + now - time::Duration::minutes(30), + None, + vec![], + ), ]; engine.consolidate(&mut close_memories).unwrap(); let close_strength = close_memories[0] @@ -3621,7 +3626,7 @@ fn mutation_consolidation_temporal_strength_increases_closer() { // Far pair: 20 hours apart let mut far_memories = vec![ make_timed_memory("event far A", now, None, vec![]), - make_timed_memory("event far B", now - Duration::hours(20), None, vec![]), + make_timed_memory("event far B", now - time::Duration::hours(20), None, vec![]), ]; engine.consolidate(&mut far_memories).unwrap(); let far_strength = far_memories[0] @@ -3644,12 +3649,12 @@ fn mutation_consolidation_spatial_same_location_v2() { // Two memories at same location → spatial association formed let config = ConsolidationConfig::default(); let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event at forest", now, Some("forest"), vec![]), make_timed_memory( "another at forest", - now - Duration::days(30), + now - time::Duration::days(30), Some("forest"), vec![], ), @@ -3666,12 +3671,12 @@ fn mutation_consolidation_spatial_different_location() { // Two memories at different locations → NO spatial association let config = ConsolidationConfig::default(); let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event at forest", now, Some("forest"), vec![]), make_timed_memory( "event at cave", - now - Duration::days(30), + now - time::Duration::days(30), Some("cave"), vec![], ), @@ -3688,12 +3693,12 @@ fn mutation_consolidation_spatial_strength_is_high() { // Spatial association strength should be 0.8 (hardcoded in source) let config = ConsolidationConfig::default(); let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event A at castle", now, Some("castle"), vec![]), make_timed_memory( "event B at castle", - now - Duration::days(30), + now - time::Duration::days(30), Some("castle"), vec![], ), @@ -3720,7 +3725,7 @@ fn mutation_consolidation_conceptual_high_overlap() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory( "the brave knight fought the dragon in the castle", @@ -3730,7 +3735,7 @@ fn mutation_consolidation_conceptual_high_overlap() { ), make_timed_memory( "the brave knight fought the dragon in the castle", - now - Duration::days(30), + now - time::Duration::days(30), None, vec!["knight"], ), @@ -3747,10 +3752,15 @@ fn mutation_consolidation_conceptual_no_overlap() { // Two memories with completely different words → no conceptual association let config = ConsolidationConfig::default(); let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("alpha bravo charlie", now, None, vec![]), - make_timed_memory("xray yankee zulu", now - Duration::days(30), None, vec![]), + make_timed_memory( + "xray yankee zulu", + now - time::Duration::days(30), + None, + vec![], + ), ]; let result = engine.consolidate(&mut memories).unwrap(); assert_eq!( @@ -3767,7 +3777,7 @@ fn mutation_consolidation_updates_strength() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![make_timed_memory("event one", now, None, vec![])]; memories[0].metadata.strength = 0.5; let old_strength = memories[0].metadata.strength; @@ -3786,7 +3796,7 @@ fn mutation_consolidation_strength_capped_at_one() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![make_timed_memory("event max", now, None, vec![])]; memories[0].metadata.strength = 0.9; engine.consolidate(&mut memories).unwrap(); @@ -3804,7 +3814,7 @@ fn mutation_consolidation_result_total() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory( "battle at forest clearing", @@ -3814,7 +3824,7 @@ fn mutation_consolidation_result_total() { ), make_timed_memory( "battle at forest clearing", - now - Duration::hours(1), + now - time::Duration::hours(1), Some("forest"), vec!["hero"], ), @@ -3836,18 +3846,18 @@ fn mutation_consolidation_respects_max_associations() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event A", now, Some("castle"), vec![]), make_timed_memory( "event B", - now - Duration::minutes(30), + now - time::Duration::minutes(30), Some("castle"), vec![], ), make_timed_memory( "event C", - now - Duration::minutes(60), + now - time::Duration::minutes(60), Some("castle"), vec![], ), @@ -3877,7 +3887,7 @@ fn mutation_compression_eligible_memory_compressed() { "this is a long text with many words that should be compressed when old enough to qualify for compression processing and optimization routines in the engine".to_string(), None, ); - memory.metadata.created_at = Utc::now() - Duration::days(60); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); memory.metadata.importance = 0.1; let mut memories = vec![memory]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -3895,7 +3905,7 @@ fn mutation_compression_permanent_not_compressed() { "important fact about the world".to_string(), "fact".to_string(), ); - memory.metadata.created_at = Utc::now() - Duration::days(365); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); memory.metadata.permanent = true; memory.metadata.importance = 0.01; let mut memories = vec![memory]; @@ -3926,7 +3936,7 @@ fn mutation_compression_high_importance_not_compressed() { }; let engine = CompressionEngine::new(config); let mut memory = Memory::sensory("old but important memory text".to_string(), None); - memory.metadata.created_at = Utc::now() - Duration::days(100); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); memory.metadata.importance = 0.9; let mut memories = vec![memory]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -3947,7 +3957,7 @@ fn mutation_compression_stats_count() { .to_string(), None, ); - old_memory.metadata.created_at = Utc::now() - Duration::days(60); + old_memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); old_memory.metadata.importance = 0.1; let new_memory = Memory::sensory("new memory".to_string(), None); let mut memories = vec![old_memory, new_memory]; @@ -3972,7 +3982,7 @@ fn mutation_compression_size_reduction_positive() { the text needs to be long enough to trigger meaningful compression behavior and it must also have enough words so that the compression ratio leaves room for both the first portion and the last portion of the text to be included in the final result".to_string(), None, ); - memory.metadata.created_at = Utc::now() - Duration::days(60); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); memory.metadata.importance = 0.1; let mut memories = vec![memory]; let result = engine.compress_memories(&mut memories).unwrap(); @@ -4015,7 +4025,7 @@ fn mutation_retrieval_matching_query_retrieved() { fn mutation_retrieval_temporal_in_window_high_score() { let engine = RetrievalEngine::new(RetrievalConfig::default()); let memory = Memory::sensory("test data".to_string(), None); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let context = RetrievalContext { query: "test data".to_string(), emotional_state: None, @@ -4023,8 +4033,8 @@ fn mutation_retrieval_temporal_in_window_high_score() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), - end: now + Duration::days(1), + start: now - time::Duration::days(1), + end: now + time::Duration::days(1), }), limit: 10, }; @@ -4121,7 +4131,7 @@ fn mutation_forgetting_old_weak_memory_forgotten() { let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); let mut memory = Memory::sensory("old fading memory".to_string(), None); - memory.metadata.created_at = Utc::now() - Duration::days(365); + memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); memory.metadata.strength = 0.01; memory.metadata.permanent = false; let mut memories = vec![memory]; @@ -4226,7 +4236,7 @@ fn make_populated_storage(episodes: Vec) -> MemoryStorage { /// Helper: create a minimal Episode with given category and quality fn make_test_episode(category: EpisodeCategory, quality_score: f32) -> Episode { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut ep = Episode::new("test_ep".to_string(), category.clone()); for i in 0..3 { ep.observations.push(Observation::new( @@ -4440,12 +4450,12 @@ fn mutation_storage_delete_nonexistent() { fn mutation_storage_prune_old() { let mut storage = MemoryStorage::in_memory().unwrap(); let mut old_memory = Memory::sensory("old one".to_string(), None); - old_memory.metadata.created_at = Utc::now() - Duration::days(365); + old_memory.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); let new_memory = Memory::sensory("new one".to_string(), None); storage.store_memory(&old_memory).unwrap(); storage.store_memory(&new_memory).unwrap(); assert_eq!(storage.count_memories().unwrap(), 2); - let cutoff = (Utc::now() - Duration::days(30)).timestamp(); + let cutoff = (time::OffsetDateTime::now_utc() - time::Duration::days(30)).unix_timestamp(); let pruned = storage.prune_old(cutoff).unwrap(); assert!(pruned > 0); } @@ -4585,10 +4595,10 @@ fn mutation_consol_temporal_exact_strength() { // Expected: 0.5 + (1.0 - 3*3600/86400) = 0.5 + 0.875 = 1.375 // If + → * (L92): 0.5 * 0.875 = 0.4375 let engine = ConsolidationEngine::new(ConsolidationConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("alpha", now, None, vec![]), - make_timed_memory("beta", now - Duration::hours(3), None, vec![]), + make_timed_memory("beta", now - time::Duration::hours(3), None, vec![]), ]; engine.consolidate(&mut memories).unwrap(); let strength = memories[0].associations.first().unwrap().strength; @@ -4610,10 +4620,10 @@ fn mutation_consol_temporal_exact_strength() { fn mutation_consol_no_duplicate_assoc() { // Run consolidate twice — should NOT create duplicate associations (catches L84 == → !=) let engine = ConsolidationEngine::new(ConsolidationConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("alpha", now, None, vec![]), - make_timed_memory("beta", now - Duration::hours(1), None, vec![]), + make_timed_memory("beta", now - time::Duration::hours(1), None, vec![]), ]; engine.consolidate(&mut memories).unwrap(); let count1 = memories[0].associations.len(); @@ -4629,12 +4639,12 @@ fn mutation_consol_no_duplicate_assoc() { fn mutation_consol_spatial_exact_strength() { // Same-location memories get strength 0.8 (catches L120 == → !=) let engine = ConsolidationEngine::new(ConsolidationConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event at forest", now, Some("forest"), vec![]), make_timed_memory( "another at forest", - now - Duration::days(30), + now - time::Duration::days(30), Some("forest"), vec![], ), @@ -4662,12 +4672,12 @@ fn mutation_consol_conceptual_similarity_word_overlap() { association_threshold: 0.1, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("the brave warrior fought", now, None, vec![]), make_timed_memory( "the brave warrior rested", - now - Duration::days(60), + now - time::Duration::days(60), None, vec![], ), @@ -4695,12 +4705,12 @@ fn mutation_consol_conceptual_with_participants() { association_threshold: 0.01, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("event one", now, None, vec!["alice", "bob"]), make_timed_memory( "event two", - now - Duration::days(60), + now - time::Duration::days(60), None, vec!["alice", "charlie"], ), @@ -4726,7 +4736,7 @@ fn mutation_consol_state_boost_exact() { consolidation_boost: 0.2, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = make_timed_memory("single memory", now, None, vec![]); m.metadata.strength = 0.5; let mut memories = vec![m]; @@ -4807,7 +4817,7 @@ fn mutation_compression_text_division() { .collect::>() .join(" "); let mut m = Memory::sensory(long_text.clone(), None); - m.metadata.created_at = Utc::now() - Duration::days(10); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); m.metadata.importance = 0.1; let original_len = m.content.text.split_whitespace().count(); let mut memories = vec![m]; @@ -4928,9 +4938,9 @@ fn mutation_retrieval_exact_relevance_score() { fn mutation_retrieval_temporal_within_window() { // Memory within time_window should get score 1.0 (catches L202-203) let engine = RetrievalEngine::new(RetrievalConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::sensory("test memory".to_string(), None); - m.metadata.created_at = now - Duration::hours(2); + m.metadata.created_at = now - time::Duration::hours(2); let context = RetrievalContext { query: "test".to_string(), emotional_state: None, @@ -4938,7 +4948,7 @@ fn mutation_retrieval_temporal_within_window() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -4956,9 +4966,9 @@ fn mutation_retrieval_temporal_within_window() { fn mutation_retrieval_temporal_decay_outside_window() { // Memory outside window should have exponential decay score (catches L218 / → %,*) let engine = RetrievalEngine::new(RetrievalConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::sensory("test memory".to_string(), None); - m.metadata.created_at = now - Duration::days(14); + m.metadata.created_at = now - time::Duration::days(14); let context = RetrievalContext { query: "test".to_string(), emotional_state: None, @@ -4966,7 +4976,7 @@ fn mutation_retrieval_temporal_decay_outside_window() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -4992,13 +5002,13 @@ fn mutation_retrieval_temporal_decay_outside_window() { fn mutation_retrieval_recency_score_range() { // Recent memory vs old memory — recency scores should differ (catches L248-249 / → %,*) let engine = RetrievalEngine::new(RetrievalConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut recent = Memory::sensory("recent test".to_string(), None); - recent.metadata.created_at = now - Duration::hours(1); - recent.metadata.last_accessed = now - Duration::hours(1); + recent.metadata.created_at = now - time::Duration::hours(1); + recent.metadata.last_accessed = now - time::Duration::hours(1); let mut old = Memory::sensory("old test".to_string(), None); - old.metadata.created_at = now - Duration::days(60); - old.metadata.last_accessed = now - Duration::days(60); + old.metadata.created_at = now - time::Duration::days(60); + old.metadata.last_accessed = now - time::Duration::days(60); let context = RetrievalContext { query: "test".to_string(), emotional_state: None, @@ -5090,7 +5100,7 @@ fn mutation_forgetting_strength_decay_formula() { let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); let mut m = Memory::episodic("old event".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(10); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); let mut memories = vec![m]; engine.apply_forgetting(&mut memories).unwrap(); assert!( @@ -5114,7 +5124,7 @@ fn mutation_forgetting_importance_modifier_v2() { // High importance memory should retain more strength (catches L201 > logic) let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); - let age = Utc::now() - Duration::days(7); + let age = time::OffsetDateTime::now_utc() - time::Duration::days(7); let mut m_low = Memory::episodic("low importance".to_string(), vec![], None); m_low.metadata.created_at = age; m_low.metadata.importance = 0.1; @@ -5149,7 +5159,7 @@ fn mutation_forgetting_should_forget_threshold() { let engine = ForgettingEngine::new(config); // Set strength well below default threshold (0.1) let mut m = Memory::sensory("forgettable".to_string(), None); - m.metadata.created_at = Utc::now() - Duration::days(365); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); m.metadata.strength = 0.001; m.metadata.permanent = false; let mut memories = vec![m]; @@ -5227,7 +5237,7 @@ fn mutation_forgetting_access_modifier_effect() { // Memory with many accesses should decay slower (catches L210 > → >= and L212 * → +) let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); - let age = Utc::now() - Duration::days(7); + let age = time::OffsetDateTime::now_utc() - time::Duration::days(7); let mut m_accessed = Memory::episodic("accessed".to_string(), vec![], None); m_accessed.metadata.created_at = age; m_accessed.metadata.access_count = 50; @@ -5765,16 +5775,16 @@ fn mutation_storage_prune_returns_count() { // Prune should return actual count of deleted, not Ok(1) (catches L294 → Ok(1)) let mut storage = MemoryStorage::in_memory().unwrap(); let mut m1 = Memory::sensory("old1".to_string(), None); - m1.metadata.created_at = Utc::now() - Duration::days(100); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); let mut m2 = Memory::sensory("old2".to_string(), None); - m2.metadata.created_at = Utc::now() - Duration::days(100); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); let mut m3 = Memory::sensory("recent".to_string(), None); - m3.metadata.created_at = Utc::now(); + m3.metadata.created_at = time::OffsetDateTime::now_utc(); storage.store_memory(&m1).unwrap(); storage.store_memory(&m2).unwrap(); storage.store_memory(&m3).unwrap(); // Prune memories older than 50 days — should delete 2 - let before_ts = (Utc::now() - Duration::days(50)).timestamp(); + let before_ts = (time::OffsetDateTime::now_utc() - time::Duration::days(50)).unix_timestamp(); let deleted = storage.prune_old(before_ts).unwrap(); assert_eq!( deleted, 2, @@ -6064,7 +6074,7 @@ fn mutation_forgetting_decay_negative_exponent() { let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); let mut m = Memory::episodic("decay_test".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(7); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); let mut memories = vec![m]; engine.apply_forgetting(&mut memories).unwrap(); assert!(!memories.is_empty(), "7-day episodic memory should survive"); @@ -6083,9 +6093,9 @@ fn mutation_temporal_score_negative_exponent() { // Formula: (-min_distance / 7.0).exp() // Without negative: (min_distance / 7.0).exp() = huge number (clamped down somewhere) let engine = RetrievalEngine::new(RetrievalConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::sensory("temporal test".to_string(), None); - m.metadata.created_at = now - Duration::days(30); // 30 days before window + m.metadata.created_at = now - time::Duration::days(30); // 30 days before window let context = RetrievalContext { query: "temporal test".to_string(), emotional_state: None, @@ -6093,7 +6103,7 @@ fn mutation_temporal_score_negative_exponent() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -6253,7 +6263,7 @@ fn mutation_compression_text_word_division() { .collect::>() .join(" "); let mut m = Memory::sensory(text, None); - m.metadata.created_at = Utc::now() - Duration::days(10); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); m.metadata.importance = 0.1; let mut memories = vec![m]; let _ = engine.compress_memories(&mut memories).unwrap(); @@ -6287,7 +6297,7 @@ fn mutation_retrieval_relevance_score_additive() { recency_boost: true, ..RetrievalConfig::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::sensory("battle sword combat warrior".to_string(), None); m.metadata.created_at = now; // Very recent — high recency m.metadata.importance = 0.9; // High importance @@ -6298,8 +6308,8 @@ fn mutation_retrieval_relevance_score_additive() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), - end: now + Duration::days(1), + start: now - time::Duration::days(1), + end: now + time::Duration::days(1), }), limit: 10, }; @@ -6319,9 +6329,9 @@ fn mutation_retrieval_temporal_within_window_score() { // catches retrieval.rs:202-203 (>= → <, && → ||, <= → >) // Memory WITHIN time window should get temporal score 1.0 let engine = RetrievalEngine::new(RetrievalConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::sensory("temporal within".to_string(), None); - m.metadata.created_at = now - Duration::hours(6); // Within a 2-day window + m.metadata.created_at = now - time::Duration::hours(6); // Within a 2-day window let context = RetrievalContext { query: "temporal within".to_string(), emotional_state: None, @@ -6329,7 +6339,7 @@ fn mutation_retrieval_temporal_within_window_score() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -6359,7 +6369,7 @@ fn mutation_retrieval_recency_score_division() { recency_boost: true, ..RetrievalConfig::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::sensory("fresh memory".to_string(), None); m.metadata.created_at = now; m.metadata.last_accessed = now; @@ -6409,7 +6419,7 @@ fn mutation_forgetting_importance_modifier_formula() { let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); // Two memories: importance 0.1 and importance 0.9, both 7 days old episodic - let age = Utc::now() - Duration::days(7); + let age = time::OffsetDateTime::now_utc() - time::Duration::days(7); let mut m_low = Memory::episodic("low imp".to_string(), vec![], None); m_low.metadata.created_at = age; m_low.metadata.importance = 0.1; @@ -6444,7 +6454,7 @@ fn mutation_forgetting_access_count_boundary_one() { // Test with access_count = 1 vs 0 vs 2 let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); - let age = Utc::now() - Duration::days(7); + let age = time::OffsetDateTime::now_utc() - time::Duration::days(7); // access_count = 0 let mut m0 = Memory::episodic("acc0".to_string(), vec![], None); m0.metadata.created_at = age; @@ -6554,14 +6564,14 @@ fn mutation_consolidation_conceptual_similarity_division() { association_threshold: 0.01, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // 2 memories with specific word overlap // "a b c d e" and "a b c x y" → 3 common out of 5 total = 0.6 overlap let mut memories = vec![ make_timed_memory("alpha bravo charlie delta echo", now, None, vec![]), make_timed_memory( "alpha bravo charlie xray yankee", - now - Duration::days(60), + now - time::Duration::days(60), None, vec![], ), @@ -6993,11 +7003,16 @@ fn mutation_consolidation_spatial_equality_check() { association_threshold: 0.01, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // DIFFERENT locations — should NOT form spatial associations let mut diff_memories = vec![ make_timed_memory("event a", now, Some("forest"), vec![]), - make_timed_memory("event b", now - Duration::days(30), Some("cave"), vec![]), + make_timed_memory( + "event b", + now - time::Duration::days(30), + Some("cave"), + vec![], + ), ]; engine.consolidate(&mut diff_memories).unwrap(); let spatial_diff = diff_memories[0] @@ -7018,12 +7033,12 @@ fn mutation_consolidation_conceptual_equality_check() { association_threshold: 0.01, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("test memorization data", now, None, vec![]), make_timed_memory( "test memorization data", - now - Duration::days(30), + now - time::Duration::days(30), None, vec![], ), @@ -7054,13 +7069,13 @@ fn mutation_consolidation_state_update_additive() { // catches consolidation.rs:214 += → *= // strength += boost should ADD, NOT multiply let engine = ConsolidationEngine::new(ConsolidationConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::sensory("state test".to_string(), None); m.metadata.strength = 0.3; // Low initial strength let initial_strength = m.metadata.strength; let mut memories = vec![ m, - make_timed_memory("other", now - Duration::hours(1), None, vec![]), + make_timed_memory("other", now - time::Duration::hours(1), None, vec![]), ]; engine.consolidate(&mut memories).unwrap(); // += boost: strength should be > initial (0.3 + boost) @@ -7373,7 +7388,7 @@ fn mutation_forgetting_decay_with_high_access() { let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); let mut m = Memory::episodic("high_access".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(7); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); m.metadata.access_count = 10; m.metadata.importance = 0.9; let mut memories = vec![m]; @@ -7408,7 +7423,7 @@ fn mutation_compression_ratio_boundary_values() { .collect::>() .join(" "); let mut m = Memory::sensory(text, None); - m.metadata.created_at = Utc::now() - Duration::days(10); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(10); m.metadata.importance = 0.1; let mut memories = vec![m]; engine.compress_memories(&mut memories).unwrap(); @@ -7478,13 +7493,13 @@ fn mutation_retrieval_temporal_decay_rate() { // With * → +: (-7 + 7).exp() = exp(0) = 1.0 (wrong!) // With / → *: (-7 * 7).exp() = exp(-49) ≈ 0 (too aggressive) let engine = RetrievalEngine::new(RetrievalConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // Memory exactly 7 days before window start let mut m7 = Memory::sensory("seven days away".to_string(), None); - m7.metadata.created_at = now - Duration::days(14); + m7.metadata.created_at = now - time::Duration::days(14); // Memory exactly 1 day before window start let mut m1 = Memory::sensory("one day away".to_string(), None); - m1.metadata.created_at = now - Duration::days(2); + m1.metadata.created_at = now - time::Duration::days(2); let context = RetrievalContext { query: "seven days away one day away".to_string(), emotional_state: None, @@ -7492,7 +7507,7 @@ fn mutation_retrieval_temporal_decay_rate() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -7522,13 +7537,13 @@ fn mutation_consolidation_similarity_boolean_operators() { association_threshold: 0.01, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // Two completely different memories — should have NO conceptual association let mut memories = vec![ make_timed_memory("unique word alpha", now, None, vec!["tag1"]), make_timed_memory( "different phrase beta", - now - Duration::days(30), + now - time::Duration::days(30), None, vec!["tag2"], ), @@ -7559,11 +7574,11 @@ fn mutation_forgetting_retention_threshold_exact() { let engine = ForgettingEngine::new(config); // Memory with strength ABOVE threshold — should survive let mut m_above = Memory::episodic("above_ret".to_string(), vec![], None); - m_above.metadata.created_at = Utc::now(); // Fresh, so won't decay + m_above.metadata.created_at = time::OffsetDateTime::now_utc(); // Fresh, so won't decay m_above.metadata.strength = 0.5; // Memory with strength BELOW threshold — should be forgotten let mut m_below = Memory::episodic("below_ret".to_string(), vec![], None); - m_below.metadata.created_at = Utc::now() - Duration::days(365); // Very old + m_below.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); // Very old m_below.metadata.importance = 0.0; m_below.metadata.strength = 0.1; // Below threshold let mut memories = vec![m_above, m_below]; @@ -7669,13 +7684,13 @@ fn mutation_consolidation_same_location_spatial() { association_threshold: 0.01, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // SAME location — should form spatial associations let mut memories = vec![ make_timed_memory("event in forest", now, Some("forest"), vec![]), make_timed_memory( "another event in forest", - now - Duration::days(30), + now - time::Duration::days(30), Some("forest"), vec![], ), @@ -7844,12 +7859,12 @@ fn mutation_consolidation_both_directions() { association_threshold: 0.01, ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory("shared concept idea", now, None, vec![]), make_timed_memory( "shared concept idea", - now - Duration::days(30), + now - time::Duration::days(30), None, vec![], ), @@ -7870,7 +7885,7 @@ fn mutation_forgetting_permanent_memories_preserved() { let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); let mut m = Memory::episodic("permanent_data".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(365 * 10); // 10 years old + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365 * 10); // 10 years old m.metadata.strength = 0.001; // Very weak m.metadata.importance = 0.0; m.metadata.permanent = true; // BUT permanent! @@ -7887,7 +7902,7 @@ fn mutation_forgetting_very_old_semantic_survives() { let config = ForgettingConfig::default(); let engine = ForgettingEngine::new(config); let mut m = Memory::semantic("important fact".to_string(), "knowledge".to_string()); - m.metadata.created_at = Utc::now() - Duration::days(90); // 90 days old + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(90); // 90 days old m.metadata.importance = 0.5; let mut memories = vec![m]; engine.apply_forgetting(&mut memories).unwrap(); @@ -7912,7 +7927,7 @@ fn make_combat_episode_exact( duration_ms: u64, resources_used: f32, ) -> Episode { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut ep = Episode::new("boundary_ep".to_string(), EpisodeCategory::Combat); ep.observations.push(Observation::new( 0, @@ -7943,7 +7958,7 @@ fn make_combat_episode_exact( } fn make_puzzle_episode_exact(success_rating: f32, duration_ms: u64) -> Episode { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut ep = Episode::new("puzzle_ep".to_string(), EpisodeCategory::Puzzle); ep.observations.push(Observation::new( 0, @@ -8529,7 +8544,7 @@ fn make_episode_with_n_actions( serde_json::json!({"player_health": 100.0}), )); } - ep.end_time = Some(Utc::now().into()); + ep.end_time = Some(time::OffsetDateTime::now_utc().into()); ep.outcome = Some(outcome); ep } @@ -9127,8 +9142,8 @@ fn mutation_consolidation_spatial_same_location_r6() { ), ]; // Set creation times far apart to avoid temporal association stealing the slot - memories[0].metadata.created_at = chrono::Utc::now() - chrono::Duration::days(30); - memories[1].metadata.created_at = chrono::Utc::now(); + memories[0].metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + memories[1].metadata.created_at = time::OffsetDateTime::now_utc(); let result = engine.consolidate(&mut memories).unwrap(); assert!( result.spatial_associations > 0, @@ -9155,8 +9170,8 @@ fn mutation_consolidation_spatial_different_location_r6() { Some("cave".to_string()), ), ]; - memories[0].metadata.created_at = chrono::Utc::now() - chrono::Duration::days(30); - memories[1].metadata.created_at = chrono::Utc::now(); + memories[0].metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + memories[1].metadata.created_at = time::OffsetDateTime::now_utc(); let result = engine.consolidate(&mut memories).unwrap(); assert_eq!( result.spatial_associations, 0, @@ -9180,8 +9195,8 @@ fn mutation_consolidation_conceptual_at_threshold_r6() { Memory::semantic("alpha beta delta".to_string(), "test".to_string()), ]; // Separate creation times to avoid temporal association stealing the slot - memories[0].metadata.created_at = chrono::Utc::now() - chrono::Duration::days(30); - memories[1].metadata.created_at = chrono::Utc::now(); + memories[0].metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + memories[1].metadata.created_at = time::OffsetDateTime::now_utc(); // Same type = 0.3, text overlap = 2/3 words = 0.667 * 0.5 = 0.333 // Total = 0.633, above 0.3 threshold let result = engine.consolidate(&mut memories).unwrap(); @@ -9206,8 +9221,8 @@ fn mutation_consolidation_conceptual_similarity_text_r6() { Memory::semantic("cat dog fish".to_string(), "animals".to_string()), Memory::semantic("cat dog bird".to_string(), "animals".to_string()), ]; - memories[0].metadata.created_at = chrono::Utc::now() - chrono::Duration::days(30); - memories[1].metadata.created_at = chrono::Utc::now(); + memories[0].metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(30); + memories[1].metadata.created_at = time::OffsetDateTime::now_utc(); // Type match = 0.3, common_words = 2 ("cat","dog"), min_len = 3 // correct: text_sim = 2/3 = 0.667, total += 0.667*0.5 = 0.333 // L200 *: text_sim = 2*3 = 6.0, total += 6.0*0.5 = 3.0 @@ -9296,8 +9311,8 @@ fn mutation_forgetting_importance_modifier_r6() { // Create memory with high importance, aged 1 day let mut mem = Memory::episodic("Important memory".to_string(), vec![], None); mem.metadata.importance = 0.9; - mem.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(1); - mem.metadata.last_accessed = chrono::Utc::now() - chrono::Duration::days(1); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); + mem.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(1); let mut memories = vec![mem]; let original_strength = memories[0].metadata.strength; engine.apply_forgetting(&mut memories).unwrap(); @@ -9312,8 +9327,8 @@ fn mutation_forgetting_importance_modifier_r6() { // Create another with low importance for comparison let mut mem_low = Memory::episodic("Low importance".to_string(), vec![], None); mem_low.metadata.importance = 0.1; - mem_low.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(1); - mem_low.metadata.last_accessed = chrono::Utc::now() - chrono::Duration::days(1); + mem_low.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); + mem_low.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(1); let mut mems_low = vec![mem_low]; engine.apply_forgetting(&mut mems_low).unwrap(); let s_low = mems_low[0].metadata.strength; @@ -9341,16 +9356,16 @@ fn mutation_forgetting_access_count_modifier_r6() { let engine = ForgettingEngine::new(config); let mut mem_accessed = Memory::episodic("Accessed memory".to_string(), vec![], None); mem_accessed.metadata.access_count = 5; - mem_accessed.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(3); - mem_accessed.metadata.last_accessed = chrono::Utc::now(); + mem_accessed.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(3); + mem_accessed.metadata.last_accessed = time::OffsetDateTime::now_utc(); let mut mems_a = vec![mem_accessed]; engine.apply_forgetting(&mut mems_a).unwrap(); let s_accessed = mems_a[0].metadata.strength; let mut mem_zero = Memory::episodic("Never accessed".to_string(), vec![], None); mem_zero.metadata.access_count = 0; - mem_zero.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(3); - mem_zero.metadata.last_accessed = chrono::Utc::now() - chrono::Duration::days(3); + mem_zero.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(3); + mem_zero.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(3); let mut mems_z = vec![mem_zero]; engine.apply_forgetting(&mut mems_z).unwrap(); let s_zero = mems_z[0].metadata.strength; @@ -9396,8 +9411,8 @@ fn mutation_forgetting_should_forget_threshold_r6() { // Memory very old (365 days) so decay drops strength below threshold let mut mem_below = Memory::episodic("Below threshold".to_string(), vec![], None); - mem_below.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(365); - mem_below.metadata.last_accessed = chrono::Utc::now() - chrono::Duration::days(365); + mem_below.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); + mem_below.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(365); mem_below.metadata.access_count = 0; mem_below.metadata.importance = 0.5; let mut mems_b = vec![mem_below]; @@ -9496,7 +9511,7 @@ fn mutation_compression_compress_text_formula_r6() { let compressed = engine.compress_memories(&mut vec![]).unwrap(); // just test the engine exists // Actually compress_text is private, test via compress_memories let mut mem = Memory::episodic(long_text.to_string(), vec![], None); - mem.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(60); + mem.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); mem.metadata.importance = 0.1; let original_len = mem.content.text.split_whitespace().count(); let mut mems = vec![mem]; @@ -9528,17 +9543,17 @@ fn mutation_compression_should_compress_checks_r6() { // Memory aged 31 days, low importance — should compress let long_text = "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15"; let mut mem_eligible = Memory::episodic(long_text.to_string(), vec![], None); - mem_eligible.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(31); + mem_eligible.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(31); mem_eligible.metadata.importance = 0.1; // Memory aged 29 days — should NOT compress (too young) let mut mem_young = Memory::episodic(long_text.to_string(), vec![], None); - mem_young.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(29); + mem_young.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(29); mem_young.metadata.importance = 0.1; // Memory with high importance — should NOT compress let mut mem_important = Memory::episodic(long_text.to_string(), vec![], None); - mem_important.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(60); + mem_important.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); mem_important.metadata.importance = 0.5; let mut mems = vec![mem_eligible, mem_young, mem_important]; @@ -9617,7 +9632,7 @@ fn mutation_compression_stats_ratio_r6() { }); let long_text = "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15"; let mut mem1 = Memory::episodic(long_text.to_string(), vec![], None); - mem1.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(60); + mem1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); mem1.metadata.importance = 0.1; let mut mem2 = Memory::episodic("Short text".to_string(), vec![], None); mem2.metadata.importance = 0.1; @@ -9696,9 +9711,9 @@ fn mutation_retrieval_temporal_score_in_window_r6() { follow_associations: false, max_results: 10, }); - let now = chrono::Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut mem = Memory::episodic("test memory".to_string(), vec![], None); - mem.metadata.created_at = now - chrono::Duration::hours(12); + mem.metadata.created_at = now - time::Duration::hours(12); let ctx = RetrievalContext { query: "test".to_string(), emotional_state: None, @@ -9706,7 +9721,7 @@ fn mutation_retrieval_temporal_score_in_window_r6() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - chrono::Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -9737,10 +9752,10 @@ fn mutation_retrieval_temporal_decay_formula_r6() { follow_associations: false, max_results: 10, }); - let now = chrono::Utc::now(); + let now = time::OffsetDateTime::now_utc(); // Memory 14 days outside window let mut mem = Memory::episodic("old memory".to_string(), vec![], None); - mem.metadata.created_at = now - chrono::Duration::days(21); + mem.metadata.created_at = now - time::Duration::days(21); let ctx = RetrievalContext { query: "old".to_string(), emotional_state: None, @@ -9748,7 +9763,7 @@ fn mutation_retrieval_temporal_decay_formula_r6() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - chrono::Duration::days(7), + start: now - time::Duration::days(7), end: now, }), limit: 10, @@ -9781,12 +9796,12 @@ fn mutation_retrieval_recency_score_formula_r6() { let engine = RetrievalEngine::new(RetrievalConfig::default()); // Recent memory (1 day old, accessed today) let mut mem_recent = Memory::episodic("recent".to_string(), vec![], None); - mem_recent.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(1); - mem_recent.metadata.last_accessed = chrono::Utc::now(); + mem_recent.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); + mem_recent.metadata.last_accessed = time::OffsetDateTime::now_utc(); // Old memory (90 days old, accessed 30 days ago) let mut mem_old = Memory::episodic("old".to_string(), vec![], None); - mem_old.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(90); - mem_old.metadata.last_accessed = chrono::Utc::now() - chrono::Duration::days(30); + mem_old.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(90); + mem_old.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(30); let memories = vec![mem_recent, mem_old]; let ctx = RetrievalContext { @@ -10623,8 +10638,8 @@ fn test_compression_compress_memories_long_text_s69() { "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15 word16 word17 word18 word19 word20 word21 word22 word23 word24 word25 word26 word27 word28 word29 word30".to_string(), vec![], None, ); - m.metadata.created_at = Utc::now() - Duration::days(60); - m.metadata.last_accessed = Utc::now() - Duration::days(60); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(60); m.metadata.importance = 0.1; // Below default threshold 0.3 m.metadata.tags.clear(); // Remove any default tags @@ -10656,8 +10671,8 @@ fn test_compression_compress_text_formula_s69() { let text = words.join(" "); let mut m = Memory::episodic(text.clone(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(60); - m.metadata.last_accessed = Utc::now() - Duration::days(60); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(60); m.metadata.importance = 0.1; m.metadata.tags.clear(); @@ -10690,8 +10705,8 @@ fn test_compression_compress_text_boundary_last_part_s69() { let text = words.join(" "); let mut m = Memory::episodic(text.clone(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(60); - m.metadata.last_accessed = Utc::now() - Duration::days(60); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(60); m.metadata.importance = 0.1; m.metadata.tags.clear(); @@ -10722,8 +10737,8 @@ fn test_forgetting_strength_exact_episodic_s70() { // spaced_rep_modifier = 1.0 (access_count <= 1) // new_strength = 1.0 * 0.7071 * 1.1 * 1.0 * 1.0 = 0.7778 let mut m = Memory::episodic("test_decay".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(7); - m.metadata.last_accessed = Utc::now() - Duration::days(7); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(7); m.metadata.importance = 0.7; m.metadata.access_count = 0; m.metadata.strength = 1.0; @@ -10754,8 +10769,8 @@ fn test_forgetting_strength_with_access_s70() { // spaced_rep_modifier = 1.0 + 0.10986 = 1.10986 // new_strength = 1.0 * 0.7071 * 1.0 * 1.1286 * 1.10986 = 0.8858 let mut m = Memory::episodic("access_test".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(7); - m.metadata.last_accessed = Utc::now() - Duration::days(1); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(7); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(1); m.metadata.importance = 0.5; m.metadata.access_count = 3; m.metadata.strength = 1.0; @@ -10798,8 +10813,8 @@ fn test_forgetting_access_count_zero_boundary_s70() { // < 0: false → modifier = 1.0 (DIFFERENT!) // >= 0: true → same as > (same result) let mut m = Memory::episodic("access_one".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(14); - m.metadata.last_accessed = Utc::now() - Duration::days(1); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(14); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(1); m.metadata.importance = 0.5; m.metadata.access_count = 1; m.metadata.strength = 1.0; @@ -10838,8 +10853,8 @@ fn test_forgetting_spaced_rep_boundary_access_two_s70() { // For L258 in calculate_adaptive_half_life: access_count > 1 → >= // Same equivalence issue. Test with access_count=2 to verify non-boundary. let mut m = Memory::episodic("spaced_rep".to_string(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(14); - m.metadata.last_accessed = Utc::now() - Duration::days(1); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(14); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(1); m.metadata.importance = 0.5; m.metadata.access_count = 2; m.metadata.strength = 1.0; @@ -10885,8 +10900,8 @@ fn test_forgetting_should_forget_strength_at_threshold_s70() { // Very old episodic (365 days), low importance: let mut old = Memory::episodic("very_old".to_string(), vec![], None); - old.metadata.created_at = Utc::now() - Duration::days(365); - old.metadata.last_accessed = Utc::now() - Duration::days(365); + old.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(365); + old.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(365); old.metadata.importance = 0.3; // Low old.metadata.access_count = 0; old.metadata.strength = 1.0; @@ -11034,9 +11049,9 @@ fn test_retrieval_temporal_in_window_s71() { ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::episodic("temporal test".to_string(), vec![], None); - m.metadata.created_at = now - Duration::hours(12); // 12 hours ago + m.metadata.created_at = now - time::Duration::hours(12); // 12 hours ago let context = RetrievalContext { query: "temporal test".to_string(), @@ -11045,7 +11060,7 @@ fn test_retrieval_temporal_in_window_s71() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -11071,8 +11086,8 @@ fn test_retrieval_temporal_at_window_start_s71() { ..Default::default() }); - let now = Utc::now(); - let window_start = now - Duration::days(2); + let now = time::OffsetDateTime::now_utc(); + let window_start = now - time::Duration::days(2); let mut m = Memory::episodic("at boundary".to_string(), vec![], None); m.metadata.created_at = window_start; // Exactly at start @@ -11115,9 +11130,9 @@ fn test_retrieval_temporal_decay_outside_window_s71() { ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::episodic("old memory decay".to_string(), vec![], None); - m.metadata.created_at = now - Duration::days(14); // 14 days ago + m.metadata.created_at = now - time::Duration::days(14); // 14 days ago let context = RetrievalContext { query: "old memory decay".to_string(), @@ -11126,7 +11141,7 @@ fn test_retrieval_temporal_decay_outside_window_s71() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(7), + start: now - time::Duration::days(7), end: now, }), limit: 10, @@ -11171,10 +11186,10 @@ fn test_retrieval_recency_score_exact_s71() { ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::episodic("recency check".to_string(), vec![], None); - m.metadata.created_at = now - Duration::days(30); - m.metadata.last_accessed = now - Duration::days(7); + m.metadata.created_at = now - time::Duration::days(30); + m.metadata.last_accessed = now - time::Duration::days(7); m.metadata.importance = 0.5; let context = RetrievalContext { @@ -11399,8 +11414,8 @@ fn test_consolidation_spatial_same_location_exact_s72() { Some("central_park".to_string()), ); // Set creation times far apart to prevent temporal association - m1.metadata.created_at = Utc::now() - Duration::days(60); - m2.metadata.created_at = Utc::now() - Duration::days(1); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); let mut memories = vec![m1, m2]; let result = engine.consolidate(&mut memories).unwrap(); @@ -11428,8 +11443,8 @@ fn test_consolidation_conceptual_similarity_exact_s72() { // Total: 0.3 + 0.375 = 0.675 → above 0.5 threshold let mut m1 = Memory::episodic("alpha beta gamma".to_string(), vec![], None); let mut m2 = Memory::episodic("alpha beta gamma delta".to_string(), vec![], None); - m1.metadata.created_at = Utc::now() - Duration::days(100); - m2.metadata.created_at = Utc::now() - Duration::days(1); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); let mut memories = vec![m1, m2]; let result = engine.consolidate(&mut memories).unwrap(); @@ -11454,10 +11469,10 @@ fn test_consolidation_strength_boost_addition_s72() { let engine = ConsolidationEngine::new(ConsolidationConfig::default()); // Create two memories close in time for temporal association (triggers consolidation) - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m1 = Memory::episodic("temporal event one".to_string(), vec![], None); let mut m2 = Memory::episodic("temporal event two".to_string(), vec![], None); - m1.metadata.created_at = now - Duration::hours(1); + m1.metadata.created_at = now - time::Duration::hours(1); m2.metadata.created_at = now; m1.metadata.strength = 0.7; @@ -11507,8 +11522,8 @@ fn test_compress_text_exact_output_r8() { let text = words.join(" "); let mut m = Memory::episodic(text.clone(), vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(60); - m.metadata.last_accessed = Utc::now() - Duration::days(60); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(60); m.metadata.importance = 0.1; m.metadata.tags.clear(); @@ -11555,8 +11570,8 @@ fn test_compress_text_20_words_exact_r8() { let text = words.join(" "); let mut m = Memory::episodic(text, vec![], None); - m.metadata.created_at = Utc::now() - Duration::days(60); - m.metadata.last_accessed = Utc::now() - Duration::days(60); + m.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(60); + m.metadata.last_accessed = time::OffsetDateTime::now_utc() - time::Duration::days(60); m.metadata.importance = 0.1; m.metadata.tags.clear(); @@ -12038,7 +12053,7 @@ fn test_retrieval_temporal_exactly_at_window_end_r8() { ..Default::default() }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let window_end = now; let mut m = Memory::episodic("end boundary test".to_string(), vec![], None); m.metadata.created_at = window_end; // Exactly at end @@ -12050,7 +12065,7 @@ fn test_retrieval_temporal_exactly_at_window_end_r8() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: window_end, }), limit: 10, @@ -12083,9 +12098,9 @@ fn test_retrieval_relevance_total_includes_temporal_r8() { max_results: 10, }); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = Memory::episodic("temporal test r8".to_string(), vec![], None); - m.metadata.created_at = now - Duration::hours(6); // Inside any reasonable window + m.metadata.created_at = now - time::Duration::hours(6); // Inside any reasonable window m.metadata.importance = 0.0; // Zero importance to isolate temporal let context = RetrievalContext { @@ -12095,7 +12110,7 @@ fn test_retrieval_relevance_total_includes_temporal_r8() { recent_memory_ids: vec![], preferred_types: vec![], time_window: Some(TimeWindow { - start: now - Duration::days(1), + start: now - time::Duration::days(1), end: now, }), limit: 10, @@ -12276,8 +12291,8 @@ fn test_consolidation_spatial_location_equality_r8() { }); let mut m1 = Memory::episodic("event one".to_string(), vec![], Some("castle".to_string())); let mut m2 = Memory::episodic("event two".to_string(), vec![], Some("castle".to_string())); - m1.metadata.created_at = Utc::now() - Duration::days(100); - m2.metadata.created_at = Utc::now() - Duration::days(1); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); let mut memories = vec![m1, m2]; let result = engine.consolidate(&mut memories).unwrap(); @@ -12300,8 +12315,8 @@ fn test_consolidation_spatial_different_location_r8() { }); let mut m1 = Memory::episodic("event A".to_string(), vec![], Some("castle".to_string())); let mut m2 = Memory::episodic("event B".to_string(), vec![], Some("forest".to_string())); - m1.metadata.created_at = Utc::now() - Duration::days(100); - m2.metadata.created_at = Utc::now() - Duration::days(1); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); let mut memories = vec![m1, m2]; let result = engine.consolidate(&mut memories).unwrap(); @@ -12334,8 +12349,8 @@ fn test_consolidation_conceptual_text_overlap_exact_r8() { // If L201 +=→-=: subtract instead → 0.3 - 0.25 = 0.05 → below threshold let mut m1 = Memory::episodic("aaa bbb ccc ddd".to_string(), vec![], None); let mut m2 = Memory::episodic("aaa bbb eee fff".to_string(), vec![], None); - m1.metadata.created_at = Utc::now() - Duration::days(100); - m2.metadata.created_at = Utc::now() - Duration::days(1); + m1.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(100); + m2.metadata.created_at = time::OffsetDateTime::now_utc() - time::Duration::days(1); let mut memories = vec![m1, m2]; let result = engine.consolidate(&mut memories).unwrap(); @@ -12357,10 +12372,10 @@ fn test_consolidation_strength_boost_exact_r8() { // Mutated: 0.5 * 0.2 = 0.1 let engine = ConsolidationEngine::new(ConsolidationConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m1 = Memory::episodic("boost test one".to_string(), vec![], None); let mut m2 = Memory::episodic("boost test two".to_string(), vec![], None); - m1.metadata.created_at = now - Duration::hours(1); + m1.metadata.created_at = now - time::Duration::hours(1); m2.metadata.created_at = now; m1.metadata.strength = 0.5; m2.metadata.strength = 0.5; @@ -12425,8 +12440,8 @@ fn test_retrieval_associated_mem_outside_window_r9() { // mem1: inside time window, matches query directly // mem2: 7 days before window start, connected via association // mem2 can ONLY appear through association chain (matches_context rejects it) - let now = Utc::now(); - let seven_days_ago = now - Duration::days(7); + let now = time::OffsetDateTime::now_utc(); + let seven_days_ago = now - time::Duration::days(7); // mem2 = old memory outside the time window let mut mem2 = Memory::sensory("battle plans strategy".to_string(), None); @@ -12441,8 +12456,8 @@ fn test_retrieval_associated_mem_outside_window_r9() { mem1.add_association(mem2_id.clone(), AssociationType::Temporal, 0.5); let window = TimeWindow { - start: now - Duration::days(1), - end: now + Duration::days(1), + start: now - time::Duration::days(1), + end: now + time::Duration::days(1), }; let config = RetrievalConfig { @@ -12523,15 +12538,15 @@ fn test_retrieval_associated_mem_outside_window_r9() { fn test_retrieval_direct_mid_window_temporal_one_r9() { // Memory in the MIDDLE of a 14-day window should get temporal_score = 1.0 // With L203 (<=→>): created_at > end is false → falls to decay → score < 1.0 - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut mem = Memory::sensory("target word".to_string(), None); mem.metadata.created_at = now; // exactly at midpoint of ±7 day window mem.metadata.last_accessed = now; let window = TimeWindow { - start: now - Duration::days(7), - end: now + Duration::days(7), + start: now - time::Duration::days(7), + end: now + time::Duration::days(7), }; let config = RetrievalConfig { @@ -12579,7 +12594,7 @@ fn test_retrieval_importance_increases_score_r9() { // Two memories with identical text match but different importance. // Higher importance should give higher relevance_score. // With L147 (+=→-=): importance contribution is SUBTRACTED, inverting the order. - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut mem_low = Memory::sensory("exact match words".to_string(), None); mem_low.metadata.importance = 0.1; @@ -12755,16 +12770,16 @@ fn mutation_spatial_same_location_must_match_r10() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut mem_a = make_timed_memory( "event alpha", - now - Duration::hours(100), + now - time::Duration::hours(100), Some("castle_gate"), vec![], ); let mem_b = make_timed_memory( "event beta", - now - Duration::hours(200), + now - time::Duration::hours(200), Some("castle_gate"), vec![], ); @@ -12797,17 +12812,17 @@ fn mutation_spatial_different_location_no_association_r10() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut memories = vec![ make_timed_memory( "event at castle", - now - Duration::hours(100), + now - time::Duration::hours(100), Some("castle"), vec![], ), make_timed_memory( "event at forest", - now - Duration::hours(200), + now - time::Duration::hours(200), Some("forest"), vec![], ), @@ -12831,11 +12846,21 @@ fn mutation_consolidation_max_associations_boundary_r10() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); - let mut mem_a = make_timed_memory("topic alpha", now - Duration::hours(100), None, vec![]); + let now = time::OffsetDateTime::now_utc(); + let mut mem_a = make_timed_memory( + "topic alpha", + now - time::Duration::hours(100), + None, + vec![], + ); // Pre-fill with exactly 1 association (at the max) mem_a.add_association("preexisting_id".to_string(), AssociationType::Temporal, 0.7); - let mem_b = make_timed_memory("topic alpha", now - Duration::hours(200), None, vec![]); + let mem_b = make_timed_memory( + "topic alpha", + now - time::Duration::hours(200), + None, + vec![], + ); let mut memories = vec![mem_a, mem_b]; let _result = engine.consolidate(&mut memories).unwrap(); // Memory A (index 0) should still have exactly 1 association — the pre-existing one @@ -12859,12 +12884,12 @@ fn mutation_consolidation_empty_text_no_nan_v10() { ..ConsolidationConfig::default() }; let engine = ConsolidationEngine::new(config); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // Memory A: empty text, Memory B: non-empty. Same type (Episodic from make_timed_memory). - let mem_a = make_timed_memory("", now - Duration::hours(100), None, vec![]); + let mem_a = make_timed_memory("", now - time::Duration::hours(100), None, vec![]); let mem_b = make_timed_memory( "hello world combat battle", - now - Duration::hours(200), + now - time::Duration::hours(200), None, vec![], ); @@ -12908,16 +12933,16 @@ fn mutation_consolidation_participant_similarity_arithmetic_r10() { ..ConsolidationConfig::default() }; let engine_a = ConsolidationEngine::new(config_a); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mem1 = make_timed_memory( "xyzzy details", - now - Duration::hours(100), + now - time::Duration::hours(100), None, vec!["alice", "bob"], ); let mem2 = make_timed_memory( "plugh info", - now - Duration::hours(200), + now - time::Duration::hours(200), None, vec!["alice", "carol"], ); @@ -12940,16 +12965,16 @@ fn mutation_consolidation_participant_division_not_mult_r10() { ..ConsolidationConfig::default() }; let engine_b = ConsolidationEngine::new(config_b); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mem1 = make_timed_memory( "xyzzy details", - now - Duration::hours(100), + now - time::Duration::hours(100), None, vec!["alice", "bob"], ); let mem2 = make_timed_memory( "plugh info", - now - Duration::hours(200), + now - time::Duration::hours(200), None, vec!["alice", "carol"], ); diff --git a/astraweave-memory/tests/storage_tests.rs b/astraweave-memory/tests/storage_tests.rs index a5d9d510c8..176e7696af 100644 --- a/astraweave-memory/tests/storage_tests.rs +++ b/astraweave-memory/tests/storage_tests.rs @@ -8,7 +8,6 @@ use astraweave_memory::{ Memory, MemoryContent, MemoryMetadata, MemorySource, MemoryStorage, MemoryType, SpatialTemporalContext, }; -use chrono::Utc; use std::time::SystemTime; fn create_test_memory( @@ -37,8 +36,8 @@ fn create_test_memory( }, }, metadata: MemoryMetadata { - created_at: Utc::now(), - last_accessed: Utc::now(), + created_at: time::OffsetDateTime::now_utc(), + last_accessed: time::OffsetDateTime::now_utc(), access_count: 0, importance, confidence: 1.0, diff --git a/astraweave-observability/Cargo.toml b/astraweave-observability/Cargo.toml index 377d2b3b84..6d64299523 100644 --- a/astraweave-observability/Cargo.toml +++ b/astraweave-observability/Cargo.toml @@ -20,7 +20,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } tokio.workspace = true astraweave-ecs.workspace = true uuid = { version = "1.0", features = ["v4"] } -chrono = { version = "0.4", features = ["serde"] } +time = { version = "0.3", features = ["parsing"] } dashmap = "6.1" async-trait = "0.1" prometheus = { version = "0.14", optional = true } diff --git a/astraweave-observability/src/lib.rs b/astraweave-observability/src/lib.rs index 4eeed7038a..b3d080d290 100644 --- a/astraweave-observability/src/lib.rs +++ b/astraweave-observability/src/lib.rs @@ -6,6 +6,8 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use astraweave_ecs::{App, Plugin}; +mod utc_stamp; + pub mod llm_telemetry; pub use llm_telemetry::*; diff --git a/astraweave-observability/src/llm_telemetry.rs b/astraweave-observability/src/llm_telemetry.rs index 275f31764d..391abaa8e7 100644 --- a/astraweave-observability/src/llm_telemetry.rs +++ b/astraweave-observability/src/llm_telemetry.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use chrono::{DateTime, Datelike, Timelike, Utc}; use dashmap::DashMap; use hdrhistogram::Histogram; use serde::{Deserialize, Serialize}; @@ -100,8 +99,10 @@ pub struct LlmTrace { pub response: Option, // Optional for privacy pub prompt_hash: Option, // Hash for deduplication pub model: String, - pub start_time: DateTime, - pub end_time: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub start_time: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub end_time: time::OffsetDateTime, pub latency_ms: u64, pub tokens_prompt: usize, pub tokens_response: usize, @@ -115,7 +116,7 @@ pub struct LlmTrace { } /// Real-time LLM metrics -#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct LlmMetrics { pub total_requests: u64, pub successful_requests: u64, @@ -133,11 +134,38 @@ pub struct LlmMetrics { pub active_requests: usize, pub queue_depth: usize, pub cache_hit_rate: f32, - pub last_updated: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_updated: time::OffsetDateTime, pub model_usage: HashMap, pub source_metrics: HashMap, } +impl Default for LlmMetrics { + fn default() -> Self { + Self { + total_requests: 0, + successful_requests: 0, + failed_requests: 0, + total_tokens: 0, + total_cost_usd: 0.0, + average_latency_ms: 0.0, + p50_latency_ms: 0, + p95_latency_ms: 0, + p99_latency_ms: 0, + error_rate: 0.0, + requests_per_second: 0.0, + tokens_per_second: 0.0, + cost_per_hour_usd: 0.0, + active_requests: 0, + queue_depth: 0, + cache_hit_rate: 0.0, + last_updated: time::OffsetDateTime::UNIX_EPOCH, + model_usage: HashMap::new(), + source_metrics: HashMap::new(), + } + } +} + /// Metrics per model #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct ModelMetrics { @@ -192,7 +220,8 @@ pub struct CostTracker { /// Hourly cost tracking #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HourlyCost { - pub hour: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub hour: time::OffsetDateTime, pub cost_usd: f32, pub requests: u64, pub tokens: u64, @@ -204,7 +233,8 @@ pub struct BudgetAlert { pub alert_type: BudgetAlertType, pub threshold: f32, pub actual: f32, - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -232,8 +262,10 @@ pub struct Alert { pub message: String, pub value: f32, pub threshold: f32, - pub first_triggered: DateTime, - pub last_triggered: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub first_triggered: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_triggered: time::OffsetDateTime, pub acknowledged: bool, pub resolved: bool, } @@ -287,14 +319,17 @@ pub struct ErrorTracker { pub struct ErrorPattern { pub error_type: String, pub frequency: u64, - pub first_seen: DateTime, - pub last_seen: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub first_seen: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_seen: time::OffsetDateTime, pub sample_messages: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ErrorEvent { - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, pub error_type: String, pub error_message: String, pub request_id: String, @@ -334,7 +369,8 @@ pub struct ModelBreakdown { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HourlyStats { - pub hour: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub hour: time::OffsetDateTime, pub requests: u64, pub cost: f32, pub avg_latency: f32, @@ -655,7 +691,7 @@ impl LlmTelemetry { } metrics.active_requests = self.active_requests.len(); - metrics.last_updated = Utc::now(); + metrics.last_updated = time::OffsetDateTime::now_utc(); Ok(()) } @@ -684,11 +720,11 @@ impl LlmTelemetry { // with_minute(0)/with_second(0)/with_nanosecond(0) are infallible let current_hour = trace .start_time - .with_minute(0) + .replace_minute(0) .expect("valid time truncation") - .with_second(0) + .replace_second(0) .expect("valid time truncation") - .with_nanosecond(0) + .replace_nanosecond(0) .expect("valid time truncation"); if let Some(hourly) = cost_tracker.hourly_costs.back_mut() { @@ -713,9 +749,8 @@ impl LlmTelemetry { }); } - // Keep only recent hourly data - while cost_tracker.hourly_costs.len() > 168 { - // Keep 1 week + // One call adds at most one hour, so one pop restores the week cap. + if cost_tracker.hourly_costs.len() > 168 { cost_tracker.hourly_costs.pop_front(); } @@ -821,7 +856,7 @@ impl LlmTelemetry { threshold: f32, ) { let alert_key = format!("{:?}", alert_type); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); if let Some(existing_alert) = alert_manager.active_alerts.get_mut(&alert_key) { existing_alert.last_triggered = now; @@ -906,13 +941,9 @@ impl LlmTelemetry { /// Calculate projected monthly cost fn calculate_projected_monthly_cost(&self, cost_tracker: &CostTracker) -> f32 { let days_in_month = 30.0; - let current_day = Utc::now().day() as f32; - - if current_day > 0.0 { - (cost_tracker.current_month_spend / current_day) * days_in_month - } else { - 0.0 - } + // `OffsetDateTime::day` is the day of the month, 1..=31. + let current_day = f32::from(time::OffsetDateTime::now_utc().day()); + (cost_tracker.current_month_spend / current_day) * days_in_month } /// Export traces to CSV format @@ -925,7 +956,7 @@ impl LlmTelemetry { "{},{},{},{},{},{},{},{},{},{}\n", trace.request_id, trace.model, - trace.start_time.format("%Y-%m-%d %H:%M:%S UTC"), + crate::utc_stamp::format_utc_clock(trace.start_time), trace.latency_ms, trace.tokens_prompt, trace.tokens_response, @@ -1014,7 +1045,7 @@ impl RequestTracker { response: Option, tags: HashMap, ) -> Result<()> { - let end_time = Utc::now(); + let end_time = time::OffsetDateTime::now_utc(); let latency = self.start_time.elapsed(); // Extract prompt_tokens and drop the DashMap guard BEFORE any .await @@ -1036,7 +1067,7 @@ impl RequestTracker { response, prompt_hash: None, model, - start_time: end_time - chrono::Duration::from_std(latency).unwrap_or_default(), + start_time: end_time - time::Duration::try_from(latency).unwrap_or_default(), end_time, latency_ms: latency.as_millis() as u64, tokens_prompt: prompt_tokens, @@ -1068,8 +1099,8 @@ pub enum ExportFormat { pub struct TraceFilter { pub model: Option, pub success: Option, - pub start_time: Option>, - pub end_time: Option>, + pub start_time: Option, + pub end_time: Option, pub min_latency_ms: Option, pub max_latency_ms: Option, } @@ -1123,6 +1154,263 @@ mod tests { assert_eq!(metrics.successful_requests, 1); } + #[tokio::test] + async fn completed_trace_starts_before_it_ends_and_adds_cost() { + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + let tracker = + telemetry.start_request("cost-request".into(), "model".into(), "src".into(), 10); + std::thread::sleep(std::time::Duration::from_millis(20)); + tracker + .complete( + "model".into(), + true, + 5, + 2.5, + None, + None, + "src".into(), + None, + None, + HashMap::new(), + ) + .await + .unwrap(); + let traces = telemetry.traces.read().await; + let trace = traces.back().unwrap(); + assert!(trace.start_time < trace.end_time); + drop(traces); + let costs = telemetry.cost_tracker.read().await; + assert!((costs.current_day_spend - 2.5).abs() < 0.01); + assert!((costs.current_month_spend - 2.5).abs() < 0.01); + assert!((costs.cost_by_model.get("model").copied().unwrap_or(0.0) - 2.5).abs() < 0.01); + assert!((costs.cost_by_source.get("src").copied().unwrap_or(0.0) - 2.5).abs() < 0.01); + assert_eq!(costs.hourly_costs.len(), 1); + let hour = costs.hourly_costs.back().unwrap(); + assert!((hour.cost_usd - 2.5).abs() < 0.01); + assert_eq!(hour.requests, 1); + assert_eq!(hour.tokens, 15); + } + + #[tokio::test] + async fn track_cost_matches_the_hour_and_keeps_a_week() { + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + let epoch = time::OffsetDateTime::UNIX_EPOCH; + { + let mut costs = telemetry.cost_tracker.write().await; + costs.hourly_costs.push_back(HourlyCost { + hour: epoch, + cost_usd: 9.0, + requests: 9, + tokens: 9, + }); + } + let tracker = + telemetry.start_request("other-hour".into(), "model".into(), "src".into(), 10); + tracker + .complete( + "model".into(), + true, + 5, + 2.5, + None, + None, + "src".into(), + None, + None, + HashMap::new(), + ) + .await + .unwrap(); + { + let costs = telemetry.cost_tracker.read().await; + assert_eq!(costs.hourly_costs.len(), 2); + assert!((costs.hourly_costs.front().unwrap().cost_usd - 9.0).abs() < 0.01); + assert!((costs.hourly_costs.back().unwrap().cost_usd - 2.5).abs() < 0.01); + } + + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + for _ in 0..2 { + let tracker = + telemetry.start_request("same-hour".into(), "model".into(), "src".into(), 10); + tracker + .complete( + "model".into(), + true, + 5, + 1.5, + None, + None, + "src".into(), + None, + None, + HashMap::new(), + ) + .await + .unwrap(); + } + { + let costs = telemetry.cost_tracker.read().await; + assert_eq!(costs.hourly_costs.len(), 1); + let hour = costs.hourly_costs.back().unwrap(); + assert!((hour.cost_usd - 3.0).abs() < 0.01); + assert_eq!(hour.requests, 2); + assert_eq!(hour.tokens, 30); + } + + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + { + let mut costs = telemetry.cost_tracker.write().await; + for i in 0..167 { + costs.hourly_costs.push_back(HourlyCost { + hour: epoch + time::Duration::hours(i), + cost_usd: 1.0, + requests: 1, + tokens: 1, + }); + } + } + let tracker = telemetry.start_request("week".into(), "model".into(), "src".into(), 1); + tracker + .complete( + "model".into(), + true, + 1, + 1.0, + None, + None, + "src".into(), + None, + None, + HashMap::new(), + ) + .await + .unwrap(); + { + let costs = telemetry.cost_tracker.read().await; + assert_eq!(costs.hourly_costs.len(), 168); + assert_eq!(costs.hourly_costs.front().unwrap().hour, epoch); + } + + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + { + let mut costs = telemetry.cost_tracker.write().await; + for i in 0..168 { + costs.hourly_costs.push_back(HourlyCost { + hour: epoch + time::Duration::hours(i), + cost_usd: 1.0, + requests: 1, + tokens: 1, + }); + } + } + let tracker = telemetry.start_request("drop".into(), "model".into(), "src".into(), 1); + tracker + .complete( + "model".into(), + true, + 1, + 1.0, + None, + None, + "src".into(), + None, + None, + HashMap::new(), + ) + .await + .unwrap(); + let costs = telemetry.cost_tracker.read().await; + assert_eq!(costs.hourly_costs.len(), 168); + assert_eq!( + costs.hourly_costs.front().unwrap().hour, + epoch + time::Duration::hours(1) + ); + } + + #[test] + fn projected_monthly_cost_scales_spend_by_the_day() { + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + let costs = CostTracker { + current_month_spend: 310.0, + ..CostTracker::default() + }; + let day = time::OffsetDateTime::now_utc().day() as f32; + let projected = telemetry.calculate_projected_monthly_cost(&costs); + let expected = (310.0 / day) * 30.0; + assert!((projected - expected).abs() < 0.01); + assert!(projected > 1.0); + } + + #[test] + fn trigger_alert_records_a_new_alert_and_updates_it() { + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + let mut manager = AlertManager::default(); + telemetry.trigger_alert( + &mut manager, + AlertType::HighLatency, + AlertSeverity::Warning, + "slow".into(), + 40.0, + 20.0, + ); + assert_eq!(manager.active_alerts.len(), 1); + assert_eq!(manager.alert_history.len(), 1); + let key = format!("{:?}", AlertType::HighLatency); + assert!((manager.active_alerts.get(&key).unwrap().value - 40.0).abs() < 0.01); + telemetry.trigger_alert( + &mut manager, + AlertType::HighLatency, + AlertSeverity::Warning, + "slower".into(), + 55.0, + 20.0, + ); + assert_eq!(manager.active_alerts.len(), 1); + assert_eq!(manager.alert_history.len(), 1); + assert!((manager.active_alerts.get(&key).unwrap().value - 55.0).abs() < 0.01); + } + + #[test] + fn trigger_alert_keeps_a_thousand_history_entries() { + let telemetry = LlmTelemetry::new(TelemetryConfig::default()); + let mut manager = AlertManager::default(); + let epoch = time::OffsetDateTime::UNIX_EPOCH; + for i in 0..999i64 { + manager.alert_history.push_back(Alert { + id: format!("old-{i}"), + alert_type: AlertType::HighCost, + severity: AlertSeverity::Warning, + message: "old".into(), + value: 1.0, + threshold: 1.0, + first_triggered: epoch + time::Duration::seconds(i), + last_triggered: epoch, + acknowledged: false, + resolved: false, + }); + } + telemetry.trigger_alert( + &mut manager, + AlertType::HighLatency, + AlertSeverity::Warning, + "new".into(), + 40.0, + 20.0, + ); + assert_eq!(manager.alert_history.len(), 1000); + assert_eq!(manager.alert_history.front().unwrap().id, "old-0"); + telemetry.trigger_alert( + &mut manager, + AlertType::HighErrorRate, + AlertSeverity::Critical, + "newer".into(), + 80.0, + 20.0, + ); + assert_eq!(manager.alert_history.len(), 1000); + assert_eq!(manager.alert_history.front().unwrap().id, "old-1"); + } + #[tokio::test] async fn test_dashboard_data() { let telemetry = LlmTelemetry::new(TelemetryConfig::default()); @@ -1163,8 +1451,8 @@ mod tests { response: Some("Hi there!".to_string()), prompt_hash: Some(12345), model: "gpt-4".to_string(), - start_time: Utc::now(), - end_time: Utc::now(), + start_time: time::OffsetDateTime::now_utc(), + end_time: time::OffsetDateTime::now_utc(), latency_ms: 500, tokens_prompt: 10, tokens_response: 20, @@ -1215,7 +1503,7 @@ mod tests { #[test] fn test_hourly_cost_creation() { let cost = HourlyCost { - hour: Utc::now(), + hour: time::OffsetDateTime::now_utc(), cost_usd: 1.50, requests: 100, tokens: 5000, @@ -1276,8 +1564,8 @@ mod tests { message: "High latency detected".to_string(), value: 6000.0, threshold: 5000.0, - first_triggered: Utc::now(), - last_triggered: Utc::now(), + first_triggered: time::OffsetDateTime::now_utc(), + last_triggered: time::OffsetDateTime::now_utc(), acknowledged: false, resolved: false, }; @@ -1291,8 +1579,8 @@ mod tests { let pattern = ErrorPattern { error_type: "RateLimitExceeded".to_string(), frequency: 5, - first_seen: Utc::now(), - last_seen: Utc::now(), + first_seen: time::OffsetDateTime::now_utc(), + last_seen: time::OffsetDateTime::now_utc(), sample_messages: vec!["Rate limit exceeded".to_string()], }; assert_eq!(pattern.frequency, 5); @@ -1302,7 +1590,7 @@ mod tests { #[test] fn test_error_event_creation() { let event = ErrorEvent { - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), error_type: "ConnectionTimeout".to_string(), error_message: "Connection timed out".to_string(), request_id: "req-456".to_string(), @@ -1362,7 +1650,7 @@ mod tests { let filter = TraceFilter { model: Some("gpt-4".to_string()), success: Some(true), - start_time: Some(Utc::now()), + start_time: Some(time::OffsetDateTime::now_utc()), end_time: None, min_latency_ms: Some(100), max_latency_ms: Some(5000), @@ -1624,7 +1912,7 @@ mod tests { alert_type: BudgetAlertType::DailyBudget, threshold: 100.0, actual: 120.0, - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), }; assert!((alert.threshold - 100.0).abs() < 0.01); assert!((alert.actual - 120.0).abs() < 0.01); @@ -1640,8 +1928,8 @@ mod tests { response: None, prompt_hash: None, model: "test-model".to_string(), - start_time: Utc::now(), - end_time: Utc::now(), + start_time: time::OffsetDateTime::now_utc(), + end_time: time::OffsetDateTime::now_utc(), latency_ms: 100, tokens_prompt: 10, tokens_response: 20, @@ -1866,7 +2154,7 @@ mod tests { #[test] fn test_hourly_stats_creation() { let stats = HourlyStats { - hour: Utc::now(), + hour: time::OffsetDateTime::now_utc(), requests: 500, cost: 2.5, avg_latency: 150.0, diff --git a/astraweave-observability/src/utc_stamp.rs b/astraweave-observability/src/utc_stamp.rs new file mode 100644 index 0000000000..e905ffce05 --- /dev/null +++ b/astraweave-observability/src/utc_stamp.rs @@ -0,0 +1,396 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Negative years through `-9999` keep a +//! sign and four digits. A year outside `-9999..=9999` is rejected; `large-dates` +//! is not enabled. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. A negative year keeps a sign and four +/// digits. Values outside `-9999..=9999` are not stored. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub(crate) fn format_utc_seconds(dt: OffsetDateTime) -> String { + let utc = dt.to_offset(UtcOffset::UTC); + format!( + "{}-{:02}-{:02} {:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ) +} + +pub(crate) fn format_utc_clock(dt: OffsetDateTime) -> String { + format!("{} UTC", format_utc_seconds(dt)) +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> Result { + let utc = dt + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year)?; + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + Ok(out) +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +fn invalid_year() -> time::error::Parse { + time::error::Parse::ParseFromDescription(time::error::ParseFromDescription::InvalidComponent( + "year", + )) +} + +pub(crate) fn parse_utc_rfc3339(text: &str) -> Result { + let rfc3339 = &time::format_description::well_known::Rfc3339; + if text.starts_with('+') || text.starts_with('-') { + parse_signed_year(text, rfc3339) + } else { + OffsetDateTime::parse(text, rfc3339).and_then(|dt| { + dt.checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) + }) + } +} + +/// A leading sign is outside `time`'s RFC 3339 year. The magnitude is at least +/// four digits. The remainder is parsed as year 2000 so a leap day survives, +/// then the result is stored as UTC. +fn parse_signed_year( + text: &str, + rfc3339: &time::format_description::well_known::Rfc3339, +) -> Result { + let negative = text.starts_with('-'); + let rest = &text[1..]; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + if digits < 4 { + return Err(invalid_year()); + } + let magnitude: i32 = rest[..digits].parse().map_err(|_| invalid_year())?; + let year = if negative { + magnitude.checked_neg().ok_or_else(invalid_year)? + } else { + magnitude + }; + let parsed = OffsetDateTime::parse(&format!("2000{}", &rest[digits..]), rfc3339)?; + let date = time::Date::from_calendar_date(year, parsed.month(), parsed.day()) + .map_err(|_| invalid_year())?; + OffsetDateTime::new_in_offset(date, parsed.time(), parsed.offset()) + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) +} + +pub(crate) mod serde_rfc3339 { + use super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize(dt: &OffsetDateTime, serializer: S) -> Result { + let text = format_utc(*dt, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_str(&text) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result { + let text = String::deserialize(deserializer)?; + parse_utc_rfc3339(&text).map_err(serde::de::Error::custom) + } + + #[allow(dead_code)] + pub mod option { + use super::super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize( + dt: &Option, + serializer: S, + ) -> Result { + match dt { + Some(value) => { + let text = format_utc(*value, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_some(&text) + } + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let text = Option::::deserialize(deserializer)?; + text.map(|value| parse_utc_rfc3339(&value).map_err(serde::de::Error::custom)) + .transpose() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn fmt_utc(dt: OffsetDateTime, zulu: bool) -> String { + format_utc(dt, zulu).unwrap() + } + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(fmt_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + fmt_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!(fmt_utc(at(100_000_000), true), "2020-01-02T03:04:05.100Z"); + assert_eq!( + fmt_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(fmt_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + fmt_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(fmt_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!(fmt_utc(at(1), false), "2020-01-02T03:04:05.000000001+00:00"); + assert_eq!(fmt_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + fmt_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + fmt_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + fmt_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + fmt_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!(format_utc_seconds(at(123_456_789)), "2020-01-02 03:04:05"); + assert_eq!(format_utc_clock(at(123_456_789)), "2020-01-02 03:04:05 UTC"); + } + + #[test] + fn parsed_offsets_become_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T08:04:05+05:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05.100Z").unwrap(), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000100+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.000100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000000001Z").unwrap(), + true + ), + "2020-01-02T03:04:05.000000001Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123400Z").unwrap(), + true + ), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123456789+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.123456789Z" + ); + } + + #[test] + fn serde_json_matches_pinned_zulu_string() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Row { + #[serde(with = "super::serde_rfc3339")] + timestamp: OffsetDateTime, + } + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let row = Row { + timestamp: at(100_000_000), + }; + assert_eq!( + serde_json::to_string(&row).unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05.100Z\"}" + ); + let back: Row = + serde_json::from_str("{\"timestamp\":\"2020-01-02T08:04:05+05:00\"}").unwrap(); + assert_eq!(fmt_utc(back.timestamp, true), "2020-01-02T03:04:05Z"); + assert_eq!( + serde_json::to_string(&Opt { timestamp: None }).unwrap(), + "{\"timestamp\":null}" + ); + assert_eq!( + serde_json::to_string(&Opt { + timestamp: Some(at(0)) + }) + .unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05Z\"}" + ); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(fmt_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + assert_eq!(format_utc_seconds(civil(-1)), "-0001-01-02 03:04:05"); + assert_eq!(format_utc_clock(civil(-1)), "-0001-01-02 03:04:05 UTC"); + } + + #[test] + fn signed_years_parse_back_to_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0001-01-02T03:04:05Z").unwrap(), true), + "-0001-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("-0001-01-01T01:00:00+05:00").unwrap(), + true + ), + "-0002-12-31T20:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+0000-01-02T03:04:05Z").unwrap(), true), + "0000-01-02T03:04:05Z" + ); + assert!(parse_utc_rfc3339("-001-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn option_timestamp_reads_a_present_string_null_and_omission() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(default, with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let present: Opt = + serde_json::from_str("{\"timestamp\":\"2020-01-02T03:04:05Z\"}").unwrap(); + assert_eq!(present.timestamp, Some(at(0))); + let null: Opt = serde_json::from_str("{\"timestamp\":null}").unwrap(); + assert!(null.timestamp.is_none()); + let omitted: Opt = serde_json::from_str("{}").unwrap(); + assert!(omitted.timestamp.is_none()); + } + + #[test] + fn signed_leap_day_round_trips_and_a_non_leap_day_is_rejected() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0004-02-29T00:00:00Z").unwrap(), true), + "-0004-02-29T00:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-02-29T00:00:00Z").unwrap(), true), + "2020-02-29T00:00:00Z" + ); + assert!(parse_utc_rfc3339("-0001-02-29T00:00:00Z").is_err()); + } + + #[test] + fn years_outside_the_stored_range_are_rejected() { + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn out_of_range_offset_fails_closed() { + assert!(parse_utc_rfc3339("9999-12-31T23:59:59-01:00").is_err()); + let date = time::Date::from_calendar_date(9999, time::Month::December, 31).unwrap(); + let clock = time::Time::from_hms(23, 59, 59).unwrap(); + let offset = time::UtcOffset::from_hms(-1, 0, 0).unwrap(); + let dt = time::OffsetDateTime::new_in_offset(date, clock, offset); + assert!(format_utc(dt, true).is_err()); + assert!(format_utc(dt, false).is_err()); + } +} diff --git a/astraweave-observability/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-observability/tests/mutation_resistant_comprehensive_tests.rs index e5496d788f..12dae4297a 100644 --- a/astraweave-observability/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-observability/tests/mutation_resistant_comprehensive_tests.rs @@ -5,7 +5,6 @@ #![allow(clippy::field_reassign_with_default)] use astraweave_observability::*; -use chrono::Utc; use std::collections::HashMap; // ======================================================================== @@ -233,6 +232,7 @@ fn llm_metrics_default_zeroed() { assert_eq!(m.p99_latency_ms, 0); assert!((m.error_rate - 0.0).abs() < 1e-6); assert_eq!(m.active_requests, 0); + assert_eq!(m.last_updated.unix_timestamp(), 0); } #[test] @@ -311,7 +311,7 @@ fn alert_manager_default_empty() { #[test] fn llm_trace_serde_roundtrip() { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let trace = LlmTrace { request_id: "req-001".to_string(), session_id: Some("sess-1".to_string()), @@ -358,7 +358,7 @@ async fn telemetry_new_empty_metrics() { #[tokio::test] async fn telemetry_record_success_increments() { let tel = LlmTelemetry::new(TelemetryConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let trace = LlmTrace { request_id: "r1".into(), session_id: None, @@ -391,7 +391,7 @@ async fn telemetry_record_success_increments() { #[tokio::test] async fn telemetry_record_failure_increments() { let tel = LlmTelemetry::new(TelemetryConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let trace = LlmTrace { request_id: "r2".into(), session_id: None, @@ -424,7 +424,7 @@ async fn telemetry_record_failure_increments() { #[tokio::test] async fn telemetry_clear_data_resets() { let tel = LlmTelemetry::new(TelemetryConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let trace = LlmTrace { request_id: "r3".into(), session_id: None, @@ -483,7 +483,7 @@ async fn telemetry_dashboard_data_has_structure() { #[tokio::test] async fn telemetry_multiple_requests_accumulate() { let tel = LlmTelemetry::new(TelemetryConfig::default()); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); for i in 0..5 { let trace = LlmTrace { request_id: format!("req-{}", i), @@ -685,7 +685,7 @@ fn make_trace( cost: f64, success: bool, ) -> LlmTrace { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); LlmTrace { request_id: id.into(), session_id: None, diff --git a/astraweave-optimization/Cargo.toml b/astraweave-optimization/Cargo.toml index 0ee3de384d..fca9ac241c 100644 --- a/astraweave-optimization/Cargo.toml +++ b/astraweave-optimization/Cargo.toml @@ -17,7 +17,7 @@ tokio = { workspace = true } tracing = { workspace = true } futures = "0.3" uuid = { version = "1.0", features = ["v4"] } -chrono = { version = "0.4", features = ["serde"] } +time = { version = "0.3", features = ["parsing"] } dashmap = "6.0" async-trait = "0.1" lru = "0.18" @@ -26,4 +26,3 @@ tokio-util = "0.7" [dev-dependencies] criterion = { version = "0.5", features = ["html_reports"] } serde_json = { workspace = true } -chrono = { version = "0.4", features = ["serde"] } \ No newline at end of file diff --git a/astraweave-optimization/src/batch_inference.rs b/astraweave-optimization/src/batch_inference.rs index 723e1ff0c2..29c3761865 100644 --- a/astraweave-optimization/src/batch_inference.rs +++ b/astraweave-optimization/src/batch_inference.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use chrono::{DateTime, Utc}; use futures::future::join_all; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -62,8 +61,10 @@ pub struct BatchRequest { pub prompt: String, pub parameters: InferenceParameters, pub priority: RequestPriority, - pub created_at: DateTime, - pub timeout_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub created_at: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timeout_at: time::OffsetDateTime, #[serde(skip)] pub response_sender: Option>>, } @@ -107,13 +108,13 @@ pub enum RequestPriority { pub struct ActiveBatch { pub id: String, pub requests: Vec, - pub started_at: DateTime, + pub started_at: time::OffsetDateTime, pub client_id: usize, pub processing: bool, } /// Metrics for batch inference performance -#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct BatchMetrics { pub total_requests: u64, pub completed_requests: u64, @@ -124,7 +125,25 @@ pub struct BatchMetrics { pub throughput_requests_per_second: f32, pub queue_depth: usize, pub active_batches: usize, - pub last_updated: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_updated: time::OffsetDateTime, +} + +impl Default for BatchMetrics { + fn default() -> Self { + Self { + total_requests: 0, + completed_requests: 0, + failed_requests: 0, + average_batch_size: 0.0, + average_processing_time_ms: 0.0, + average_wait_time_ms: 0.0, + throughput_requests_per_second: 0.0, + queue_depth: 0, + active_batches: 0, + last_updated: time::OffsetDateTime::UNIX_EPOCH, + } + } } /// Result of batch processing @@ -224,9 +243,11 @@ impl BatchInferenceEngine { prompt, parameters, priority, - created_at: Utc::now(), - timeout_at: Utc::now() - + chrono::Duration::from_std(self.config.request_timeout).unwrap_or_default(), + created_at: time::OffsetDateTime::now_utc(), + timeout_at: crate::utc_stamp::instant_after( + time::OffsetDateTime::now_utc(), + self.config.request_timeout, + ), response_sender: Some(response_tx), }; @@ -244,7 +265,7 @@ impl BatchInferenceEngine { let mut metrics = self.metrics.write().await; metrics.total_requests += 1; metrics.queue_depth = self.request_queue.read().await.len(); - metrics.last_updated = Utc::now(); + metrics.last_updated = time::OffsetDateTime::now_utc(); } debug!("Submitted request to batch queue"); @@ -305,19 +326,22 @@ impl BatchInferenceEngine { tokio::spawn(async move { info!("Started batch scheduler"); - let mut last_schedule = Utc::now(); + let mut last_schedule = time::OffsetDateTime::now_utc(); loop { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); // Check if we should create a new batch let should_schedule = { let queue = request_queue.read().await; - - queue.len() >= config.min_batch_size - || (!queue.is_empty() - && (now - last_schedule).to_std().unwrap_or(Duration::ZERO) - >= config.batch_timeout) + let elapsed = + crate::utc_stamp::saturating_std(now - last_schedule, Duration::ZERO); + Self::should_schedule_batch( + queue.len(), + elapsed, + config.min_batch_size, + config.batch_timeout, + ) }; if should_schedule { @@ -339,20 +363,19 @@ impl BatchInferenceEngine { tokio::spawn(async move { let mut last_completed = 0u64; - let mut last_time = Utc::now(); + let mut last_time = time::OffsetDateTime::now_utc(); loop { sleep(Duration::from_secs(1)).await; - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut m = metrics.write().await; // Calculate throughput - let completed_diff = m.completed_requests - last_completed; - let time_diff = (now - last_time) - .to_std() - .unwrap_or(Duration::from_secs(1)) - .as_secs_f32(); + let completed_diff = Self::completed_since(m.completed_requests, last_completed); + let time_diff = + crate::utc_stamp::saturating_std(now - last_time, Duration::from_secs(1)) + .as_secs_f32(); if time_diff > 0.0 { m.throughput_requests_per_second = completed_diff as f32 / time_diff; @@ -500,6 +523,19 @@ impl BatchInferenceEngine { ); } + fn should_schedule_batch( + queue_len: usize, + elapsed: Duration, + min_batch_size: usize, + batch_timeout: Duration, + ) -> bool { + queue_len >= min_batch_size || (queue_len > 0 && elapsed >= batch_timeout) + } + + fn completed_since(total: u64, previous: u64) -> u64 { + total - previous + } + /// Schedule a new batch from the request queue async fn schedule_batch( request_queue: &Arc>>, @@ -526,7 +562,7 @@ impl BatchInferenceEngine { let batch = ActiveBatch { id: Uuid::new_v4().to_string(), requests: batch_requests, - started_at: Utc::now(), + started_at: time::OffsetDateTime::now_utc(), client_id: 0, // Will be assigned by worker processing: false, }; @@ -550,7 +586,7 @@ impl BatchInferenceEngine { // Check urgency based on request timeouts let urgent_count = queue .iter() - .filter(|req| (req.timeout_at - Utc::now()).num_seconds() < 5) + .filter(|req| (req.timeout_at - time::OffsetDateTime::now_utc()).whole_seconds() < 5) .count(); if urgent_count > 0 { @@ -568,7 +604,7 @@ impl BatchInferenceEngine { /// Clean up expired requests from the queue async fn clean_expired_requests( request_queue: &Arc>>, - current_time: DateTime, + current_time: time::OffsetDateTime, ) { let mut queue = request_queue.write().await; let initial_len = queue.len(); @@ -686,8 +722,8 @@ mod tests { prompt: "Test".to_string(), parameters: InferenceParameters::default(), priority: RequestPriority::Normal, - created_at: Utc::now(), - timeout_at: Utc::now() + chrono::Duration::seconds(30), + created_at: time::OffsetDateTime::now_utc(), + timeout_at: time::OffsetDateTime::now_utc() + time::Duration::seconds(30), response_sender: None, }]; @@ -695,4 +731,132 @@ mod tests { assert!(batch_size > 0); assert!(batch_size <= config.max_batch_size); } + + fn request_due(seconds_left: i64) -> BatchRequest { + let now = time::OffsetDateTime::now_utc(); + BatchRequest { + id: format!("req-{seconds_left}"), + prompt: "p".into(), + parameters: InferenceParameters::default(), + priority: RequestPriority::Normal, + created_at: now, + timeout_at: now + + time::Duration::seconds(seconds_left) + + time::Duration::milliseconds(200), + response_sender: None, + } + } + + #[test] + fn schedule_predicate_matches_queue_length_and_timeout() { + let min = 4; + let timeout = Duration::from_millis(100); + let due = |len, elapsed_ms| { + BatchInferenceEngine::should_schedule_batch( + len, + Duration::from_millis(elapsed_ms), + min, + timeout, + ) + }; + assert!(due(4, 0)); + assert!(due(5, 0)); + assert!(!due(3, 0)); + assert!(!due(0, 500)); + assert!(due(1, 100)); + assert!(due(1, 101)); + assert!(!due(1, 99)); + } + + #[test] + fn completed_since_is_a_difference() { + assert_eq!(BatchInferenceEngine::completed_since(10, 4), 6); + assert_eq!(BatchInferenceEngine::completed_since(4, 4), 0); + } + + #[tokio::test] + async fn submit_request_sets_a_future_timeout_and_schedule_batch_drains_the_queue() { + let engine = + BatchInferenceEngine::new(vec![Arc::new(MockLlm)], BatchInferenceConfig::default()); + let before = time::OffsetDateTime::now_utc(); + engine + .submit_request( + "p".into(), + InferenceParameters::default(), + RequestPriority::High, + ) + .await + .unwrap(); + let queued = engine.request_queue.read().await; + assert!(queued[0].timeout_at > queued[0].created_at); + assert!(queued[0].timeout_at >= before + time::Duration::seconds(29)); + drop(queued); + let metrics = engine.get_metrics().await; + assert_eq!(metrics.total_requests, 1); + + let config = BatchInferenceConfig { + enable_dynamic_batching: false, + max_batch_size: 2, + ..BatchInferenceConfig::default() + }; + let queue = Arc::new(RwLock::new(vec![request_due(30), request_due(30)])); + let batches = Arc::new(RwLock::new(HashMap::new())); + BatchInferenceEngine::schedule_batch(&queue, &batches, &config).await; + assert!(queue.read().await.is_empty()); + assert_eq!(batches.read().await.len(), 1); + assert_eq!( + batches.read().await.values().next().unwrap().requests.len(), + 2 + ); + } + + #[test] + fn dynamic_batch_size_treats_under_five_seconds_as_urgent() { + let config = BatchInferenceConfig { + min_batch_size: 1, + ..BatchInferenceConfig::default() + }; + let urgent = vec![request_due(4), request_due(4), request_due(4)]; + assert_eq!( + BatchInferenceEngine::calculate_dynamic_batch_size(&urgent, &config), + 1 + ); + let on_boundary = vec![request_due(5), request_due(5), request_due(5)]; + assert_eq!( + BatchInferenceEngine::calculate_dynamic_batch_size(&on_boundary, &config), + 3 + ); + let comfortable = vec![request_due(6), request_due(6), request_due(6)]; + assert_eq!( + BatchInferenceEngine::calculate_dynamic_batch_size(&comfortable, &config), + 3 + ); + let full: Vec<_> = (0..20).map(|_| request_due(30)).collect(); + assert_eq!( + BatchInferenceEngine::calculate_dynamic_batch_size(&full, &config), + config.optimal_batch_size + ); + } + + #[tokio::test] + async fn a_ten_thousand_year_request_timeout_does_not_abort() { + let config = BatchInferenceConfig { + request_timeout: Duration::from_secs(10_000 * 365 * 24 * 3600), + ..BatchInferenceConfig::default() + }; + let engine = BatchInferenceEngine::new(vec![Arc::new(MockLlm)], config); + engine + .submit_request( + "p".into(), + InferenceParameters::default(), + RequestPriority::Normal, + ) + .await + .unwrap(); + let queued = engine.request_queue.read().await; + assert_eq!( + queued[0].timeout_at, + time::OffsetDateTime::new_utc(time::Date::MAX, time::Time::MAX) + ); + } } diff --git a/astraweave-optimization/src/lib.rs b/astraweave-optimization/src/lib.rs index 121be4a8a2..342eb64d6f 100644 --- a/astraweave-optimization/src/lib.rs +++ b/astraweave-optimization/src/lib.rs @@ -8,6 +8,8 @@ //! - Adaptive load balancing //! - Token usage optimization +mod utc_stamp; + pub mod batch_inference; pub use batch_inference::*; diff --git a/astraweave-optimization/src/prompt_cache.rs b/astraweave-optimization/src/prompt_cache.rs index 188095516f..cb5f92214b 100644 --- a/astraweave-optimization/src/prompt_cache.rs +++ b/astraweave-optimization/src/prompt_cache.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use chrono::{DateTime, Utc}; use dashmap::DashMap; use lru::LruCache; use serde::{Deserialize, Serialize}; @@ -67,10 +66,13 @@ pub struct CachedResponse { pub response: String, pub original_prompt: String, pub prompt_hash: u64, - pub created_at: DateTime, - pub last_accessed: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub created_at: time::OffsetDateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_accessed: time::OffsetDateTime, pub access_count: u32, - pub ttl_expires_at: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub ttl_expires_at: time::OffsetDateTime, pub response_quality: f32, pub compression_ratio: Option, pub tags: Vec, @@ -108,7 +110,8 @@ pub struct CacheStats { pub average_response_time_ms: f32, pub memory_usage_mb: f32, pub compression_savings_mb: f32, - pub last_updated: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub last_updated: time::OffsetDateTime, } impl Default for CacheStats { @@ -123,7 +126,7 @@ impl Default for CacheStats { average_response_time_ms: 0.0, memory_usage_mb: 0.0, compression_savings_mb: 0.0, - last_updated: Utc::now(), + last_updated: time::OffsetDateTime::now_utc(), } } } @@ -237,7 +240,7 @@ impl PromptCache { } let prompt_hash = self.calculate_hash(prompt); - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let cached_response = CachedResponse { id: Uuid::new_v4().to_string(), @@ -247,8 +250,7 @@ impl PromptCache { created_at: now, last_accessed: now, access_count: 1, - ttl_expires_at: now - + chrono::Duration::from_std(self.config.entry_ttl).unwrap_or_default(), + ttl_expires_at: crate::utc_stamp::instant_after(now, self.config.entry_ttl), response_quality: quality, compression_ratio: None, // Would be calculated if compression is enabled tags: Vec::new(), @@ -320,7 +322,7 @@ impl PromptCache { (stats.cache_hits + stats.semantic_hits) as f32 / stats.total_requests as f32; } - stats.last_updated = Utc::now(); + stats.last_updated = time::OffsetDateTime::now_utc(); stats.clone() } @@ -388,7 +390,11 @@ impl PromptCache { /// Check if a cached response is expired fn is_expired(&self, cached: &CachedResponse) -> bool { - Utc::now() > cached.ttl_expires_at + self.expired_at(cached, time::OffsetDateTime::now_utc()) + } + + fn expired_at(&self, cached: &CachedResponse, now: time::OffsetDateTime) -> bool { + now > cached.ttl_expires_at } /// Record a cache hit @@ -397,7 +403,7 @@ impl PromptCache { for mut cached_entry in self.hash_cache.iter_mut() { let cached = cached_entry.value_mut(); if cached.id == response_id { - cached.last_accessed = Utc::now(); + cached.last_accessed = time::OffsetDateTime::now_utc(); cached.access_count += 1; break; } @@ -535,7 +541,7 @@ impl PromptCache { /// Invalidate expired entries async fn invalidate_expired(&self) -> Result { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let mut invalidated = 0; // Clean hash cache @@ -582,13 +588,17 @@ impl PromptCache { semantic_cache.retain(|_, entries| !entries.is_empty()); } - if invalidated > 0 { + if Self::any_expired(invalidated) { debug!("Invalidated {} expired cache entries", invalidated); } Ok(invalidated) } + fn any_expired(count: usize) -> bool { + count > 0 + } + /// Invalidate least recently used entries async fn invalidate_lru(&self) -> Result { // LRU cache handles this automatically, but we can force eviction @@ -709,4 +719,150 @@ mod tests { let exact_similarity = cache.calculate_text_similarity("hello world", "hello world"); assert_eq!(exact_similarity, 1.0); } + + fn cached(id: &str, ttl: time::OffsetDateTime) -> CachedResponse { + CachedResponse { + id: id.into(), + response: "r".into(), + original_prompt: id.into(), + prompt_hash: 1, + created_at: ttl, + last_accessed: ttl, + access_count: 0, + ttl_expires_at: ttl, + response_quality: 1.0, + compression_ratio: None, + tags: Vec::new(), + } + } + + #[test] + fn expiry_is_strictly_after_the_ttl() { + let cache = PromptCache::new(PromptCacheConfig::default()); + let now = time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(5_000); + let entry = cached("a", now); + assert!(!cache.expired_at(&entry, now)); + assert!(cache.expired_at(&entry, now + time::Duration::nanoseconds(1))); + assert!(!cache.expired_at(&entry, now - time::Duration::seconds(1))); + + let mut past = cached( + "past", + time::OffsetDateTime::now_utc() - time::Duration::hours(1), + ); + past.ttl_expires_at = time::OffsetDateTime::now_utc() - time::Duration::hours(1); + assert!(cache.is_expired(&past)); + let mut future = cached("future", time::OffsetDateTime::now_utc()); + future.ttl_expires_at = time::OffsetDateTime::now_utc() + time::Duration::hours(1); + assert!(!cache.is_expired(&future)); + } + + #[tokio::test] + async fn record_hit_updates_only_the_matching_id_and_stats() { + let cache = PromptCache::new(PromptCacheConfig::default()); + let now = time::OffsetDateTime::now_utc(); + cache.hash_cache.insert(1, cached("alpha", now)); + cache.hash_cache.insert(2, cached("beta", now)); + cache.record_hit("alpha").await; + assert_eq!(cache.hash_cache.get(&1).unwrap().access_count, 1); + assert_eq!(cache.hash_cache.get(&2).unwrap().access_count, 0); + { + let stats = cache.stats.read().await; + assert_eq!(stats.cache_hits, 1); + assert_eq!(stats.total_requests, 1); + } + cache.semantic_cache.write().await.insert( + "kept".into(), + vec![SemanticCacheEntry { + cached_response: cached("sem", time::OffsetDateTime::now_utc()), + embedding: Vec::new(), + similarity_scores: HashMap::new(), + }], + ); + { + let mut stats = cache.stats.write().await; + stats.semantic_hits = 3; + stats.total_requests = 8; + } + let stats = cache.get_stats().await; + assert_eq!(stats.cache_hits, 1); + assert_eq!(stats.semantic_hits, 3); + assert_eq!(stats.total_requests, 8); + assert!((stats.hit_rate - 0.5).abs() < f32::EPSILON); + assert!((stats.memory_usage_mb - (3.0 / 1024.0)).abs() < 1e-6); + + let empty = PromptCache::new(PromptCacheConfig::default()); + let empty_stats = empty.get_stats().await; + assert_eq!(empty_stats.hit_rate, 0.0); + assert_eq!(empty_stats.memory_usage_mb, 0.0); + assert_eq!(empty_stats.total_requests, 0); + assert!(PromptCache::any_expired(1)); + assert!(PromptCache::any_expired(2)); + assert!(!PromptCache::any_expired(0)); + } + + #[tokio::test] + async fn invalidate_expired_removes_every_expired_hash_entry() { + let cache = PromptCache::new(PromptCacheConfig::default()); + let now = time::OffsetDateTime::now_utc(); + cache + .hash_cache + .insert(1, cached("old-a", now - time::Duration::hours(2))); + cache + .hash_cache + .insert(2, cached("old-b", now - time::Duration::hours(3))); + cache + .hash_cache + .insert(3, cached("fresh", now + time::Duration::hours(2))); + cache.cache.write().await.put( + "old-lru".into(), + cached("old-lru", now - time::Duration::hours(1)), + ); + cache.cache.write().await.put( + "fresh-lru".into(), + cached("fresh-lru", now + time::Duration::hours(1)), + ); + cache.semantic_cache.write().await.insert( + "old".into(), + vec![SemanticCacheEntry { + cached_response: cached("old-sem", now - time::Duration::hours(1)), + embedding: Vec::new(), + similarity_scores: HashMap::new(), + }], + ); + cache.semantic_cache.write().await.insert( + "keep".into(), + vec![SemanticCacheEntry { + cached_response: cached("fresh-sem", now + time::Duration::hours(1)), + embedding: Vec::new(), + similarity_scores: HashMap::new(), + }], + ); + let removed = cache.invalidate_expired().await.unwrap(); + assert_eq!(removed, 4); + assert_eq!(cache.hash_cache.len(), 1); + assert!(cache.hash_cache.contains_key(&3)); + let lru = cache.cache.read().await; + assert!(lru.contains(&String::from("fresh-lru"))); + assert!(!lru.contains(&String::from("old-lru"))); + drop(lru); + let semantic = cache.semantic_cache.read().await; + assert!(semantic.contains_key("keep")); + assert!(!semantic.contains_key("old")); + } + + #[tokio::test] + async fn a_ten_thousand_year_ttl_does_not_abort() { + let config = PromptCacheConfig { + entry_ttl: Duration::from_secs(10_000 * 365 * 24 * 3600), + enable_semantic_cache: false, + ..PromptCacheConfig::default() + }; + let cache = PromptCache::new(config); + cache.store("prompt", "response", 1.0).await.unwrap(); + let stored = cache.hash_cache.iter().next().expect("stored entry"); + assert_eq!( + stored.ttl_expires_at, + time::OffsetDateTime::new_utc(time::Date::MAX, time::Time::MAX) + ); + } } diff --git a/astraweave-optimization/src/utc_stamp.rs b/astraweave-optimization/src/utc_stamp.rs new file mode 100644 index 0000000000..7adc22e82c --- /dev/null +++ b/astraweave-optimization/src/utc_stamp.rs @@ -0,0 +1,431 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Negative years through `-9999` keep a +//! sign and four digits. A year outside `-9999..=9999` is rejected; `large-dates` +//! is not enabled. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. A negative year keeps a sign and four +/// digits. Values outside `-9999..=9999` are not stored. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> Result { + let utc = dt + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year)?; + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + Ok(out) +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +fn invalid_year() -> time::error::Parse { + time::error::Parse::ParseFromDescription(time::error::ParseFromDescription::InvalidComponent( + "year", + )) +} + +pub(crate) fn parse_utc_rfc3339(text: &str) -> Result { + let rfc3339 = &time::format_description::well_known::Rfc3339; + if text.starts_with('+') || text.starts_with('-') { + parse_signed_year(text, rfc3339) + } else { + OffsetDateTime::parse(text, rfc3339).and_then(|dt| { + dt.checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) + }) + } +} + +/// A leading sign is outside `time`'s RFC 3339 year. The magnitude is at least +/// four digits. The remainder is parsed as year 2000 so a leap day survives, +/// then the result is stored as UTC. +fn parse_signed_year( + text: &str, + rfc3339: &time::format_description::well_known::Rfc3339, +) -> Result { + let negative = text.starts_with('-'); + let rest = &text[1..]; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + if digits < 4 { + return Err(invalid_year()); + } + let magnitude: i32 = rest[..digits].parse().map_err(|_| invalid_year())?; + let year = if negative { + magnitude.checked_neg().ok_or_else(invalid_year)? + } else { + magnitude + }; + let parsed = OffsetDateTime::parse(&format!("2000{}", &rest[digits..]), rfc3339)?; + let date = time::Date::from_calendar_date(year, parsed.month(), parsed.day()) + .map_err(|_| invalid_year())?; + OffsetDateTime::new_in_offset(date, parsed.time(), parsed.offset()) + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) +} + +pub(crate) mod serde_rfc3339 { + use super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize(dt: &OffsetDateTime, serializer: S) -> Result { + let text = format_utc(*dt, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_str(&text) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result { + let text = String::deserialize(deserializer)?; + parse_utc_rfc3339(&text).map_err(serde::de::Error::custom) + } + + #[allow(dead_code)] + pub mod option { + use super::super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize( + dt: &Option, + serializer: S, + ) -> Result { + match dt { + Some(value) => { + let text = format_utc(*value, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_some(&text) + } + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let text = Option::::deserialize(deserializer)?; + text.map(|value| parse_utc_rfc3339(&value).map_err(serde::de::Error::custom)) + .transpose() + } + } +} + +pub(crate) fn saturating_std( + duration: time::Duration, + fallback: std::time::Duration, +) -> std::time::Duration { + std::time::Duration::try_from(duration).unwrap_or(fallback) +} + +/// `now` plus a configured span. +/// +/// A span that does not fit the clock uses the latest instant the clock can store. +pub(crate) fn instant_after(now: OffsetDateTime, span: std::time::Duration) -> OffsetDateTime { + let duration = time::Duration::try_from(span).unwrap_or(time::Duration::MAX); + now.checked_add(duration).unwrap_or_else(latest_instant) +} + +fn latest_instant() -> OffsetDateTime { + OffsetDateTime::new_utc(time::Date::MAX, time::Time::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + fn fmt_utc(dt: OffsetDateTime, zulu: bool) -> String { + format_utc(dt, zulu).unwrap() + } + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(fmt_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + fmt_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!(fmt_utc(at(100_000_000), true), "2020-01-02T03:04:05.100Z"); + assert_eq!( + fmt_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(fmt_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + fmt_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(fmt_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!(fmt_utc(at(1), false), "2020-01-02T03:04:05.000000001+00:00"); + assert_eq!(fmt_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + fmt_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + fmt_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + fmt_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + fmt_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + } + + #[test] + fn parsed_offsets_become_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T08:04:05+05:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05.100Z").unwrap(), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000100+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.000100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000000001Z").unwrap(), + true + ), + "2020-01-02T03:04:05.000000001Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123400Z").unwrap(), + true + ), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123456789+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.123456789Z" + ); + } + + #[test] + fn serde_json_matches_pinned_zulu_string() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Row { + #[serde(with = "super::serde_rfc3339")] + timestamp: OffsetDateTime, + } + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let row = Row { + timestamp: at(100_000_000), + }; + assert_eq!( + serde_json::to_string(&row).unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05.100Z\"}" + ); + let back: Row = + serde_json::from_str("{\"timestamp\":\"2020-01-02T08:04:05+05:00\"}").unwrap(); + assert_eq!(fmt_utc(back.timestamp, true), "2020-01-02T03:04:05Z"); + assert_eq!( + serde_json::to_string(&Opt { timestamp: None }).unwrap(), + "{\"timestamp\":null}" + ); + assert_eq!( + serde_json::to_string(&Opt { + timestamp: Some(at(0)) + }) + .unwrap(), + "{\"timestamp\":\"2020-01-02T03:04:05Z\"}" + ); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(fmt_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + } + + #[test] + fn signed_years_parse_back_to_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0001-01-02T03:04:05Z").unwrap(), true), + "-0001-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("-0001-01-01T01:00:00+05:00").unwrap(), + true + ), + "-0002-12-31T20:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+0000-01-02T03:04:05Z").unwrap(), true), + "0000-01-02T03:04:05Z" + ); + assert!(parse_utc_rfc3339("-001-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn option_timestamp_reads_a_present_string_null_and_omission() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(default, with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let present: Opt = + serde_json::from_str("{\"timestamp\":\"2020-01-02T03:04:05Z\"}").unwrap(); + assert_eq!(present.timestamp, Some(at(0))); + let null: Opt = serde_json::from_str("{\"timestamp\":null}").unwrap(); + assert!(null.timestamp.is_none()); + let omitted: Opt = serde_json::from_str("{}").unwrap(); + assert!(omitted.timestamp.is_none()); + } + + #[test] + fn instant_after_keeps_a_span_that_fits() { + let now = OffsetDateTime::UNIX_EPOCH; + assert_eq!( + instant_after(now, std::time::Duration::from_secs(30)), + now.checked_add(time::Duration::seconds(30)) + .expect("30s fits") + ); + } + + #[test] + fn instant_after_uses_the_latest_instant_when_the_span_does_not_fit() { + let now = OffsetDateTime::UNIX_EPOCH; + let latest = latest_instant(); + let ten_thousand_years = std::time::Duration::from_secs(10_000 * 365 * 24 * 3600); + assert_eq!(instant_after(now, ten_thousand_years), latest); + assert_eq!(instant_after(now, std::time::Duration::MAX), latest); + } + + #[test] + fn saturating_std_keeps_a_nonzero_duration() { + assert_eq!( + saturating_std( + time::Duration::seconds(2), + std::time::Duration::from_secs(9) + ), + std::time::Duration::from_secs(2) + ); + assert_eq!( + saturating_std( + time::Duration::seconds(-1), + std::time::Duration::from_secs(9) + ), + std::time::Duration::from_secs(9) + ); + } + + #[test] + fn signed_leap_day_round_trips_and_a_non_leap_day_is_rejected() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0004-02-29T00:00:00Z").unwrap(), true), + "-0004-02-29T00:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-02-29T00:00:00Z").unwrap(), true), + "2020-02-29T00:00:00Z" + ); + assert!(parse_utc_rfc3339("-0001-02-29T00:00:00Z").is_err()); + } + + #[test] + fn years_outside_the_stored_range_are_rejected() { + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn out_of_range_offset_fails_closed() { + assert!(parse_utc_rfc3339("9999-12-31T23:59:59-01:00").is_err()); + let date = time::Date::from_calendar_date(9999, time::Month::December, 31).unwrap(); + let clock = time::Time::from_hms(23, 59, 59).unwrap(); + let offset = time::UtcOffset::from_hms(-1, 0, 0).unwrap(); + let dt = time::OffsetDateTime::new_in_offset(date, clock, offset); + assert!(format_utc(dt, true).is_err()); + assert!(format_utc(dt, false).is_err()); + } +} diff --git a/astraweave-optimization/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-optimization/tests/mutation_resistant_comprehensive_tests.rs index 7e6261309b..41d357c12c 100644 --- a/astraweave-optimization/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-optimization/tests/mutation_resistant_comprehensive_tests.rs @@ -7,7 +7,6 @@ //! InvalidationStrategy (all variants). use astraweave_optimization::*; -use chrono::Utc; use std::collections::HashMap; use std::time::Duration; @@ -128,6 +127,7 @@ fn request_priority_serde_roundtrip() { fn batch_metrics_default_total_requests() { let m = BatchMetrics::default(); assert_eq!(m.total_requests, 0); + assert_eq!(m.last_updated.unix_timestamp(), 0); } #[test] @@ -295,7 +295,7 @@ fn cache_config_clone() { } // ========================================================================= -// CacheStats — manual Default (last_updated = Utc::now()) +// CacheStats — manual Default (last_updated = time::OffsetDateTime::now_utc()) // ========================================================================= #[test] @@ -354,9 +354,9 @@ fn cache_stats_default_compression_savings() { #[test] fn cache_stats_default_last_updated_is_recent() { - let before = Utc::now(); + let before = time::OffsetDateTime::now_utc(); let s = CacheStats::default(); - let after = Utc::now(); + let after = time::OffsetDateTime::now_utc(); assert!(s.last_updated >= before); assert!(s.last_updated <= after); } @@ -377,7 +377,7 @@ fn cache_stats_serde_roundtrip() { #[test] fn cached_response_serde_roundtrip() { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let r = CachedResponse { id: "resp1".to_string(), response: "Hello world".to_string(), @@ -404,7 +404,7 @@ fn cached_response_serde_roundtrip() { #[test] fn cached_response_clone() { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let r = CachedResponse { id: "r1".to_string(), response: "ok".to_string(), @@ -455,7 +455,7 @@ fn prompt_template_serde_roundtrip() { #[test] fn semantic_cache_entry_serde_roundtrip() { - let now = Utc::now(); + let now = time::OffsetDateTime::now_utc(); let entry = SemanticCacheEntry { cached_response: CachedResponse { id: "se1".to_string(), diff --git a/astraweave-persona/Cargo.toml b/astraweave-persona/Cargo.toml index 4643fd59d9..b783d3ec0e 100644 --- a/astraweave-persona/Cargo.toml +++ b/astraweave-persona/Cargo.toml @@ -26,7 +26,7 @@ async-trait = "0.1" # Additional utilities uuid = { version = "1.0", features = ["v4", "serde"] } -chrono = { version = "0.4", features = ["serde"] } +time = "0.3" rand = "0.9" [dev-dependencies] diff --git a/astraweave-persona/src/lib.rs b/astraweave-persona/src/lib.rs index 3f3b8ec406..97dcb01879 100644 --- a/astraweave-persona/src/lib.rs +++ b/astraweave-persona/src/lib.rs @@ -348,3 +348,6 @@ prefs_json = 'invalid json {' assert!(msg.contains("exceeds cap"), "{msg}"); } } + +#[cfg(test)] +mod unix_instant; diff --git a/astraweave-persona/src/llm_persona.rs b/astraweave-persona/src/llm_persona.rs index 2e67f58301..30a2e1f02a 100644 --- a/astraweave-persona/src/llm_persona.rs +++ b/astraweave-persona/src/llm_persona.rs @@ -845,7 +845,7 @@ Respond as {{persona.name}} would, staying true to your personality, current sta let influence = PersonalityInfluence { event: trigger.to_string(), factor_changes, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, decay_rate: 0.1, }; diff --git a/astraweave-persona/src/unix_instant.rs b/astraweave-persona/src/unix_instant.rs new file mode 100644 index 0000000000..5dd2be2d85 --- /dev/null +++ b/astraweave-persona/src/unix_instant.rs @@ -0,0 +1,10 @@ +//! Unix seconds for 2020-01-02 03:04:05 UTC. Subsecond digits do not change the second. + +#[test] +fn unix_timestamp_matches_pinned_instant() { + let whole = time::OffsetDateTime::from_unix_timestamp(1_577_934_245).unwrap(); + assert_eq!(whole.unix_timestamp(), 1_577_934_245); + let subsec = + time::OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_100_000_000).unwrap(); + assert_eq!(subsec.unix_timestamp(), 1_577_934_245); +} diff --git a/astraweave-prompts/Cargo.toml b/astraweave-prompts/Cargo.toml index 25796aedcb..79a37cc038 100644 --- a/astraweave-prompts/Cargo.toml +++ b/astraweave-prompts/Cargo.toml @@ -25,7 +25,7 @@ walkdir = "2.4" regex = "1.12" # Date and time -chrono = { version = "0.4", features = ["serde"] } +time = "0.3" # Random number generation for few-shot examples rand = "0.9" diff --git a/astraweave-prompts/src/lib.rs b/astraweave-prompts/src/lib.rs index 404ea11fed..6e04d903ac 100644 --- a/astraweave-prompts/src/lib.rs +++ b/astraweave-prompts/src/lib.rs @@ -45,6 +45,8 @@ fn main() -> anyhow::Result<()> { ``` */ +mod utc_stamp; + pub mod context; pub mod engine; pub mod helpers; diff --git a/astraweave-prompts/src/library.rs b/astraweave-prompts/src/library.rs index 150c935102..60ca39311a 100644 --- a/astraweave-prompts/src/library.rs +++ b/astraweave-prompts/src/library.rs @@ -133,7 +133,7 @@ impl LibraryMetadata { version: version.into(), description: description.into(), author: author.into(), - created_at: chrono::Utc::now().to_rfc3339(), + created_at: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), } } @@ -143,7 +143,7 @@ impl LibraryMetadata { version: "1.0.0".to_string(), description: "AstraWeave Template Library".to_string(), author: "AstraWeave".to_string(), - created_at: chrono::Utc::now().to_rfc3339(), + created_at: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), } } @@ -324,7 +324,7 @@ impl TemplateLibrary { version: "1.0.0".to_string(), description: "Loaded from directory".to_string(), author: "AstraWeave".to_string(), - created_at: chrono::Utc::now().to_rfc3339(), + created_at: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), }, ); diff --git a/astraweave-prompts/src/utc_stamp.rs b/astraweave-prompts/src/utc_stamp.rs new file mode 100644 index 0000000000..7d1704f6f2 --- /dev/null +++ b/astraweave-prompts/src/utc_stamp.rs @@ -0,0 +1,132 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Every other year +//! keeps a sign and at least four digits of magnitude. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. Any other year keeps a sign and at least +/// four digits of magnitude. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub(crate) fn format_utc_rfc3339(dt: OffsetDateTime) -> String { + format_utc(dt, false) +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> String { + let utc = dt.to_offset(UtcOffset::UTC); + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + out +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(format_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(format_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + format_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!( + format_utc(at(100_000_000), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + format_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(format_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + format_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(format_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!( + format_utc(at(1), false), + "2020-01-02T03:04:05.000000001+00:00" + ); + assert_eq!(format_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + format_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + format_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + format_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + format_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + format_utc_rfc3339(at(100_000_000)), + "2020-01-02T03:04:05.100+00:00" + ); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(format_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(format_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(format_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(format_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(format_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + assert_eq!(format_utc_rfc3339(civil(-1)), "-0001-01-02T03:04:05+00:00"); + } +} diff --git a/astraweave-quests/Cargo.toml b/astraweave-quests/Cargo.toml index 30ffed14f5..86f8e38bce 100644 --- a/astraweave-quests/Cargo.toml +++ b/astraweave-quests/Cargo.toml @@ -18,7 +18,6 @@ tokio = { workspace = true } tracing = { workspace = true } futures = "0.3" uuid = { version = "1.0", features = ["v4"] } -chrono = { version = "0.4", features = ["serde"] } rand.workspace = true # Phase 10: Terrain quest triggers [dev-dependencies] diff --git a/astraweave-rag/Cargo.toml b/astraweave-rag/Cargo.toml index 5d0de30066..eb436efbe3 100644 --- a/astraweave-rag/Cargo.toml +++ b/astraweave-rag/Cargo.toml @@ -29,7 +29,7 @@ dashmap = "6.1" parking_lot = "0.12" # Date and time -chrono = { version = "0.4", features = ["serde"] } +time = "0.3" # Random sampling for diversity rand = "0.9" diff --git a/astraweave-rag/benches/rag_benchmarks.rs b/astraweave-rag/benches/rag_benchmarks.rs index c58936446e..427af9111d 100644 --- a/astraweave-rag/benches/rag_benchmarks.rs +++ b/astraweave-rag/benches/rag_benchmarks.rs @@ -17,7 +17,7 @@ fn create_test_memory(id: &str, text: &str, category: MemoryCategory, importance id: id.to_string(), text: text.to_string(), category, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance, valence: 0.0, entities: vec![], diff --git a/astraweave-rag/src/consolidation.rs b/astraweave-rag/src/consolidation.rs index 20155094fb..a76b8eac79 100644 --- a/astraweave-rag/src/consolidation.rs +++ b/astraweave-rag/src/consolidation.rs @@ -204,7 +204,7 @@ mod tests { id: id.to_string(), text: text.to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance, valence: 0.0, entities: vec![], @@ -217,7 +217,7 @@ mod tests { id: id.to_string(), text: text.to_string(), category, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], @@ -234,7 +234,7 @@ mod tests { id: id.to_string(), text: text.to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], @@ -316,7 +316,7 @@ mod tests { id: "1".to_string(), text: "The cat is sleeping".to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], @@ -326,7 +326,7 @@ mod tests { id: "2".to_string(), text: "The cat is resting".to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], diff --git a/astraweave-rag/src/forgetting.rs b/astraweave-rag/src/forgetting.rs index bbfd13f481..f866188e81 100644 --- a/astraweave-rag/src/forgetting.rs +++ b/astraweave-rag/src/forgetting.rs @@ -66,7 +66,7 @@ impl Default for MemoryStrength { Self { current_strength: 1.0, initial_strength: 1.0, - last_access: chrono::Utc::now().timestamp(), + last_access: time::OffsetDateTime::now_utc().unix_timestamp(), access_count: 0, protected: false, } @@ -115,7 +115,7 @@ impl ForgettingEngine { let mut forgotten_count = 0; let mut updated_count = 0; - let current_time = chrono::Utc::now().timestamp(); + let current_time = time::OffsetDateTime::now_utc().unix_timestamp(); for memory in memories { // Get or create strength tracking for this memory @@ -206,7 +206,7 @@ impl ForgettingEngine { pub fn strengthen_memory(&mut self, memory_id: &str, boost_factor: f32) -> Result<()> { if let Some(strength) = self.memory_strengths.get_mut(memory_id) { strength.current_strength = (strength.current_strength + boost_factor).min(1.0); - strength.last_access = chrono::Utc::now().timestamp(); + strength.last_access = time::OffsetDateTime::now_utc().unix_timestamp(); strength.access_count += 1; } Ok(()) @@ -295,7 +295,7 @@ mod tests { id: "1".to_string(), text: "Recent memory".to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], @@ -305,7 +305,7 @@ mod tests { id: "2".to_string(), text: "Old memory".to_string(), category: MemoryCategory::Social, - timestamp: (chrono::Utc::now().timestamp() - 3600) as u64, // 1 hour old + timestamp: (time::OffsetDateTime::now_utc().unix_timestamp() - 3600) as u64, // 1 hour old importance: 0.5, valence: 0.0, entities: vec![], @@ -336,7 +336,7 @@ mod tests { id: "test1".to_string(), text: "Test memory".to_string(), category: MemoryCategory::Gameplay, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], @@ -364,7 +364,7 @@ mod tests { id: "protect_test".to_string(), text: "Important memory".to_string(), category: MemoryCategory::Gameplay, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.1, // Very low importance valence: 0.0, entities: vec![], @@ -400,7 +400,7 @@ mod tests { id: "1".to_string(), text: "Memory 1".to_string(), category: MemoryCategory::Gameplay, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], @@ -410,7 +410,7 @@ mod tests { id: "2".to_string(), text: "Memory 2".to_string(), category: MemoryCategory::Quest, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.8, valence: 0.0, entities: vec![], @@ -438,7 +438,7 @@ mod tests { id: "decay_test".to_string(), text: "Test decay".to_string(), category: MemoryCategory::Gameplay, - timestamp: (chrono::Utc::now().timestamp() - 3600) as u64, // 1 hour old + timestamp: (time::OffsetDateTime::now_utc().unix_timestamp() - 3600) as u64, // 1 hour old importance: 0.5, valence: 0.0, entities: vec![], @@ -470,8 +470,8 @@ mod tests { id: "quest1".to_string(), text: "Important quest".to_string(), category: MemoryCategory::Quest, // Protected category - timestamp: (chrono::Utc::now().timestamp() - 10000) as u64, // Very old - importance: 0.1, // Very low importance + timestamp: (time::OffsetDateTime::now_utc().unix_timestamp() - 10000) as u64, // Very old + importance: 0.1, // Very low importance valence: 0.0, entities: vec![], context: HashMap::new(), @@ -496,8 +496,8 @@ mod tests { id: "old1".to_string(), text: "Very old memory".to_string(), category: MemoryCategory::Gameplay, - timestamp: (chrono::Utc::now().timestamp() - 200) as u64, // 200 seconds old - importance: 0.9, // High importance + timestamp: (time::OffsetDateTime::now_utc().unix_timestamp() - 200) as u64, // 200 seconds old + importance: 0.9, // High importance valence: 0.0, entities: vec![], context: HashMap::new(), @@ -523,7 +523,7 @@ mod tests { id: "high_imp".to_string(), text: "High importance memory".to_string(), category: MemoryCategory::Gameplay, - timestamp: (chrono::Utc::now().timestamp() - 7200) as u64, // 2 hours old + timestamp: (time::OffsetDateTime::now_utc().unix_timestamp() - 7200) as u64, // 2 hours old importance: 0.9, valence: 0.0, entities: vec![], @@ -534,7 +534,7 @@ mod tests { id: "low_imp".to_string(), text: "Low importance memory".to_string(), category: MemoryCategory::Gameplay, - timestamp: (chrono::Utc::now().timestamp() - 7200) as u64, // 2 hours old + timestamp: (time::OffsetDateTime::now_utc().unix_timestamp() - 7200) as u64, // 2 hours old importance: 0.1, valence: 0.0, entities: vec![], diff --git a/astraweave-rag/src/injection.rs b/astraweave-rag/src/injection.rs index 13c6cd17b7..564df32a4e 100644 --- a/astraweave-rag/src/injection.rs +++ b/astraweave-rag/src/injection.rs @@ -162,7 +162,7 @@ impl InjectionEngine { /// Calculate recency boost for memory fn recency_boost(&self, memory: &Memory) -> f32 { - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let age_seconds = (now - memory.timestamp as i64).max(0) as f32; let age_hours = age_seconds / 3600.0; @@ -228,7 +228,7 @@ mod tests { id: "1".to_string(), text: "Cats are independent animals".to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], diff --git a/astraweave-rag/src/lib.rs b/astraweave-rag/src/lib.rs index 9dde884b1b..340c1fb8d9 100644 --- a/astraweave-rag/src/lib.rs +++ b/astraweave-rag/src/lib.rs @@ -514,3 +514,6 @@ mod tests { assert_eq!(strategies.len(), 5); } } + +#[cfg(test)] +mod unix_instant; diff --git a/astraweave-rag/src/retrieval.rs b/astraweave-rag/src/retrieval.rs index 9805914df3..649e99ce1a 100644 --- a/astraweave-rag/src/retrieval.rs +++ b/astraweave-rag/src/retrieval.rs @@ -142,7 +142,7 @@ mod tests { id: "1".to_string(), text: "The cat sat on the mat".to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], @@ -152,7 +152,7 @@ mod tests { id: "2".to_string(), text: "Dogs are loyal animals".to_string(), category: MemoryCategory::Social, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], diff --git a/astraweave-rag/src/unix_instant.rs b/astraweave-rag/src/unix_instant.rs new file mode 100644 index 0000000000..5dd2be2d85 --- /dev/null +++ b/astraweave-rag/src/unix_instant.rs @@ -0,0 +1,10 @@ +//! Unix seconds for 2020-01-02 03:04:05 UTC. Subsecond digits do not change the second. + +#[test] +fn unix_timestamp_matches_pinned_instant() { + let whole = time::OffsetDateTime::from_unix_timestamp(1_577_934_245).unwrap(); + assert_eq!(whole.unix_timestamp(), 1_577_934_245); + let subsec = + time::OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_100_000_000).unwrap(); + assert_eq!(subsec.unix_timestamp(), 1_577_934_245); +} diff --git a/astraweave-rag/tests/consolidation_tests.rs b/astraweave-rag/tests/consolidation_tests.rs index 088a1c3221..4271e60224 100644 --- a/astraweave-rag/tests/consolidation_tests.rs +++ b/astraweave-rag/tests/consolidation_tests.rs @@ -4,7 +4,6 @@ use astraweave_embeddings::{Memory, MemoryCategory}; use astraweave_rag::consolidation::{ ConsolidationConfig, ConsolidationEngine, ConsolidationStrategy, }; -use chrono::Utc; use std::collections::HashMap; fn create_memory(id: &str, text: &str, category: MemoryCategory) -> Memory { @@ -12,7 +11,7 @@ fn create_memory(id: &str, text: &str, category: MemoryCategory) -> Memory { id: id.to_string(), text: text.to_string(), category, - timestamp: Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities: vec![], diff --git a/astraweave-rag/tests/injection_tests.rs b/astraweave-rag/tests/injection_tests.rs index 891e678b00..9bf5833000 100644 --- a/astraweave-rag/tests/injection_tests.rs +++ b/astraweave-rag/tests/injection_tests.rs @@ -3,11 +3,10 @@ use astraweave_embeddings::{Memory, MemoryCategory}; use astraweave_rag::injection::{InjectionConfig, InjectionContext, InjectionEngine}; use astraweave_rag::InjectionStrategy; -use chrono::Utc; use std::collections::HashMap; fn create_memory(id: &str, text: &str, category: MemoryCategory, age_hours: i64) -> Memory { - let timestamp = Utc::now().timestamp() - (age_hours * 3600); + let timestamp = time::OffsetDateTime::now_utc().unix_timestamp() - (age_hours * 3600); Memory { id: id.to_string(), text: text.to_string(), diff --git a/astraweave-rag/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-rag/tests/mutation_resistant_comprehensive_tests.rs index 33b09542b8..71e213ced0 100644 --- a/astraweave-rag/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-rag/tests/mutation_resistant_comprehensive_tests.rs @@ -19,7 +19,7 @@ fn make_memory(id: &str, text: &str, category: MemoryCategory, importance: f32) id: id.to_string(), text: text.to_string(), category, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance, valence: 0.0, entities: vec![], @@ -45,7 +45,7 @@ fn make_memory_with_entities(id: &str, text: &str, entities: Vec) -> Mem id: id.to_string(), text: text.to_string(), category: MemoryCategory::Combat, - timestamp: chrono::Utc::now().timestamp() as u64, + timestamp: time::OffsetDateTime::now_utc().unix_timestamp() as u64, importance: 0.5, valence: 0.0, entities, @@ -1060,7 +1060,7 @@ fn decay_modifier_formula_importance_matters() { let mut engine = ForgettingEngine::new(config); // Use timestamps far enough in the past that decay is visible - let old_ts = (chrono::Utc::now().timestamp() - 36000) as u64; // 10 hours ago + let old_ts = (time::OffsetDateTime::now_utc().unix_timestamp() - 36000) as u64; // 10 hours ago let m_high = make_memory_with_timestamp("high", "important memory", old_ts, 0.9); let m_low = make_memory_with_timestamp("low", "unimportant memory", old_ts, 0.1); @@ -1097,7 +1097,7 @@ fn should_forget_boundary_at_threshold() { let mut engine = ForgettingEngine::new(config); // Insert a memory into the strength map by processing it - let now_ts = chrono::Utc::now().timestamp() as u64; + let now_ts = time::OffsetDateTime::now_utc().unix_timestamp() as u64; let m = make_memory_with_timestamp("boundary", "at threshold", now_ts, 0.5); let (retained, _) = engine.process_forgetting(vec![m]).unwrap(); @@ -1147,7 +1147,7 @@ fn should_forget_boundary_at_max_age() { let mut engine = ForgettingEngine::new(config); // Memory timestamp exactly max_age seconds ago - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let ts_at_boundary = (now - max_age as i64) as u64; let m = make_memory_with_timestamp("age_boundary", "exactly at max age", ts_at_boundary, 0.5); let (retained, result) = engine.process_forgetting(vec![m]).unwrap(); @@ -1178,7 +1178,7 @@ fn strengthen_memory_adds_boost() { let mut engine = ForgettingEngine::new(config); // First populate the strength map - let now_ts = chrono::Utc::now().timestamp() as u64; + let now_ts = time::OffsetDateTime::now_utc().unix_timestamp() as u64; let m = make_memory_with_timestamp("boost_test", "memory to strengthen", now_ts, 0.5); engine.process_forgetting(vec![m]).unwrap(); @@ -1199,7 +1199,7 @@ fn strengthen_memory_adds_boost() { let mut engine2 = ForgettingEngine::new(config2); // Memory from 10 hours ago to ensure meaningful decay - let old_ts = (chrono::Utc::now().timestamp() - 36000) as u64; + let old_ts = (time::OffsetDateTime::now_utc().unix_timestamp() - 36000) as u64; let m2 = make_memory_with_timestamp("boost2", "decayed memory", old_ts, 0.0); engine2.process_forgetting(vec![m2]).unwrap(); @@ -1247,7 +1247,7 @@ fn statistics_weak_count_and_average_strength() { let mut engine = ForgettingEngine::new(config); // Populate with 3 memories (all retained since threshold=0.5 and strength=1.0) - let now_ts = chrono::Utc::now().timestamp() as u64; + let now_ts = time::OffsetDateTime::now_utc().unix_timestamp() as u64; let m1 = make_memory_with_timestamp("s1", "strong 1", now_ts, 0.5); let m2 = make_memory_with_timestamp("s2", "strong 2", now_ts, 0.5); let m3 = make_memory_with_timestamp("s3", "strong 3", now_ts, 0.5); @@ -1273,7 +1273,7 @@ fn statistics_weak_count_and_average_strength() { // Recent memory: strength ≈ 1.0 (above threshold) let m_recent = make_memory_with_timestamp("recent", "recent mem", now_ts, 0.0); // Old memory: decays to low strength (below threshold) - let old_ts = (chrono::Utc::now().timestamp() - 72000) as u64; // 20 hours ago + let old_ts = (time::OffsetDateTime::now_utc().unix_timestamp() - 72000) as u64; // 20 hours ago let m_old = make_memory_with_timestamp("old", "old mem", old_ts, 0.0); let (_retained, _) = engine2.process_forgetting(vec![m_recent, m_old]).unwrap(); diff --git a/crates/astraweave-persistence-player/Cargo.toml b/crates/astraweave-persistence-player/Cargo.toml index 2886f83fd1..325317f3fb 100644 --- a/crates/astraweave-persistence-player/Cargo.toml +++ b/crates/astraweave-persistence-player/Cargo.toml @@ -10,7 +10,7 @@ license = "MIT" serde = { version = "1.0", features = ["derive"] } toml = "0.8" anyhow = "1.0" -chrono = { version = "0.4", features = ["serde"] } +time = { version = "0.3", features = ["parsing"] } postcard = { version = "1.0", default-features = false, features = ["alloc"] } serde_bytes = "0.11" diff --git a/crates/astraweave-persistence-player/examples/save_slots_demo.rs b/crates/astraweave-persistence-player/examples/save_slots_demo.rs index 76da99568d..fd6bcb4549 100644 --- a/crates/astraweave-persistence-player/examples/save_slots_demo.rs +++ b/crates/astraweave-persistence-player/examples/save_slots_demo.rs @@ -88,7 +88,7 @@ fn main() { println!(" Playtime: {}h {}m", hours, minutes); println!( " Saved: {}", - slot.timestamp.format("%Y-%m-%d %H:%M:%S") + astraweave_persistence_player::format_utc_seconds(slot.timestamp) ); } diff --git a/crates/astraweave-persistence-player/src/lib.rs b/crates/astraweave-persistence-player/src/lib.rs index 28d90144f2..a87cbece2e 100644 --- a/crates/astraweave-persistence-player/src/lib.rs +++ b/crates/astraweave-persistence-player/src/lib.rs @@ -32,6 +32,9 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; +mod utc_stamp; +pub use utc_stamp::format_utc_seconds; + mod autosave; mod progression; mod save_slots; diff --git a/crates/astraweave-persistence-player/src/save_slots.rs b/crates/astraweave-persistence-player/src/save_slots.rs index 476d3f59f4..321c190fb2 100644 --- a/crates/astraweave-persistence-player/src/save_slots.rs +++ b/crates/astraweave-persistence-player/src/save_slots.rs @@ -1,7 +1,6 @@ //! Save slot management for multi-slot game saves use anyhow::{Context, Result}; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::fs; use std::path::PathBuf; @@ -100,7 +99,7 @@ impl SaveSlotManager { // Create metadata let metadata = SaveMetadata { slot_id, - timestamp: Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), playtime_seconds: player_profile.stats.playtime_seconds, level_name, character_name: player_profile.name.clone(), @@ -128,7 +127,11 @@ impl SaveSlotManager { // Write to disk fs::write(self.save_file_path(slot_id), save_data).context("Failed to write save file")?; - println!("💾 Saved game to slot {} ({})", slot_id, metadata.timestamp); + println!( + "💾 Saved game to slot {} ({})", + slot_id, + crate::utc_stamp::format_utc_display(metadata.timestamp) + ); Ok(()) } @@ -162,7 +165,8 @@ impl SaveSlotManager { println!( "📂 Loaded game from slot {} ({})", - slot_id, save_slot.metadata.timestamp + slot_id, + crate::utc_stamp::format_utc_display(save_slot.metadata.timestamp) ); Ok(save_slot) @@ -224,7 +228,8 @@ pub struct SaveMetadata { pub slot_id: usize, /// Save timestamp - pub timestamp: DateTime, + #[serde(with = "crate::utc_stamp::serde_rfc3339")] + pub timestamp: time::OffsetDateTime, /// Total playtime (seconds) pub playtime_seconds: u64, diff --git a/crates/astraweave-persistence-player/src/utc_stamp.rs b/crates/astraweave-persistence-player/src/utc_stamp.rs new file mode 100644 index 0000000000..6d7b57a21e --- /dev/null +++ b/crates/astraweave-persistence-player/src/utc_stamp.rs @@ -0,0 +1,396 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Negative years through `-9999` keep a +//! sign and four digits. A year outside `-9999..=9999` is rejected; `large-dates` +//! is not enabled. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. A negative year keeps a sign and four +/// digits. Values outside `-9999..=9999` are not stored. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub fn format_utc_seconds(dt: OffsetDateTime) -> String { + let utc = dt.to_offset(UtcOffset::UTC); + format!( + "{}-{:02}-{:02} {:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ) +} + +pub(crate) fn format_utc_display(dt: OffsetDateTime) -> String { + let utc = dt.to_offset(UtcOffset::UTC); + let mut out = format_utc_seconds(utc); + push_fraction(&mut out, utc.nanosecond()); + out.push_str(" UTC"); + out +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> Result { + let utc = dt + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year)?; + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + Ok(out) +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +fn invalid_year() -> time::error::Parse { + time::error::Parse::ParseFromDescription(time::error::ParseFromDescription::InvalidComponent( + "year", + )) +} + +pub(crate) fn parse_utc_rfc3339(text: &str) -> Result { + let rfc3339 = &time::format_description::well_known::Rfc3339; + if text.starts_with('+') || text.starts_with('-') { + parse_signed_year(text, rfc3339) + } else { + OffsetDateTime::parse(text, rfc3339).and_then(|dt| { + dt.checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) + }) + } +} + +/// A leading sign is outside `time`'s RFC 3339 year. The magnitude is at least +/// four digits. The remainder is parsed as year 2000 so a leap day survives, +/// then the result is stored as UTC. +fn parse_signed_year( + text: &str, + rfc3339: &time::format_description::well_known::Rfc3339, +) -> Result { + let negative = text.starts_with('-'); + let rest = &text[1..]; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + if digits < 4 { + return Err(invalid_year()); + } + let magnitude: i32 = rest[..digits].parse().map_err(|_| invalid_year())?; + let year = if negative { + magnitude.checked_neg().ok_or_else(invalid_year)? + } else { + magnitude + }; + let parsed = OffsetDateTime::parse(&format!("2000{}", &rest[digits..]), rfc3339)?; + let date = time::Date::from_calendar_date(year, parsed.month(), parsed.day()) + .map_err(|_| invalid_year())?; + OffsetDateTime::new_in_offset(date, parsed.time(), parsed.offset()) + .checked_to_offset(UtcOffset::UTC) + .ok_or_else(invalid_year) +} + +pub(crate) mod serde_rfc3339 { + use super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize(dt: &OffsetDateTime, serializer: S) -> Result { + let text = format_utc(*dt, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_str(&text) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result { + let text = String::deserialize(deserializer)?; + parse_utc_rfc3339(&text).map_err(serde::de::Error::custom) + } + + #[allow(dead_code)] + pub mod option { + use super::super::{format_utc, parse_utc_rfc3339}; + use serde::{Deserialize, Deserializer, Serializer}; + use time::OffsetDateTime; + + pub fn serialize( + dt: &Option, + serializer: S, + ) -> Result { + match dt { + Some(value) => { + let text = format_utc(*value, true).map_err(serde::ser::Error::custom)?; + serializer.serialize_some(&text) + } + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + let text = Option::::deserialize(deserializer)?; + text.map(|value| parse_utc_rfc3339(&value).map_err(serde::de::Error::custom)) + .transpose() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn fmt_utc(dt: OffsetDateTime, zulu: bool) -> String { + format_utc(dt, zulu).unwrap() + } + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(fmt_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + fmt_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!(fmt_utc(at(100_000_000), true), "2020-01-02T03:04:05.100Z"); + assert_eq!( + fmt_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(fmt_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + fmt_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(fmt_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!(fmt_utc(at(1), false), "2020-01-02T03:04:05.000000001+00:00"); + assert_eq!(fmt_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + fmt_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + fmt_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + fmt_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + fmt_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!(format_utc_seconds(at(123_456_789)), "2020-01-02 03:04:05"); + assert_eq!(format_utc_display(at(0)), "2020-01-02 03:04:05 UTC"); + assert_eq!( + format_utc_display(at(100_000_000)), + "2020-01-02 03:04:05.100 UTC" + ); + } + + #[test] + fn parsed_offsets_become_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T08:04:05+05:00").unwrap(), + true + ), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("2020-01-02T03:04:05.100Z").unwrap(), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000100+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.000100Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.000000001Z").unwrap(), + true + ), + "2020-01-02T03:04:05.000000001Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123400Z").unwrap(), + true + ), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("2020-01-02T03:04:05.123456789+00:00").unwrap(), + true + ), + "2020-01-02T03:04:05.123456789Z" + ); + } + + #[test] + fn toml_and_postcard_match_pinned_zulu_string() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Row { + #[serde(with = "super::serde_rfc3339")] + timestamp: OffsetDateTime, + } + let row = Row { + timestamp: at(100_000_000), + }; + assert_eq!( + toml::to_string(&row).unwrap(), + "timestamp = \"2020-01-02T03:04:05.100Z\"\n" + ); + assert_eq!( + postcard::to_allocvec(&row).unwrap(), + b"\x182020-01-02T03:04:05.100Z".to_vec() + ); + let whole = Row { timestamp: at(0) }; + assert_eq!( + postcard::to_allocvec(&whole).unwrap(), + b"\x142020-01-02T03:04:05Z".to_vec() + ); + let back: Row = toml::from_str("timestamp = \"2020-01-02T08:04:05+05:00\"\n").unwrap(); + assert_eq!(fmt_utc(back.timestamp, true), "2020-01-02T03:04:05Z"); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(fmt_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(fmt_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(fmt_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + assert_eq!(format_utc_seconds(civil(-1)), "-0001-01-02 03:04:05"); + assert_eq!(format_utc_display(civil(-1)), "-0001-01-02 03:04:05 UTC"); + } + + #[test] + fn signed_years_parse_back_to_utc() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0001-01-02T03:04:05Z").unwrap(), true), + "-0001-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc( + parse_utc_rfc3339("-0001-01-01T01:00:00+05:00").unwrap(), + true + ), + "-0002-12-31T20:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-01-02T03:04:05Z").unwrap(), true), + "2020-01-02T03:04:05Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+0000-01-02T03:04:05Z").unwrap(), true), + "0000-01-02T03:04:05Z" + ); + assert!(parse_utc_rfc3339("-001-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn option_timestamp_reads_a_present_string_null_and_omission() { + #[derive(serde::Serialize, serde::Deserialize)] + struct Opt { + #[serde(default, with = "super::serde_rfc3339::option")] + timestamp: Option, + } + let present: Opt = + serde_json::from_str("{\"timestamp\":\"2020-01-02T03:04:05Z\"}").unwrap(); + assert_eq!(present.timestamp, Some(at(0))); + let null: Opt = serde_json::from_str("{\"timestamp\":null}").unwrap(); + assert!(null.timestamp.is_none()); + let omitted: Opt = serde_json::from_str("{}").unwrap(); + assert!(omitted.timestamp.is_none()); + } + + #[test] + fn signed_leap_day_round_trips_and_a_non_leap_day_is_rejected() { + assert_eq!( + fmt_utc(parse_utc_rfc3339("-0004-02-29T00:00:00Z").unwrap(), true), + "-0004-02-29T00:00:00Z" + ); + assert_eq!( + fmt_utc(parse_utc_rfc3339("+2020-02-29T00:00:00Z").unwrap(), true), + "2020-02-29T00:00:00Z" + ); + assert!(parse_utc_rfc3339("-0001-02-29T00:00:00Z").is_err()); + } + + #[test] + fn years_outside_the_stored_range_are_rejected() { + assert!(parse_utc_rfc3339("+10000-01-02T03:04:05Z").is_err()); + assert!(parse_utc_rfc3339("-10000-01-02T03:04:05Z").is_err()); + } + + #[test] + fn out_of_range_offset_fails_closed() { + assert!(parse_utc_rfc3339("9999-12-31T23:59:59-01:00").is_err()); + let date = time::Date::from_calendar_date(9999, time::Month::December, 31).unwrap(); + let clock = time::Time::from_hms(23, 59, 59).unwrap(); + let offset = time::UtcOffset::from_hms(-1, 0, 0).unwrap(); + let dt = time::OffsetDateTime::new_in_offset(date, clock, offset); + assert!(format_utc(dt, true).is_err()); + assert!(format_utc(dt, false).is_err()); + } +} diff --git a/docs/architecture/ai_pipeline.md b/docs/architecture/ai_pipeline.md index 0e6a42442d..210f4d6557 100644 --- a/docs/architecture/ai_pipeline.md +++ b/docs/architecture/ai_pipeline.md @@ -8,8 +8,8 @@ domain: ai lifecycle_status: active integration_status: wired owns: [astraweave-ai, astraweave-behavior, astraweave-context, astraweave-coordination, astraweave-dialogue, astraweave-director, astraweave-embeddings, astraweave-llm, astraweave-memory, astraweave-npc, astraweave-persona, astraweave-prompts, astraweave-rag] -doc_version: "1.60" -last_verified_commit: ba187b0ccf37e431e16f5b17baf5e4a165e746f1 +doc_version: "1.61" +last_verified_commit: 3cb7e5f9cc993f802e58dcf016d32ad32a680a6c --- # Architecture Trace: AI Pipeline + AI Core + GOAP + Behavior Trees + LLM Integration + Arbiter @@ -20,11 +20,11 @@ last_verified_commit: ba187b0ccf37e431e16f5b17baf5e4a165e746f1 |---|---| | **System name** | AI Pipeline (Perception → Reasoning → Planning → Action) — foundational AI-first substrate | | **Primary crates** | `astraweave-ai` (39 files / 30.5K LoC), `astraweave-behavior` (6 / 5K), `astraweave-llm` (29 / 23.5K), `astraweave-memory` (17 / 11.5K), `astraweave-director` (6 / 3.3K), `astraweave-npc` (6 / 1.7K), `astraweave-dialogue` (4 / 5K), `astraweave-coordination` (5 / 5.3K) — **8 crates, 112 files, ~85K LoC total** | -| **Document version** | 1.60 | -| **Last verified against commit** | ba187b0ccf37e431e16f5b17baf5e4a165e746f1 | -| **Last verified date** | 2026-10-30 | +| **Document version** | 1.61 | +| **Last verified against commit** | 3cb7e5f9cc993f802e58dcf016d32ad32a680a6c | +| **Last verified date** | 2026-11-20 | | **Status** | **Active foundation — AI-first citizen of the engine.** The canonical loop is stable and validated for 12,700+ agents @ 60 FPS (per `astraweave-ai/src/lib.rs:27`). The Arbiter / dual-executor / LLM fallback chain has shipped multiple iterations and is hardening continuously. Subsystems like Memory, Director, NPC, Dialogue, Coordination are each large enough to warrant per-system follow-up traces. | -| **Owner notes** | 1.60 (2026-10-30): `TextPreprocessor::chunk_text` in `astraweave-embeddings/src/utils.rs` takes at least one scalar when `max_chunk_size` is smaller than the next character and always advances when overlap is near `max_chunk_size` on multibyte text (`byte_after_char` with `ceil_char_boundary` / `floor_char_boundary`). Regression tests cover overlap stall and CJK chunk boundaries. Verified at ba187b0ccf37e431e16f5b17baf5e4a165e746f1. 1.59 (2026-10-30): Char-safe byte caps extended to `astraweave-persona::llm_persona` (2048-byte cleaned response, CJK regression test) and `astraweave-embeddings::TextPreprocessor::preprocess` / `chunk_text` (8192-byte cap). Both depend on `astraweave-core::util::{byte_prefix,ceil_char_boundary,floor_char_boundary}`. `llm_adapter::truncate_prompt` regression test cuts at a non-boundary index. Verified at c56e2e78b0bc4bc947d04c98ec7d0fe0fd77f4ef. 1.58 (2026-10-30): Ollama assembled-response debug tail uses `byte_suffix`; `ollama_assembled_debug_snippets` has an `ollama`-feature regression test. Verified at `67e1a5616`. 1.57 (2026-10-30): Byte caps use `astraweave-core::util::{floor_char_boundary,byte_prefix,byte_suffix}` in `astraweave-prompts::truncate_input`, `astraweave-llm::plan_parser` (preview + `truncate`), `llm_adapter::truncate_prompt`, and Ollama assembled-response debug snippets in `lib.rs` (start via `byte_prefix`, end via `byte_suffix`). Slicing mid-scalar panics are removed. For `truncate_input`, limits 0–3 omit `"..."` so output length stays within the cap; larger limits keep the prior prefix-plus-ellipsis behavior. Verified at `67e1a5616`. 1.56 (2026-10-29): `sanitize_plan` bounds `MoveTo` and `Throw` coordinates with `unsigned_abs` against `MAX_COORD_BOUND` (100). `i32::MIN` and `i32::MAX` on x or y are dropped in debug and release. An in-bound step in the same plan stays. Verified at `f77da930`. 1.55 (2026-10-29): `default_tool_registry` names `MoveTo`, `Throw`, `CoverFire`, and `Revive`. `LlmOrchestrator::new` uses that registry when the caller passes none, and `make_system_orchestrator` passes it. A plan of those four steps validates. `validate_plan` returns an error for a step whose tool is not in the registry. `sanitize_plan` drops that step and returns `Ok`. Verified at `dde6b320`. 1.54 (2026-10-28): The schema cache key is length-prefixed. `steps` requires `minItems` 1. Enum tokens are lowercase, and `MoveTo` includes optional `speed`. A 400 retries without the schema only for an unsupported-format error, and that retry is logged. `/api/generate` after a chat 404 or 405 does the same retry. Batch tiers 1 and 2 send the schema when the registry names a tool. `validate_plan` returns an error for a step whose tool is not in the registry. `sanitize_plan` drops that step and returns `Ok`. Verified at `95084c1c`. 1.53 (2026-10-28): Tier 1 and Tier 2 send a JSON Schema built from the agent's tool registry as Ollama `format` when that registry names a tool. An empty registry does not send `format`. `parse_llm_plan` and `parse_llm_response` still reject an unregistered tool. `num_keep` stays `-1` and is the context-shift keep count. Verified at `f4a5c708`. 1.52 (2026-10-28): Corrected the silent-read wording. A silent Qwen thinking body in `complete_streaming` ends at `stream_read_idle` (180s by default), not at the 300s lifetime. The lifetime cuts a drip. A silent chat error body ends at 120s. Verified at `75486dcf`. 1.51 (2026-10-28): A non-success body in `OllamaChatClient::complete`, including the `/api/generate` fallback, and the thinking JSON body in `Qwen3Ollama::complete_streaming` stop at the time still left in the stream lifetime or at 64 KiB, whichever comes first. A withheld error body ends at that lifetime instead of the default 180s idle. `OLLAMA_STREAM_LIFETIME_MS` can only shorten those reads. Verified at `65e0fb3c`. 1.50 (2026-10-28): Each header wait is the idle limit or the time still left in the stream lifetime, whichever is shorter. A success-path body on the default chat stream, Hermes streaming, and `examples/ollama_probe` ends at 120s from the request start. Qwen's non-thinking scan ends at 300s, including when `OLLAMA_TIMEOUT_SECS` is longer than 300s. `OLLAMA_STREAM_LIFETIME_MS` can only shorten those header waits and success-path scans. A non-success body and Qwen's thinking JSON read still follow the client read timeout. A lifetime or idle error after at least one token returns those tokens from `OllamaChatClient::complete`. The error is returned only when the stream produced none. `with_read_idle` is removed. Verified at `94e91971`. 1.49 (2026-10-28): Silence on a streaming body stops after one idle period. A longer gap ceiling does not extend that wait. A non-empty chunk starts a new gap. An empty chunk does not. `OllamaChatClient::complete`, Hermes streaming, and `examples/ollama_probe` stop at 120s from the request start. Qwen streaming stops at 300s. Lines already buffered are parsed without checking the clock. The 1 MiB raw budget and the 64 KiB content cap are unchanged. Verified at `fa97d5fa`. 1.48 (2026-10-27): The `CAiController` example imports `htn::GatherGoal`. The parent `99382af7` names `GatherGoal` with no import, so `cargo test -p astraweave-ai --all-features --doc` fails and cargo-mutants records zero mutants. 1.47 (2026-10-25): The slow-chunk probe sets `TCP_NODELAY`. macOS delayed ACK was holding each 50 ms chunk, so the 4 s overall cap stopped the read around token 30. The cap is unchanged. Verified at `b06a106b`. 1.46 (2026-10-23): Every return from `OllamaChatClient::complete` is capped at 64 KiB, including a body with no newline and early exit. Exactly 64 KiB is kept. Newlines are drained in one pass, and that pass checks the overall deadline. The probe decodes UTF-8 on complete lines. Verified at `76e3ab28`. 1.45 (2026-10-23): Raw NDJSON counts toward a 1 MiB stream budget. Extracted content stays at 64 KiB. A bad NDJSON line keeps earlier lines in that slice and drops the lines after it. Embedding index checks decode the JSON body. Verified at `cf5fa478`. 1.44 (2026-10-23): Qwen and Hermes scans wait only the time still left and end after one error. Lines are split before the UTF-8 check. A bad line in the default chat stream keeps tokens already read. `done: true` ends those scans. An embedding row is placed at its index. Verified at `c9e45bd4`. 1.43 (2026-10-23): Thinking mode and `embed_batch` have an overall deadline. Qwen and Hermes streams stop at twice the idle timeout. A non-UTF-8 NDJSON line is an error. `embed_batch` requires one row per input. Verified at `f486032c`. 1.42 (2026-10-23): Qwen complete is 300s overall. Qwen preload and chat, Hermes chat and complete, and Phi-3 complete are 120s overall. The default chat stream keeps split UTF-8 and partial tokens and stops at twice the idle timeout. Embedding reads clamp to 8 MiB and refuse a saturated limit. Verified at `e9c404a3`. 1.41 (2026-10-22): The chat stream counts every received byte. `embed_batch` caps from batch length times dimensions. Warmup, non-stream attempts, and the tags probe keep an overall deadline. `send_for_headers` keeps the reqwest error. Verified at `5586a744`. 1.40 (2026-10-22): Model `.text()` and `.json()` reads stop at 64 KiB. `send_for_headers` had copied the reqwest error into a string. Verified at `a336b808`. 1.39 (2026-10-22): A readable non-streaming error status is returned and does not start the streaming POST. Error bodies and batch text stop at 64 KiB. `with_read_idle` keeps the reqwest source. Verified at `74d5beda`. 1.38 (2026-10-22): Same tree as 1.37, restamped after the rebase onto `c1714ff7`. Verified at `5fb72a77`. 1.37 (2026-10-22): A stalled 200 body on `OllamaChatClient::complete` returns the read error and keeps the reqwest source, including when `OLLAMA_LOW_LATENCY` is off. `warmup` returns that error. Verified at `8938318f`. 1.36 (2026-10-22): `Qwen3Ollama::preload` and the non-streaming chat error path return the body read error and keep the reqwest source. A failed batch chunk keeps text already received. Thinking mode uses `ReadTimeoutBody`, not `with_read_idle`. Verified at `bcd10bf7`. 1.35 (2026-10-22): `OllamaChatClient::complete` returns a failed `.text()` on the chat error status and on `/api/generate`. Verified at `2ed752bb`. 1.34 (2026-10-22): `build_model_client` sets `read_timeout` from `OLLAMA_TIMEOUT_SECS`. A failed `.text()` on the HTTP error path and on `/api/generate` is returned. `.json()` uses that same per-read bound. 1.33 (2026-10-22): Header waits use `send_for_headers`. That wait does not cover a later `.text()` or `.json()`. Verified at `03482d11`. 1.32 (2026-10-22): Streaming reads use a per-read idle timeout, not a total reqwest deadline. A body error stops the loop and keeps tokens already read. Verified at `c240dd3d`. 1.31 (2026-10-22): The closed-port probe tests live in `tests/ollama_chat_probe.rs`. Windows archive partitions skip that target and `loopback_http_proxy`. Verified at `ad4a956a`. 1.30 (2026-10-22): A constructor that would rewrite the URL returns `Err` and does not store a bearer token. Verified at `ff97fa17`. 1.29 (2026-10-22): `loopback_model_url` docs say userinfo is always replaced. The closed-port chat tests spawn `ollama_chat_probe`. Verified at `2221569e`. 1.28 (2026-10-22): Userinfo is rejected before `allow_remote` returns the URL. `RemoteEmbeddingClient::assemble` errors on userinfo. The model `url` is private and `ensure_model_request` re-checks the first hop. The proxy test is a subprocess. Verified at `18c28563`. 1.27 (2026-10-22): `localhost` is a literal name pinned to `127.0.0.1`. `build_model_client` returns the build error. Verified at `8b497b7d`. 1.26 (2026-10-22): `loopback_http_client` disables proxy env and follows only loopback redirects. `localhost` is pinned to `127.0.0.1`. `allowing_remote` keeps a remote URL on reqwest's default client. 1.25 (2026-10-22): `is_loopback_http_url` is the shared parsed check. Direct Ollama HTTP callers use `loopback_model_url`. 1.24 (2026-10-22): `loopback_model_url` parses with the `url` crate. Userinfo is rejected. A host is kept only for `127.0.0.0/8`, `::1`, or `localhost`. 1.23 (2026-10-20): The `ai_planning` tick stops at `RuleOrchestrator`. `dispatch_planner` and Stage L are separate callers. 1.22 (2026-10-20): `sys_ai_planning` always boxes `RuleOrchestrator` and does not call `dispatch_planner`. The four paths in §2.6 do not call each other. 1.21 (2026-10-20): `PlannerMode::GOAP` calls `htn::gather_method(controller.gather)` only when `ai-goap` is on. The snapshot is unused. `GoapPlanner::plan` is not that path. `PlannerMode::Htn` is always available and calls `HtnOrchestrator::propose_plan`. 1.20 (2026-10-18): With `ai-goap` on, `PlannerMode::GOAP` calls `htn::gather_method` with an explicit `GatherGoal` and does not scan the policy string. The default build leaves `ai-goap` off and returns an error instead of reading `gather`. `GoapOrchestrator` delegates to `legacy_goap_plan`. `AIArbiter` compiles only with `llm_orchestrator`. `astraweave-ai/src/goap` compiles only with `planner_advanced`. `astraweave-behavior` `GoapPlanner` is not feature-gated. None of them is on `sys_ai_planning`. 1.19 (2026-10-16): `sys_ai_planning` stays on `RuleOrchestrator` when `veilweaver_slice` is unified in. 1.18 (2026-10-16): dialogue prompts use `set_path` so `speaker.*` and `player_emotion.*` nest. Conversation metadata stores `started_turn` and `last_turn`. Each conversation is a mutex held for the whole `generate_response` step. 1.17 (2026-10-16): `recorded_line` has no non-test caller. 1.16 (2026-10-16): deletion follow-ups are #334 (`AIArbiter`) and #335 (`GoapPlanner`). 1.15 (2026-10-16): `llm_dialogue` compiles. `recorded_line` is the sim boundary (seeded, not drawn). `AIArbiter`, `GoapPlanner`, and `generate_response` stay off `sys_spatial_tick` / `sys_ai_planning`. 1.14 (2026-10-15): `OllamaClient::new` rewrites a non-loopback URL to `http://127.0.0.1:11434` unless `allowing_remote` is used. 1.13 (2026-10-15): `OllamaClient::complete` no longer prints the prompt or the raw response. `Qwen3Ollama`, `Phi3Ollama`, `Hermes2ProOllama`, and `OllamaChatClient` keep loopback URLs unless `allowing_remote` is used. Quest and world-event model text uses `parse_bounded_model_json` (64 KiB). Persona zips cap entry count, uncompressed size, and the manifest read. This trace is a **navigational map + load-bearing detail**, not an exhaustive per-file enumeration. Scale: 85K LoC across 8 crates. The canonical loop (`astraweave-ai/src/core_loop.rs` + `orchestrator.rs` + `tool_sandbox.rs` + `ai_arbiter.rs` + `llm_executor.rs` + `astraweave-behavior/src/goap.rs` + `astraweave-llm/src/{plan_parser,fallback_system,tool_guard,production_hardening}.rs`) is documented in detail. **Subsystem trace for Memory added 2026-05-12 (see §13.1)** — surfaced dormancy of the main memory pipeline w.r.t. the runtime AI loop. **Subsystem trace for Director added 2026-05-12 (see §13.2)** — confirmed Director is a parallel sibling AI subsystem (boss/encounter authoring) with its own validation gate `apply_director_plan`; the Companion-AI loop and Director loop share `WorldSnapshot` but otherwise do not interact. **Subsystem trace for NPC added 2026-05-12 (see §13.3)** — confirmed NPC is a fully isolated AI subsystem with its own parallel vocabulary (`NpcAction`/`NpcPlan`/`NpcWorldView`/`LlmAdapter`/`CommandSink`), zero imports of canonical AI types, and direct physics/audio integration rather than ECS-loop participation. **Subsystem trace for Dialogue added 2026-05-12 (see §13.4)** — confirmed Dialogue has a **two-layer architecture**: the basic `DialogueGraph`/`DialogueRunner`/`toml_loader` path is actively production-wired into `veilweaver_slice_runtime` and the editor; the LLM-enhanced `llm_dialogue.rs` (2941 LoC / 60% of crate) is dormant with zero external consumers. **Subsystem trace for Coordination added 2026-05-12 (see §13.5)** — most aggressively dormant subsystem traced: zero workspace consumers of any kind (no examples, no tools, no game-loop crates), explicit `#[allow(dead_code)]` "reserved for future…" markers on 7+ struct/field locations, three commented-out module declarations whose source files were never created. The entire `AgentCoordinator`/`WorldEventGenerator`/`NarrativeCoherenceEngine` surface is in-design. **Subsystem trace for Advanced GOAP added 2026-05-12 (see §13.6)** — largest subsystem traced (22 files / 16.7K LoC) and most architecturally mature among the dormant subsystems: feature-gated on `planner_advanced`, structured across 6 phases (0-5) of explicit phase-numbered development, integrates with the canonical loop via the `Orchestrator` trait, includes built-in shadow-mode infrastructure for safe rollout, but currently has zero production constructors outside tests/benches and three disabled CLI bins. **Subsystem trace for LLM Production Hardening added 2026-05-12 (see §13.7)** — second-deepest LoC dormancy reservoir at ~15K LoC across 16 files. Confirmed only one primitive (`parse_llm_response`) is actively wired in production (via `FallbackOrchestrator` Tier-1/Tier-2), but `FallbackOrchestrator::new` itself is doc-comment-only with zero non-test constructors. The runtime `AIArbiter`/`LlmExecutor` path bypasses the entire hardening surface — no rate limiting, no circuit breaking, no backpressure, no A/B routing, no retry, no telemetry, no ToolGuard, no 4-tier fallback. The 4096-char prompt limit and `safe_llm_invoke` stub are unreachable code. **Subsystem trace for RAG added 2026-05-12 (see §13.8)** — closes the original §11 follow-up list. Three-crate stack (`astraweave-rag` + `astraweave-embeddings` + `astraweave-context`, ~12.3K LoC total). Foundation primitives are active (`TokenCounter::new` is the most actively-wired primitive — instantiated by `RagPipeline::new` AND `ConversationHistory::new`), but the `RagPipeline` composite is dormant for the runtime AI loop: held as a field in 5 LLM-enhanced consumer crates (Director, Quests, Persona, Dialogue, Coordination), all of which are themselves dormant per §13.2/§13.4/§13.5. Surfaced two parallel-implementation anti-patterns (matching the CLAUDE.md "Architecture Drift" warning): (a) a SECOND orphaned `RagPipeline` struct in `astraweave-ai/src/rag/pipeline.rs:115` that never compiles because `pub mod rag` is not declared in lib.rs; (b) internal `astraweave-rag` crate duplication of `InjectionConfig` + `InjectionResult` types (different field sets, same names, two modules). Also surfaced "vocabulary-only" enum drift: `RetrievalMethod` 4 unused variants, `DiversityStrategy` 4 unused variants, `InjectionStrategy` 4 unused variants, plus `VectorStoreWrapper::get_all_memories` returns empty Vec making consolidation a no-op, plus HNSW indexing advertised but linear-scan implemented. **All originally enumerated per-subsystem follow-up traces are now complete.** **Verification pass 2026-05-12 (version 1.9):** resolved 22 markers across §1 / §3 / §5 / §6 / §8 / §10 / §11 / §13.2 / §13.3 / §13.4 / §13.5 / §13.6 / §13.7 / §13.8 with file:line evidence. Three factual corrections surfaced: (a) `GOAPOrchestrator` (Advanced GOAP) does NOT implement the `Orchestrator` trait despite earlier trace claim; (b) `plan_to_intent` emits `tracing::warn!` on unknown actions (not silent drop as previously hedged); (c) `BatchInferenceExecutor` IS actively wired via `FallbackOrchestrator` (not "[NEEDS VERIFICATION]"). One bug-class confirmation: `ProductionHardeningLayer` has no `Drop` impl, confirming runtime resource leak risk without explicit `shutdown().await`. **Deep investigation pass 2026-05-12 (version 1.10):** closed 2 factual §11 Open Questions (`*_stub` grep result, `AIArbiter` non-Send violation check) by moving resolutions into §8 Invariants 19 and 20. Enriched 4 decisional §11 questions with deeper factual context: `AIControlMode` vs `PlannerMode` (variant-set diff), Hermes2Pro/Qwen3/Phi3 (3-client coexistence + phi3:medium runtime default contradiction), `astraweave-ai` forbid_unsafe (grep verified absent crate-wide), `VectorStoreWrapper` consolidation no-op (verified no test catches the bug). Surfaced one new cognitive trap in §6: runtime LLM default is phi3:medium despite doc-comment Qwen3 claims. **Verification pass 2026-05-12 (version 1.11):** resolved 5 additional markers in §7 (Interner test isolation — no `serial_test` in astraweave-behavior), §13.2 (Director context/prompts deps enrichment), §13.3 (`PhysicsWorld::control_character` confirmed to use dt internally), §13.4 (D12 LlmDialogueSystem Send+Sync fields audited, TOML speaker field NOT retained, RunnerState Idle/Finished externally observable only via `is_finished()`). Verified git log searches for "Phase 7" + "WorldState" + "fallback" returned no relevant AI-pipeline commits — §7 Decision Log "[Reasoning not recovered]" markers remain unrecoverable per Default 3 (honest acknowledgment of missing rationale). | +| **Owner notes** | 1.61 (2026-11-20): A temporal window in `[0, 1)` hour is a 0-second duration. Memories from the same instant still link, and `add_association` stores a finite strength (ratio 0, then the usual clamp). Verified at 3cb7e5f9cc993f802e58dcf016d32ad32a680a6c. 1.60 (2026-10-30): `TextPreprocessor::chunk_text` in `astraweave-embeddings/src/utils.rs` takes at least one scalar when `max_chunk_size` is smaller than the next character and always advances when overlap is near `max_chunk_size` on multibyte text (`byte_after_char` with `ceil_char_boundary` / `floor_char_boundary`). Regression tests cover overlap stall and CJK chunk boundaries. Verified at ba187b0ccf37e431e16f5b17baf5e4a165e746f1. 1.59 (2026-10-30): Char-safe byte caps extended to `astraweave-persona::llm_persona` (2048-byte cleaned response, CJK regression test) and `astraweave-embeddings::TextPreprocessor::preprocess` / `chunk_text` (8192-byte cap). Both depend on `astraweave-core::util::{byte_prefix,ceil_char_boundary,floor_char_boundary}`. `llm_adapter::truncate_prompt` regression test cuts at a non-boundary index. Verified at c56e2e78b0bc4bc947d04c98ec7d0fe0fd77f4ef. 1.58 (2026-10-30): Ollama assembled-response debug tail uses `byte_suffix`; `ollama_assembled_debug_snippets` has an `ollama`-feature regression test. Verified at `67e1a5616`. 1.57 (2026-10-30): Byte caps use `astraweave-core::util::{floor_char_boundary,byte_prefix,byte_suffix}` in `astraweave-prompts::truncate_input`, `astraweave-llm::plan_parser` (preview + `truncate`), `llm_adapter::truncate_prompt`, and Ollama assembled-response debug snippets in `lib.rs` (start via `byte_prefix`, end via `byte_suffix`). Slicing mid-scalar panics are removed. For `truncate_input`, limits 0–3 omit `"..."` so output length stays within the cap; larger limits keep the prior prefix-plus-ellipsis behavior. Verified at `67e1a5616`. 1.56 (2026-10-29): `sanitize_plan` bounds `MoveTo` and `Throw` coordinates with `unsigned_abs` against `MAX_COORD_BOUND` (100). `i32::MIN` and `i32::MAX` on x or y are dropped in debug and release. An in-bound step in the same plan stays. Verified at `f77da930`. 1.55 (2026-10-29): `default_tool_registry` names `MoveTo`, `Throw`, `CoverFire`, and `Revive`. `LlmOrchestrator::new` uses that registry when the caller passes none, and `make_system_orchestrator` passes it. A plan of those four steps validates. `validate_plan` returns an error for a step whose tool is not in the registry. `sanitize_plan` drops that step and returns `Ok`. Verified at `dde6b320`. 1.54 (2026-10-28): The schema cache key is length-prefixed. `steps` requires `minItems` 1. Enum tokens are lowercase, and `MoveTo` includes optional `speed`. A 400 retries without the schema only for an unsupported-format error, and that retry is logged. `/api/generate` after a chat 404 or 405 does the same retry. Batch tiers 1 and 2 send the schema when the registry names a tool. `validate_plan` returns an error for a step whose tool is not in the registry. `sanitize_plan` drops that step and returns `Ok`. Verified at `95084c1c`. 1.53 (2026-10-28): Tier 1 and Tier 2 send a JSON Schema built from the agent's tool registry as Ollama `format` when that registry names a tool. An empty registry does not send `format`. `parse_llm_plan` and `parse_llm_response` still reject an unregistered tool. `num_keep` stays `-1` and is the context-shift keep count. Verified at `f4a5c708`. 1.52 (2026-10-28): Corrected the silent-read wording. A silent Qwen thinking body in `complete_streaming` ends at `stream_read_idle` (180s by default), not at the 300s lifetime. The lifetime cuts a drip. A silent chat error body ends at 120s. Verified at `75486dcf`. 1.51 (2026-10-28): A non-success body in `OllamaChatClient::complete`, including the `/api/generate` fallback, and the thinking JSON body in `Qwen3Ollama::complete_streaming` stop at the time still left in the stream lifetime or at 64 KiB, whichever comes first. A withheld error body ends at that lifetime instead of the default 180s idle. `OLLAMA_STREAM_LIFETIME_MS` can only shorten those reads. Verified at `65e0fb3c`. 1.50 (2026-10-28): Each header wait is the idle limit or the time still left in the stream lifetime, whichever is shorter. A success-path body on the default chat stream, Hermes streaming, and `examples/ollama_probe` ends at 120s from the request start. Qwen's non-thinking scan ends at 300s, including when `OLLAMA_TIMEOUT_SECS` is longer than 300s. `OLLAMA_STREAM_LIFETIME_MS` can only shorten those header waits and success-path scans. A non-success body and Qwen's thinking JSON read still follow the client read timeout. A lifetime or idle error after at least one token returns those tokens from `OllamaChatClient::complete`. The error is returned only when the stream produced none. `with_read_idle` is removed. Verified at `94e91971`. 1.49 (2026-10-28): Silence on a streaming body stops after one idle period. A longer gap ceiling does not extend that wait. A non-empty chunk starts a new gap. An empty chunk does not. `OllamaChatClient::complete`, Hermes streaming, and `examples/ollama_probe` stop at 120s from the request start. Qwen streaming stops at 300s. Lines already buffered are parsed without checking the clock. The 1 MiB raw budget and the 64 KiB content cap are unchanged. Verified at `fa97d5fa`. 1.48 (2026-10-27): The `CAiController` example imports `htn::GatherGoal`. The parent `99382af7` names `GatherGoal` with no import, so `cargo test -p astraweave-ai --all-features --doc` fails and cargo-mutants records zero mutants. 1.47 (2026-10-25): The slow-chunk probe sets `TCP_NODELAY`. macOS delayed ACK was holding each 50 ms chunk, so the 4 s overall cap stopped the read around token 30. The cap is unchanged. Verified at `b06a106b`. 1.46 (2026-10-23): Every return from `OllamaChatClient::complete` is capped at 64 KiB, including a body with no newline and early exit. Exactly 64 KiB is kept. Newlines are drained in one pass, and that pass checks the overall deadline. The probe decodes UTF-8 on complete lines. Verified at `76e3ab28`. 1.45 (2026-10-23): Raw NDJSON counts toward a 1 MiB stream budget. Extracted content stays at 64 KiB. A bad NDJSON line keeps earlier lines in that slice and drops the lines after it. Embedding index checks decode the JSON body. Verified at `cf5fa478`. 1.44 (2026-10-23): Qwen and Hermes scans wait only the time still left and end after one error. Lines are split before the UTF-8 check. A bad line in the default chat stream keeps tokens already read. `done: true` ends those scans. An embedding row is placed at its index. Verified at `c9e45bd4`. 1.43 (2026-10-23): Thinking mode and `embed_batch` have an overall deadline. Qwen and Hermes streams stop at twice the idle timeout. A non-UTF-8 NDJSON line is an error. `embed_batch` requires one row per input. Verified at `f486032c`. 1.42 (2026-10-23): Qwen complete is 300s overall. Qwen preload and chat, Hermes chat and complete, and Phi-3 complete are 120s overall. The default chat stream keeps split UTF-8 and partial tokens and stops at twice the idle timeout. Embedding reads clamp to 8 MiB and refuse a saturated limit. Verified at `e9c404a3`. 1.41 (2026-10-22): The chat stream counts every received byte. `embed_batch` caps from batch length times dimensions. Warmup, non-stream attempts, and the tags probe keep an overall deadline. `send_for_headers` keeps the reqwest error. Verified at `5586a744`. 1.40 (2026-10-22): Model `.text()` and `.json()` reads stop at 64 KiB. `send_for_headers` had copied the reqwest error into a string. Verified at `a336b808`. 1.39 (2026-10-22): A readable non-streaming error status is returned and does not start the streaming POST. Error bodies and batch text stop at 64 KiB. `with_read_idle` keeps the reqwest source. Verified at `74d5beda`. 1.38 (2026-10-22): Same tree as 1.37, restamped after the rebase onto `c1714ff7`. Verified at `5fb72a77`. 1.37 (2026-10-22): A stalled 200 body on `OllamaChatClient::complete` returns the read error and keeps the reqwest source, including when `OLLAMA_LOW_LATENCY` is off. `warmup` returns that error. Verified at `8938318f`. 1.36 (2026-10-22): `Qwen3Ollama::preload` and the non-streaming chat error path return the body read error and keep the reqwest source. A failed batch chunk keeps text already received. Thinking mode uses `ReadTimeoutBody`, not `with_read_idle`. Verified at `bcd10bf7`. 1.35 (2026-10-22): `OllamaChatClient::complete` returns a failed `.text()` on the chat error status and on `/api/generate`. Verified at `2ed752bb`. 1.34 (2026-10-22): `build_model_client` sets `read_timeout` from `OLLAMA_TIMEOUT_SECS`. A failed `.text()` on the HTTP error path and on `/api/generate` is returned. `.json()` uses that same per-read bound. 1.33 (2026-10-22): Header waits use `send_for_headers`. That wait does not cover a later `.text()` or `.json()`. Verified at `03482d11`. 1.32 (2026-10-22): Streaming reads use a per-read idle timeout, not a total reqwest deadline. A body error stops the loop and keeps tokens already read. Verified at `c240dd3d`. 1.31 (2026-10-22): The closed-port probe tests live in `tests/ollama_chat_probe.rs`. Windows archive partitions skip that target and `loopback_http_proxy`. Verified at `ad4a956a`. 1.30 (2026-10-22): A constructor that would rewrite the URL returns `Err` and does not store a bearer token. Verified at `ff97fa17`. 1.29 (2026-10-22): `loopback_model_url` docs say userinfo is always replaced. The closed-port chat tests spawn `ollama_chat_probe`. Verified at `2221569e`. 1.28 (2026-10-22): Userinfo is rejected before `allow_remote` returns the URL. `RemoteEmbeddingClient::assemble` errors on userinfo. The model `url` is private and `ensure_model_request` re-checks the first hop. The proxy test is a subprocess. Verified at `18c28563`. 1.27 (2026-10-22): `localhost` is a literal name pinned to `127.0.0.1`. `build_model_client` returns the build error. Verified at `8b497b7d`. 1.26 (2026-10-22): `loopback_http_client` disables proxy env and follows only loopback redirects. `localhost` is pinned to `127.0.0.1`. `allowing_remote` keeps a remote URL on reqwest's default client. 1.25 (2026-10-22): `is_loopback_http_url` is the shared parsed check. Direct Ollama HTTP callers use `loopback_model_url`. 1.24 (2026-10-22): `loopback_model_url` parses with the `url` crate. Userinfo is rejected. A host is kept only for `127.0.0.0/8`, `::1`, or `localhost`. 1.23 (2026-10-20): The `ai_planning` tick stops at `RuleOrchestrator`. `dispatch_planner` and Stage L are separate callers. 1.22 (2026-10-20): `sys_ai_planning` always boxes `RuleOrchestrator` and does not call `dispatch_planner`. The four paths in §2.6 do not call each other. 1.21 (2026-10-20): `PlannerMode::GOAP` calls `htn::gather_method(controller.gather)` only when `ai-goap` is on. The snapshot is unused. `GoapPlanner::plan` is not that path. `PlannerMode::Htn` is always available and calls `HtnOrchestrator::propose_plan`. 1.20 (2026-10-18): With `ai-goap` on, `PlannerMode::GOAP` calls `htn::gather_method` with an explicit `GatherGoal` and does not scan the policy string. The default build leaves `ai-goap` off and returns an error instead of reading `gather`. `GoapOrchestrator` delegates to `legacy_goap_plan`. `AIArbiter` compiles only with `llm_orchestrator`. `astraweave-ai/src/goap` compiles only with `planner_advanced`. `astraweave-behavior` `GoapPlanner` is not feature-gated. None of them is on `sys_ai_planning`. 1.19 (2026-10-16): `sys_ai_planning` stays on `RuleOrchestrator` when `veilweaver_slice` is unified in. 1.18 (2026-10-16): dialogue prompts use `set_path` so `speaker.*` and `player_emotion.*` nest. Conversation metadata stores `started_turn` and `last_turn`. Each conversation is a mutex held for the whole `generate_response` step. 1.17 (2026-10-16): `recorded_line` has no non-test caller. 1.16 (2026-10-16): deletion follow-ups are #334 (`AIArbiter`) and #335 (`GoapPlanner`). 1.15 (2026-10-16): `llm_dialogue` compiles. `recorded_line` is the sim boundary (seeded, not drawn). `AIArbiter`, `GoapPlanner`, and `generate_response` stay off `sys_spatial_tick` / `sys_ai_planning`. 1.14 (2026-10-15): `OllamaClient::new` rewrites a non-loopback URL to `http://127.0.0.1:11434` unless `allowing_remote` is used. 1.13 (2026-10-15): `OllamaClient::complete` no longer prints the prompt or the raw response. `Qwen3Ollama`, `Phi3Ollama`, `Hermes2ProOllama`, and `OllamaChatClient` keep loopback URLs unless `allowing_remote` is used. Quest and world-event model text uses `parse_bounded_model_json` (64 KiB). Persona zips cap entry count, uncompressed size, and the manifest read. This trace is a **navigational map + load-bearing detail**, not an exhaustive per-file enumeration. Scale: 85K LoC across 8 crates. The canonical loop (`astraweave-ai/src/core_loop.rs` + `orchestrator.rs` + `tool_sandbox.rs` + `ai_arbiter.rs` + `llm_executor.rs` + `astraweave-behavior/src/goap.rs` + `astraweave-llm/src/{plan_parser,fallback_system,tool_guard,production_hardening}.rs`) is documented in detail. **Subsystem trace for Memory added 2026-05-12 (see §13.1)** — surfaced dormancy of the main memory pipeline w.r.t. the runtime AI loop. **Subsystem trace for Director added 2026-05-12 (see §13.2)** — confirmed Director is a parallel sibling AI subsystem (boss/encounter authoring) with its own validation gate `apply_director_plan`; the Companion-AI loop and Director loop share `WorldSnapshot` but otherwise do not interact. **Subsystem trace for NPC added 2026-05-12 (see §13.3)** — confirmed NPC is a fully isolated AI subsystem with its own parallel vocabulary (`NpcAction`/`NpcPlan`/`NpcWorldView`/`LlmAdapter`/`CommandSink`), zero imports of canonical AI types, and direct physics/audio integration rather than ECS-loop participation. **Subsystem trace for Dialogue added 2026-05-12 (see §13.4)** — confirmed Dialogue has a **two-layer architecture**: the basic `DialogueGraph`/`DialogueRunner`/`toml_loader` path is actively production-wired into `veilweaver_slice_runtime` and the editor; the LLM-enhanced `llm_dialogue.rs` (2941 LoC / 60% of crate) is dormant with zero external consumers. **Subsystem trace for Coordination added 2026-05-12 (see §13.5)** — most aggressively dormant subsystem traced: zero workspace consumers of any kind (no examples, no tools, no game-loop crates), explicit `#[allow(dead_code)]` "reserved for future…" markers on 7+ struct/field locations, three commented-out module declarations whose source files were never created. The entire `AgentCoordinator`/`WorldEventGenerator`/`NarrativeCoherenceEngine` surface is in-design. **Subsystem trace for Advanced GOAP added 2026-05-12 (see §13.6)** — largest subsystem traced (22 files / 16.7K LoC) and most architecturally mature among the dormant subsystems: feature-gated on `planner_advanced`, structured across 6 phases (0-5) of explicit phase-numbered development, integrates with the canonical loop via the `Orchestrator` trait, includes built-in shadow-mode infrastructure for safe rollout, but currently has zero production constructors outside tests/benches and three disabled CLI bins. **Subsystem trace for LLM Production Hardening added 2026-05-12 (see §13.7)** — second-deepest LoC dormancy reservoir at ~15K LoC across 16 files. Confirmed only one primitive (`parse_llm_response`) is actively wired in production (via `FallbackOrchestrator` Tier-1/Tier-2), but `FallbackOrchestrator::new` itself is doc-comment-only with zero non-test constructors. The runtime `AIArbiter`/`LlmExecutor` path bypasses the entire hardening surface — no rate limiting, no circuit breaking, no backpressure, no A/B routing, no retry, no telemetry, no ToolGuard, no 4-tier fallback. The 4096-char prompt limit and `safe_llm_invoke` stub are unreachable code. **Subsystem trace for RAG added 2026-05-12 (see §13.8)** — closes the original §11 follow-up list. Three-crate stack (`astraweave-rag` + `astraweave-embeddings` + `astraweave-context`, ~12.3K LoC total). Foundation primitives are active (`TokenCounter::new` is the most actively-wired primitive — instantiated by `RagPipeline::new` AND `ConversationHistory::new`), but the `RagPipeline` composite is dormant for the runtime AI loop: held as a field in 5 LLM-enhanced consumer crates (Director, Quests, Persona, Dialogue, Coordination), all of which are themselves dormant per §13.2/§13.4/§13.5. Surfaced two parallel-implementation anti-patterns (matching the CLAUDE.md "Architecture Drift" warning): (a) a SECOND orphaned `RagPipeline` struct in `astraweave-ai/src/rag/pipeline.rs:115` that never compiles because `pub mod rag` is not declared in lib.rs; (b) internal `astraweave-rag` crate duplication of `InjectionConfig` + `InjectionResult` types (different field sets, same names, two modules). Also surfaced "vocabulary-only" enum drift: `RetrievalMethod` 4 unused variants, `DiversityStrategy` 4 unused variants, `InjectionStrategy` 4 unused variants, plus `VectorStoreWrapper::get_all_memories` returns empty Vec making consolidation a no-op, plus HNSW indexing advertised but linear-scan implemented. **All originally enumerated per-subsystem follow-up traces are now complete.** **Verification pass 2026-05-12 (version 1.9):** resolved 22 markers across §1 / §3 / §5 / §6 / §8 / §10 / §11 / §13.2 / §13.3 / §13.4 / §13.5 / §13.6 / §13.7 / §13.8 with file:line evidence. Three factual corrections surfaced: (a) `GOAPOrchestrator` (Advanced GOAP) does NOT implement the `Orchestrator` trait despite earlier trace claim; (b) `plan_to_intent` emits `tracing::warn!` on unknown actions (not silent drop as previously hedged); (c) `BatchInferenceExecutor` IS actively wired via `FallbackOrchestrator` (not "[NEEDS VERIFICATION]"). One bug-class confirmation: `ProductionHardeningLayer` has no `Drop` impl, confirming runtime resource leak risk without explicit `shutdown().await`. **Deep investigation pass 2026-05-12 (version 1.10):** closed 2 factual §11 Open Questions (`*_stub` grep result, `AIArbiter` non-Send violation check) by moving resolutions into §8 Invariants 19 and 20. Enriched 4 decisional §11 questions with deeper factual context: `AIControlMode` vs `PlannerMode` (variant-set diff), Hermes2Pro/Qwen3/Phi3 (3-client coexistence + phi3:medium runtime default contradiction), `astraweave-ai` forbid_unsafe (grep verified absent crate-wide), `VectorStoreWrapper` consolidation no-op (verified no test catches the bug). Surfaced one new cognitive trap in §6: runtime LLM default is phi3:medium despite doc-comment Qwen3 claims. **Verification pass 2026-05-12 (version 1.11):** resolved 5 additional markers in §7 (Interner test isolation — no `serial_test` in astraweave-behavior), §13.2 (Director context/prompts deps enrichment), §13.3 (`PhysicsWorld::control_character` confirmed to use dt internally), §13.4 (D12 LlmDialogueSystem Send+Sync fields audited, TOML speaker field NOT retained, RunnerState Idle/Finished externally observable only via `is_finished()`). Verified git log searches for "Phase 7" + "WorldState" + "fallback" returned no relevant AI-pipeline commits — §7 Decision Log "[Reasoning not recovered]" markers remain unrecoverable per Default 3 (honest acknowledgment of missing rationale). | --- @@ -460,7 +460,7 @@ This section enumerates the load-bearing files. Per-file enumeration of all 112 | `astraweave-memory/src/preference_profile.rs` | `PreferenceProfile`, `ProfileBuilder`, `CompanionActionPreference` | Active | | | `astraweave-memory/src/dynamic_weighting.rs` | `AdaptiveWeightManager`, `BehaviorNodeType` (6 variants), `NodeWeight` | Active (Phase 4) | Adaptive behavior tree weighting. **No production consumers found** — see §13.1.7 | | `astraweave-memory/src/learned_behavior_validator.rs` | `BehaviorValidator`, `SafetyRule`, `ValidationResult`, `ValidationStats` | Active | | -| `astraweave-memory/src/consolidation.rs` | `ConsolidationEngine`, `ConsolidationConfig` (default `association_threshold = 0.7`, `temporal_window_hours = 24.0`, `max_associations = 10`) | Active | | +| `astraweave-memory/src/consolidation.rs` | `ConsolidationEngine`, `ConsolidationConfig` (default `association_threshold = 0.7`, `temporal_window_hours = 24.0`, `max_associations = 10`). A window in `[0, 1)` hour is a 0-second duration. Memories from the same instant still link, and the stored strength is finite | Active | | | `astraweave-memory/src/forgetting.rs` | `ForgettingEngine`, `ForgettingConfig`, per-`MemoryType` `ForgettingCurve` (Sensory half-life ~6 h, Working ~1 day, Episodic ~2 weeks, …) | Active | Re-exported via `lib.rs:51-52`. Not in original parent §5 enumeration | | `astraweave-memory/src/compression.rs` | `CompressionEngine`, `CompressionConfig`, `CompressionResult` (memory summarization to reduce storage) | Active | Re-exported via `lib.rs:54-55`. Not in original parent §5 enumeration | | `astraweave-memory/src/retrieval.rs` | `RetrievalConfig`, `RetrievalResult`, `ScoreBreakdown`, `RetrievalPath` (semantic + temporal + associative weighted search; defaults `semantic_weight = 0.6`, `temporal_weight = 0.2`, `associative_weight = 0.2`) | Active | Re-exported via `lib.rs:57-58`. Not in original parent §5 enumeration | @@ -967,7 +967,9 @@ The Memory subsystem is the intended substrate for **companion learning**: it ca ▼ [M7 — Side branches] ConsolidationEngine — astraweave-memory/src/consolidation.rs (24 h temporal-window - association formation; default association_threshold = 0.7) + association formation; default association_threshold = 0.7). A window in + `[0, 1)` hour is a 0-second duration. Same-instant memories still link, + and the stored strength is finite. ForgettingEngine — astraweave-memory/src/forgetting.rs (per-MemoryType half-life curves: Sensory ~6 h, Working ~1 day, Episodic ~2 weeks, …) CompressionEngine — astraweave-memory/src/compression.rs (memory summarization @@ -1574,10 +1576,10 @@ All listed in parent §5 enrichment above. Summary: | **Totals** | **6930** | **297** | | **Dependencies (per `astraweave-dialogue/Cargo.toml`):** -- Used by basic layer: `serde`, `serde_json`, `anyhow`, `toml` (stdlib + serde stack only) -- Used by LLM layer only: `astraweave-llm`, `astraweave-embeddings`, `astraweave-context`, `astraweave-prompts`, `astraweave-rag`, `astraweave-persona`, `tokio (full)`, `async-trait`, `uuid`, `chrono`, `rand`, `regex` +- Used by basic layer: `serde`, `serde_json`, `anyhow`, `toml` +- Used by LLM layer only: `astraweave-core`, `astraweave-llm`, `astraweave-embeddings`, `astraweave-context`, `astraweave-prompts`, `astraweave-rag`, `astraweave-persona`, `tokio (full)`, `async-trait`, `regex` -The basic layer compiles without any of the LLM-stack deps; the LLM layer pulls in six AstraWeave crates plus heavyweight async + regex + non-deterministic RNG. The dependency split mirrors the active/dormant split. +The basic layer uses none of the LLM-stack deps. The crate depends on seven AstraWeave crates (`astraweave-core` plus the six LLM crates) along with tokio, async-trait, and regex. The dependency split mirrors the active/dormant split. #### 13.4.5 Cross-subsystem touchpoints @@ -1739,7 +1741,7 @@ The Coordination subsystem is the **multi-agent orchestration layer** designed f |---|---|---| | **`Agent`** trait | Async trait with 15 required methods: `agent_id`, `agent_type`, `get_state`, `set_state`, `handle_message`, `get_goals`, `set_goals`, `get_capabilities`, `can_handle_task`, `execute_task`, `get_resource_usage`, `get_event_subscriptions`, `handle_world_event`, `add_task`, `is_available`. `Send + Sync`. **Distinct from** `astraweave-ai::orchestrator::Orchestrator` (parent §3) — Coordination's `Agent` is broader, message-oriented, and async-by-default. | `agent.rs:11-58` | | **`AgentState`** | `#[non_exhaustive]` 6-variant enum: `Idle`, `Processing`, `WaitingForInput`, `Collaborating`, `Disabled`, `Error(String)`. Parallel to NPC's `NpcMode` (§13.3.3) and Director's `CoordinationStatus` but distinct. | `agent.rs:62-70` | -| **`AgentMessage`** | `{ id: String, from: String, to: String, message_type: MessageType, content: serde_json::Value, timestamp: DateTime, ... }`. The inter-agent message envelope. | `agent.rs:73-…` | +| **`AgentMessage`** | `{ id: String, from: String, to: String, message_type: MessageType, content: serde_json::Value, timestamp: time::OffsetDateTime, ... }`. The inter-agent message envelope. | `agent.rs:73-…` | | **`AgentGoal`**, **`Task`**, **`TaskResult`** | Goal/task lifecycle types used by `Agent::execute_task`. | `agent.rs` | | **`WorldEvent`**, **`EventSeverity`** | World-event broadcast types used by `Agent::handle_world_event`. `EventSeverity` distribution defaults in `SeverityDistribution`: 40% trivial / 30% minor / 20% moderate / 8% major / 2% critical. | `agent.rs`, `world_events.rs:46-52` | | **`ResourceUsage`** | Per-agent resource accounting (CPU/memory/LLM-token tracking) returned by `Agent::get_resource_usage`. | `agent.rs` | @@ -1776,7 +1778,7 @@ All listed in parent §5 enrichment above. Summary: | `benches/coordination_adversarial.rs` | 982 | 0 | 0 | Criterion bench harness | | **Totals** | **7335** | **98** | **7** | | -**Dependencies (per `astraweave-coordination/Cargo.toml`):** `astraweave-llm`, `astraweave-rag`, `astraweave-context`, `astraweave-prompts`, plus `tokio (workspace)`, `futures 0.3`, `uuid`, `chrono`, `dashmap 6.0`, `petgraph 0.6`, `async-trait`, `rand`. **Notably absent:** `astraweave-core`, `astraweave-ai`, `astraweave-behavior`, `astraweave-memory`, `astraweave-director`, `astraweave-npc`, `astraweave-dialogue`. Despite being designed to coordinate the latter subsystems, the Coordination crate does not depend on any of them. +**Dependencies (per `astraweave-coordination/Cargo.toml`):** `astraweave-llm`, `astraweave-rag`, `astraweave-context`, `astraweave-prompts`, plus `tokio (workspace)`, `futures 0.3`, `uuid`, `time`, `dashmap 6.0`, `petgraph 0.6`, `async-trait`, `rand`. **Notably absent:** `astraweave-core`, `astraweave-ai`, `astraweave-behavior`, `astraweave-memory`, `astraweave-director`, `astraweave-npc`, `astraweave-dialogue`. Despite being designed to coordinate the latter subsystems, the Coordination crate does not depend on any of them. #### 13.5.5 Cross-subsystem touchpoints @@ -2647,7 +2649,7 @@ InjectionResult{enhanced_prompt, injected_memories, context_tokens, metadata: - **`InjectionStrategy` is metadata-only.** [Factual.] `pipeline.rs:481` hardcodes `InjectionStrategy::Insert` regardless of actual template behavior. The 5-variant enum (Prepend/Append/Insert/Interleave/Replace) is decorative. Either implement the alternate strategies (which would require different template logic per strategy), prune the unused variants, or rename the enum to `InjectionShape` to make clear it's a template-pattern descriptor rather than an active control. - **`TokenCounter::new("cl100k_base")` hardcoded.** [Factual / decisional.] `pipeline.rs:198` chooses the GPT-3.5/GPT-4 encoder unconditionally. For Qwen3/Llama3-family tokenizers, the cl100k_base count is approximate (typically over-estimates by 5-15%). Per `astraweave-context/src/token_counter.rs:41-43` `get_bpe_from_model` falls back to cl100k_base for any unrecognized model name, so the practical impact is small, but the API contract is misleading. Options: thread `encoding_model: String` through `RagConfig` (low blast radius — just add a field with cl100k_base default); add `RagPipeline::with_token_counter(custom_counter)`; or document the cl100k_base universality choice in the type's doc-comment. - **`add_memory` / `add_memory_async` default Memory fields are coarse.** [Decisional.] Both hardcode `importance: 1.0`, `valence: 0.0`, `category: MemoryCategory::Gameplay`, `entities: []`, `context: {}` (`pipeline.rs:226-234, :624-632`). Consumers wanting categorized + entity-tagged memories must use `add_memory_obj(Memory{...})` directly. The asymmetric API (text-shortcut vs full-object) is workable but the lossy defaults invite consumers to use the shortcut and never realize they've lost categorical structure. Recommendation: deprecate the shortcuts in favor of explicit Memory construction. -- **`current_timestamp()` non-determinism.** [Factual / decisional, mirrors `forgetting.rs:69` `chrono::Utc::now().timestamp()` usage.] All RAG timestamps are wall-clock UNIX seconds. Game replays / deterministic ECS-tick systems cannot use RAG as a deterministic memory input. Options: thread a "time source" trait through `RagConfig` (e.g. `Box` defaulting to wall-clock); document that RAG is explicitly non-deterministic and consumers wanting determinism must implement their own; or accept the non-determinism as a deliberate choice for live-LLM AI (which is itself non-deterministic). +- **`current_timestamp()` non-determinism.** [Factual / decisional, mirrors `forgetting.rs` `OffsetDateTime::now_utc().unix_timestamp()` usage.] All RAG timestamps are wall-clock UNIX seconds. Game replays / deterministic ECS-tick systems cannot use RAG as a deterministic memory input. Options: thread a "time source" trait through `RagConfig` (e.g. `Box` defaulting to wall-clock); document that RAG is explicitly non-deterministic and consumers wanting determinism must implement their own; or accept the non-determinism as a deliberate choice for live-LLM AI (which is itself non-deterministic). - **`VectorStore` is a linear-scan, NOT actually HNSW.** [Factual / cognitive trap.] `astraweave-embeddings/src/lib.rs:9` advertises "Fast similarity search using HNSW indexing." `astraweave-embeddings/src/store.rs:16` says "with HNSW indexing (simplified implementation)." Actual code at `store.rs:42-60` shows a DashMap with a `next_index` Mutex (unused), with no HNSW data structure visible. Search is a linear scan iterating the DashMap (verified by reading `search` impl in the same file). The `hnsw_rs = { version = "0.3", optional = true }` dependency in `Cargo.toml:31` and the `hnsw = ["hnsw_rs"]` feature flag (`:42`) suggest HNSW was planned but never integrated. At 100,000-vector capacity with linear scan + 384-dim cosine distance, search latency is ~10-50ms — likely acceptable for game AI but the documentation suggests sub-millisecond ANN search. Options: actually implement HNSW; remove the HNSW claims from the doc-comments; or document the "simplified scan" trade-off explicitly. - **`RagPipeline` vs `astraweave-memory::MemoryManager` — two memory subsystems with no shared types.** [Decisional, mirrors parent §13.1 Memory dormancy pattern.] Factual (verified 2026-05-12 + cross-referenced with §13.1): `astraweave-rag` operates on `astraweave-embeddings::Memory{id, text, timestamp, importance, valence, category, entities, context}`. `astraweave-memory` operates on its own types (`MemoryRecord`, `Persona`, `GameEpisode`, `Episode`, hierarchical sensory/working/episodic/semantic). The two subsystems do NOT share a memory representation. Per §13.1 both are dormant for the runtime AI loop. The directional question is the same: production-wire one (and prune or rebrand the other), or surface the two-subsystem-coexistence as deliberate (e.g. memory crate for hierarchical typing + RAG crate for semantic retrieval). The two-crate stack would either need an adapter layer or one would need to subsume the other. - **The `protected_categories: vec![MemoryCategory::Quest]` default in ForgettingConfig.** [Factual.] `forgetting.rs:44`. Quest memories never decay through `ForgettingEngine`. This is a deliberate choice (quest progress should not be forgotten), but it interacts with `ConsolidationStrategy::Importance` which CAN remove low-importance Quest memories during consolidation. If a Quest memory has importance 0.1 and is dropped by importance-based consolidation, the protected-category flag in forgetting is moot. Either align consolidation to respect protected_categories, or document the asymmetry, or deprecate one of the two protection mechanisms. diff --git a/docs/architecture/aw_editor.md b/docs/architecture/aw_editor.md index 864af86c30..ff8e9e2031 100644 --- a/docs/architecture/aw_editor.md +++ b/docs/architecture/aw_editor.md @@ -22,9 +22,9 @@ last_verified_commit: 154d723aa | **Primary crates** | `tools/aw_editor/` (sole primary crate; two binaries: `aw_editor` GUI + `aw_game_runtime` standalone game runner — both windowed via winit+wgpu, see §6 trap notes) | | **Document version** | 1.21 | | **Last verified against commit** | `154d723aa` (v1.16, 2026-08-02: L.3.C-resolution — L-series CSM harnesses + `tests/common` relief module; trace updated in the same commit as the code, so this names its parent); prior L.2-calibration working tree over `5b78fdd78` (v1.13 pass); prior `b1295b93f` (v1.12); prior L.1 `1d8e1c792` (v1.11); prior ED-3 `09ea417af` (v1.10), prior `03f9d9a2d` (v1.9), prior `1e3d8f692` (v1.7), `8232b150b` (v1.5). Note: v1.8 (ED-2) bumped the front-matter `doc_version` only and left this table at 1.7 — corrected here. | -| **Last verified date** | 2026-07-29 (v1.15, L.3.A — the camera-anchored shadow boundary, editor side: engine-only fix (render trace v1.18 — third survey cascade to 3000 m); the editor surface is the new **camera-MOTION verification harness** `tests/l3a_proof.rs` (radial shadow-effect profile at two survey altitudes with flat-plane row→distance mapping + stated dune-height error bars; a 600 m lateral sweep at the rejection recording's Y≈219 with two world-anchored shadow features tracked by reprojection — the assertions that camera position must not change a world feature's shadow state; `L3A_EXPECT=fixed` arms them). Close/mid station frames byte-match L.3 (c0/c1 pinned); y414 shows relief shadowed; off-toggle bit-exact. The verification bar minted: camera-fitted systems get motion legs, never static stations alone. Evidence: `docs/audits/L3A_OUTCOME.md`. Prior v1.14, 2026-07-28 (L.3 — terrain CSM cast+receive, editor side: (1) **the editor terrain scene now renders terrain shadows** — engine-side caster+receiver (render trace v1.17, invariant 20); the adapter's involvement is configuration truth: at defaults the scene's shadow state comes from **`GameQuality` applied at adapter init** (`apply_quality_preset(GameQuality)` in `new`) because the terrain-upload block's auto-switch to `EditorTerrain` is gated on `quality_preset != GameQuality` — i.e. the `EditorTerrain` preset does NOT apply on the default path (proven: two harness legs differing only in the preset's `set_shadow_filter` bias were bit-identical across 12 frames). The upload block's own `set_shadow_filter(1.5, 0.0005, 1.0)` is the delivered filter config (receiver bias 0.0005; the 3rd arg slope-scale is write-only — never uploaded, logged residue). (2) The `EditorTerrain` preset itself now enables shadows with explicit filter values (the ratified T2F §5 A(iii): it must not silently kill terrain shadows when a user selects it) and its variant/docs state the truth. (3) The upload block's `set_cascade_extents(80, 250)` is a **no-op** (fields never read — sphere fitting superseded them); `set_cascade_lambda(0.7)` IS live → split0 ≈ 86.1 m in the terrain scene. (4) New `tests/l3_proof.rs` (cloned from l2_proof): 4 pinned stations × default-sun (43.2°, the panel-pinned override — `set_time_of_day` is INERT in terrain scenes, proven byte-identical, so the raking-sun leg drives `set_lighting_params` varying only `sun_dir` to elevation 20°/same azimuth 51.3°) + rake + ED-3 normals mask + `L3_SHADOWS=off` sentinel toggle leg + per-cascade caster culling stats + 2-station perf. Toggle proof: off-state vs pre-L.3 = 0 differing pixels (desert_close + all normals; ≤3 px @ 1 LSB elsewhere). Evidence: `docs/audits/L3_OUTCOME.md`. Prior v1.13, L.2 calibration — director-ratified A+B+E shipped: (1) **the init IBL bake runs on a WORKER THREAD** (`spawn_default_environment_bake` at adapter construction: a second `IblManager` on the `l2-env-bake` thread bakes the tracked kloppenheim HDRI and channels `IblResources` back; `poll_env_bake` — called per frame from `render_to_texture` — installs via `Renderer::install_baked_environment`; the UI thread never blocks on the ~2.5 s bake; frames before arrival use the fallback sky-fill env, a one-time startup transition; `wait_env_bake(timeout)` gives harnesses a deterministic post-bake state — l1_proof/l2_proof call it). (2) Engine-side calibration: bake-cube sun-clamp + fixed intensity 1.5 (render trace v1.16). (3) Final A/B at shipped calibration: desert +33 / grass +22 mean luma vs L.1 baseline, sd 9.9–15.6, glitter-free; L.1 controls re-certified (defaults-push 0 differing px; exposure 79/146/197; late-push landed 50.19 vs ~146 dropped, thr 140). Evidence: `docs/audits/L2_OUTCOME.md` §0.1. Prior v1.12, 2026-07-27 (L.2 — IBL for editor terrain: (1) **the editor bakes an environment at adapter init** — `EngineRenderAdapter::new` → `bake_default_environment()`: tracked `assets/hdri/polyhaven/kloppenheim_02_puresky_2k.hdr` (catalog `kloppenheim_daytime`, CC0, present in a bare clone), tier Medium (the load_hdri/clear_hdri convention), probed from `assets`/`../../assets`, absence/failure → `tracing::warn!` + continue on the fallback bind groups (2.48 s cold, once per adapter). (2) Terrain pixels are environment-lit via the engine's shared `compute_ibl` at group(3) — the World-panel ambient controls are relabelled **"(statics)"** with hover text (honest repurpose per the L.2 binding condition: they still drive the static-mesh ambient floor; terrain no longer reads them). (3) `l1_proof.rs` late-push dark params recalibrated for the IBL fill (dark push now also carries exposure 0.5; threshold 140; landed 92.31 vs ~178 dropped). (4) New `tests/l2_proof.rs` A/B harness (4 pinned stations × lit+ED-3-normals; the normals pair doubles as the sky/ground attribution mask — byte-identical at all stations, zero sky pixels in the pinned framings). (5) **Default calibration STOPPED pending ratification** — the delivered default over-drives IBL ~2.4–2.5× with irradiance fireflies; measured diagnosis + previewed remedies in `docs/audits/L2_OUTCOME.md` §4–5. Prior v1.11, 2026-07-26 (L.1 — lighting calibration & honesty, all visually neutral at defaults, proven 0 differing pixels at 4 pinned stations: (1) **the frame-1 lighting-push race is FIXED** — `ViewportRenderer::set_lighting_params` PARKS a push arriving before the async engine adapter exists (`pending_lighting_params`) and `init_engine_adapter` delivers it, so a push is never silently dropped and the caller's change-cache in `main.rs` stays truthful (pre-L.1 the World panel's frame-1 push was dropped + cached as delivered, leaving the panel displaying sun 2.2x while the renderer delivered 1.0x until a slider touch jumped the scene +42%; T2F_LIGHTING_RECON.md par.3). (2) **The World panel lighting defaults are reconciled to the DELIVERED state** via pinned constants in `viewport/types.rs` (`DEFAULT_SUN_*`/`DEFAULT_AMBIENT_*`/`DEFAULT_EXPOSURE`, single source for the panel struct defaults, `TerrainLightingParams::default()`, and the engine adapter's terrain-upload block; bit-identity of the pinned sun direction with the upload hardcode is asserted by test). (3) **The Exposure slider is LIVE end-to-end** — `TerrainLightingParams.exposure` -> `EngineRenderAdapter::set_lighting_params` -> `SceneEnvironment.exposure` -> the scene-env UBO pad float at offset 72 -> `uPostScene.exposure` in the POST shaders (default 1.35 = the former hardcode). (4) **Preset fictions deleted**: EditorTerrain/EditorDefault no longer claim SSAO, GameQuality no longer claims TAA — no such passes exist in this render path (only `bloom_enabled` is consumed); flags zeroed, enum/setter docs rewritten, dormant machinery untouched. Proof: `tests/l1_proof.rs` (neutrality: 0 differing pixels before/after at 4 stations; exposure 0.5/1.35/3.0 pairwise-different, byte-identical at the default; pre-init push lands after adapter init — both control tests FAIL at the pre-L.1 commit, demonstrated). Evidence: `docs/audits/L1_OUTCOME.md`. Prior v1.10, 2026-07-26 (ED-3: **all three settable-but-never-read surfaces CLOSED - every control now works or is hidden.** (1) The viewport shading dropdown is LIVE: `ShadingMode` grew `Normals`/`Uvs` (5 modes), `ViewportRenderer::render`'s formerly-dead `_shading_mode` param is consumed and forwarded via `EngineRenderAdapter::set_debug_shading` into the scene-env UBO's new `debug_mode` (a commandeered pad float, 96-B layout unchanged) plus a wireframe pipeline swap; all three live fragment shaders branch on it uniformly (no second render path). (2) The docked five-entry dropdown maps 1:1 onto the same enum - the silent Normals/UVs-to-Lit collapse is deleted (`main.rs` handler). Wireframe ships as polygon-mode-Line variants of the static-mesh + terrain-forward pipelines, feature-gated: `toolbar.wireframe_supported` (synced per frame from the renderer) hides the entry on devices without `POLYGON_MODE_LINE`. (3) The Terrain panel's dead absolute Amplitude slider is replaced by **"Amplitude x (spline scale)"** - `TerrainPanel::amplitude_scale` -> `TerrainState::set_amplitude_scale` -> `NoiseConfig::base_amplitude_scale` (default 1.0 = bit-identical; archetype splines stay the authority) - which makes T.3's amplitude-finality gate actionable. Proof: `tests/ed3_proof.rs` (2 GPU tests - five modes render 99.8-100% different from Lit; three amplitude scales differ pairwise ~99.5%; on pre-ED-3 code both collapse to byte-identical frames, the defect itself). Evidence: `docs/audits/ED3_OUTCOME.md`. Prior v1.9, 2026-07-25 (T.2d third pass `03f9d9a2d`: **three settable-but-never-read surfaces recorded in §11**, no code change. (1) The viewport shading dropdown is inert — `ShadingMode` is converted at `viewport/widget.rs:880` and handed to `ViewportRenderer::render`, whose parameter is `_shading_mode: u32` (`viewport/renderer.rs:570`) and is unused; `has_lighting()`/`is_wireframe()` have zero non-test callers. (2) The docked Viewport panel advertises five modes (`tab_viewer/mod.rs:2082`) of which **Normals** and **UVs** are silently mapped to `Lit` (`main.rs:5208-5214`) — debug visualisations promised but never built, which is exactly what a renderer diagnosis reaches for first. (3) The Terrain panel's *Base Amplitude* slider is inert (trace: `docs/architecture/terrain.md` §11), proven by `t2d_camera_light.rs` Experiment F rendering three amplitudes byte-identical. Evidence: `docs/audits/T2D_CAMERA_LIGHT.md` §10. Prior v1.8, ED-2 `03f9d9a2d`: camera pin/restore + viewport capture, Invariants 30/31. Prior v1.7, 2026-07-24 (v1.7, T.W.2 `1e3d8f692`: **paintable water**. (1) **Carve Water brush** — `BrushMode::CarveWater` in the sculpt family (`terrain_panel.rs`; `name`/`icon`/`all()` touched); the shared `apply_brush`'s `flatten_target` arg generalized to `target_height`, its CarveWater arm blends terrain toward `water_level − carve_depth` DOWNWARD-ONLY (idempotent at depth, falloff→shore); the panel's `brush_target_height()` recomputes it per-application; carve-depth slider + water-off affordance; reuses the sculpt undo path verbatim (`end_brush_stroke`→`TerrainBrushCommand`, no carve-specific undo). A pure terrain op — touches no water config. (2) **WaterVolume entity** — `WaterVolume` archetype + `+ Add → Environment → Water Volume` + `show_water_volume_inspector` (extents + `WaterStyle`; entity Y = surface level) + AddComponent default (all registration surfaces touched); `viewport/widget.rs` collects `WaterVolumeSpec` from the `EntityManager` like lights, `viewport/renderer.rs`→`EngineRenderAdapter::set_water_volumes` resolves style via `water_style_params` (factored, shared plane+volume) and forwards to `Renderer::set_water_volumes`. (3) **Component persistence** — `EntityData` gained `components: HashMap` (serde default + skip-if-empty; pre-TW2 files parse); `save_scene_with_overlay`/`load_scene_with_overlay` carry the `EntityManager` overlay through the file, **fixing a pre-existing bug where Light/Camera components were dropped on every save/reload**. All save surfaces updated incl. the `Ctrl+S`/`Ctrl+Shift+S` hotkeys (`subsystems/hotkeys.rs` — a missed registration surface caught live); the drag-drop `.ron` + asset-browser load paths consolidated onto `load_scene_from_path`. New Invariant 29. Prior v1.6, T.W.1 `88c6ba588`: **editor water surfaced** — `set_water_enabled` format fix (`surface_format()`→`hdr_format()`; the old argument panicked wgpu against the Rgba16Float water pass, `TWR_WATER_RECON.md` §1.6) + W.2c.2 scaffolding-weave deletion (`engine_adapter.rs`); legacy `primary_biome` water gate in `main.rs` replaced by the aquatic-biome census default (`TerrainState::has_aquatic_biomes`) + Terrain-panel Water checkbox/level slider (level defaults `astraweave_terrain::SEA_LEVEL`; was a frozen 0.0 field with no UI); per-archetype `WaterStyle` map (`water_style_for_archetype`, coast→Ocean, Boreal/Desert→Lake) threaded through `widget`/`viewport::renderer` `set_water_enabled(enabled, style)`; ratified hygiene deletions — dead SPH-era panel fluid block (`FluidSimParams`/`WaterBodyPreset`/`FluidQualityPreset`/`DetectedWaterBodyInfo`/`FluidStats` + ~200 tested-but-uncalled tests) and zero-caller `apply_brush_paint`+`id_to_biome` (`chunk.biome_map_mut` retains its generation caller). New Invariant 28. Prior v1.5, T.0 trace-sync: **multi-biome terrain render integration — the E3 build's editor side** (`d506658d8`, 2026-07-03; landed BEFORE the v1.3/v1.4 passes but never traced — reconstruction at `docs/audits/E3_PREFLIGHT_2026-07.md`). `generate_terrain` threads per-vertex `chunk.biome_ids()` into `generate_heightmap_mesh` (`terrain_integration.rs:375-388`, param `:766`); `build_biome_slot_field` (`:1293-1370`) maps each vertex's Whittaker `BiomeId` through the exhaustive 19→8 `biome_id_to_slot` (`:1250-1274`), adds a slope-rock overlay toward slot 3 (consts `:1304-1306`) and a 1-ring box blur, and the result drives per-vertex `material_ids`/`material_weights` into `TerrainVertex` (`:837-840`, `:861-867`); the legacy single-`primary_biome` splat generator survives only as the fallback when biome data is absent (`:797-802`, `:841-852`). Biome-driven assignment emits pack-layer indices DIRECTLY (arrays.toml order matches `biome_id_to_slot` 1:1) and therefore bypasses the palette remap — the remap governs manual painting only (the two paths coexist; see Invariant 27). Also records the four `E3-terrain (temporary)` judging aids as REVERT-BEFORE-v1 debt owned by terrain beat T.3 (see §6). Prior v1.4 2026-07-15: AD.5.A Fix 3 — paint-palette→pack-layer name remap (AD.4.A §5a Option C, director-ratified). New `viewport/palette_remap.rs` (`PaletteRemap::resolve` joins `MATERIAL_NAMES` stems against the loaded pack's per-layer albedo stems; placeholder set gets identity 0..8); `CanonicalLayerBytes.albedo_stem` retained at load as the join key; `EngineRenderAdapter` re-resolves on every terrain-layer upload and exposes `palette_remap()`; `EditorApp::update` syncs it per frame (try_lock) into the live `dock_tab_viewer.terrain_panel`; both paint call sites write the REMAPPED layer index (raw-palette-id writes removed) and unresolved entries render disabled with tooltip. Prior pass 2026-07-02 v1.3: AstraWeave branded theme as default — palette single-source `ui/palette.rs`, dock chrome unified via `DockLayout::themed_style`, window icon + top-bar brand mark `ui/branding.rs`, splash video re-enabled with first-frame gate reverting the functional half of `1fc266c93`. Feedback pass 2026-07-02: palette re-tinted to neon sky-blue accent over black metallic-flake surfaces; `world_wizard.rs` theme-routed and made a true modal (Foreground order, input-swallowing dim, one-shot raise above HUD overlays — re-raising per frame would cover its own ComboBox popups); dark branded Win11 title bar via `DWMWA_CAPTION_COLOR`/`DWMWA_TEXT_COLOR` in the DWM composition helper. Prior full pass 2026-05-12 v1.2) | +| **Last verified date** | 2026-07-29 (v1.15, L.3.A — the camera-anchored shadow boundary, editor side: engine-only fix (render trace v1.18 — third survey cascade to 3000 m); the editor surface is the new **camera-MOTION verification harness** `tests/l3a_proof.rs` (radial shadow-effect profile at two survey altitudes with flat-plane row→distance mapping + stated dune-height error bars; a 600 m lateral sweep at the rejection recording's Y≈219 with two world-anchored shadow features tracked by reprojection — the assertions that camera position must not change a world feature's shadow state; `L3A_EXPECT=fixed` arms them). Close/mid station frames byte-match L.3 (c0/c1 pinned); y414 shows relief shadowed; off-toggle bit-exact. The verification bar minted: camera-fitted systems get motion legs, never static stations alone. Evidence: `docs/audits/L3A_OUTCOME.md`. Prior v1.14, 2026-07-28 (L.3 — terrain CSM cast+receive, editor side: (1) **the editor terrain scene now renders terrain shadows** — engine-side caster+receiver (render trace v1.17, invariant 20); the adapter's involvement is configuration truth: at defaults the scene's shadow state comes from **`GameQuality` applied at adapter init** (`apply_quality_preset(GameQuality)` in `new`) because the terrain-upload block's auto-switch to `EditorTerrain` is gated on `quality_preset != GameQuality` — i.e. the `EditorTerrain` preset does NOT apply on the default path (proven: two harness legs differing only in the preset's `set_shadow_filter` bias were bit-identical across 12 frames). The upload block's own `set_shadow_filter(1.5, 0.0005, 1.0)` is the delivered filter config (receiver bias 0.0005; the 3rd arg slope-scale is write-only — never uploaded, logged residue). (2) The `EditorTerrain` preset itself now enables shadows with explicit filter values (the ratified T2F §5 A(iii): it must not silently kill terrain shadows when a user selects it) and its variant/docs state the truth. (3) The upload block's `set_cascade_extents(80, 250)` is a **no-op** (fields never read — sphere fitting superseded them); `set_cascade_lambda(0.7)` IS live → split0 ≈ 86.1 m in the terrain scene. (4) New `tests/l3_proof.rs` (cloned from l2_proof): 4 pinned stations × default-sun (43.2°, the panel-pinned override — `set_time_of_day` is INERT in terrain scenes, proven byte-identical, so the raking-sun leg drives `set_lighting_params` varying only `sun_dir` to elevation 20°/same azimuth 51.3°) + rake + ED-3 normals mask + `L3_SHADOWS=off` sentinel toggle leg + per-cascade caster culling stats + 2-station perf. Toggle proof: off-state vs pre-L.3 = 0 differing pixels (desert_close + all normals; ≤3 px @ 1 LSB elsewhere). Evidence: `docs/audits/L3_OUTCOME.md`. Prior v1.13, L.2 calibration — director-ratified A+B+E shipped: (1) **the init IBL bake runs on a WORKER THREAD** (`spawn_default_environment_bake` at adapter construction: a second `IblManager` on the `l2-env-bake` thread bakes the tracked kloppenheim HDRI and channels `IblResources` back; `poll_env_bake` — called per frame from `render_to_texture` — installs via `Renderer::install_baked_environment`; the UI thread never blocks on the ~2.5 s bake; frames before arrival use the fallback sky-fill env, a one-time startup transition; `wait_env_bake(timeout)` gives harnesses a deterministic post-bake state — l1_proof/l2_proof call it). (2) Engine-side calibration: bake-cube sun-clamp + fixed intensity 1.5 (render trace v1.16). (3) Final A/B at shipped calibration: desert +33 / grass +22 mean luma vs L.1 baseline, sd 9.9–15.6, glitter-free; L.1 controls re-certified (defaults-push 0 differing px; exposure 79/146/197; late-push landed 50.19 vs ~146 dropped, thr 140). Evidence: `docs/audits/L2_OUTCOME.md` §0.1. Prior v1.12, 2026-07-27 (L.2 — IBL for editor terrain: (1) **the editor bakes an environment at adapter init** — `EngineRenderAdapter::new` → `bake_default_environment()`: tracked `assets/hdri/polyhaven/kloppenheim_02_puresky_2k.hdr` (catalog `kloppenheim_daytime`, CC0, present in a bare clone), tier Medium (the load_hdri/clear_hdri convention), probed from `assets`/`../../assets`, absence/failure → `tracing::warn!` + continue on the fallback bind groups (2.48 s cold, once per adapter). (2) Terrain pixels are environment-lit via the engine's shared `compute_ibl` at group(3) — the World-panel ambient controls are relabelled **"(statics)"** with hover text (honest repurpose per the L.2 binding condition: they still drive the static-mesh ambient floor; terrain no longer reads them). (3) `l1_proof.rs` late-push dark params recalibrated for the IBL fill (dark push now also carries exposure 0.5; threshold 140; landed 92.31 vs ~178 dropped). (4) New `tests/l2_proof.rs` A/B harness (4 pinned stations × lit+ED-3-normals; the normals pair doubles as the sky/ground attribution mask — byte-identical at all stations, zero sky pixels in the pinned framings). (5) **Default calibration STOPPED pending ratification** — the delivered default over-drives IBL ~2.4–2.5× with irradiance fireflies; measured diagnosis + previewed remedies in `docs/audits/L2_OUTCOME.md` §4–5. Prior v1.11, 2026-07-26 (L.1 — lighting calibration & honesty, all visually neutral at defaults, proven 0 differing pixels at 4 pinned stations: (1) **the frame-1 lighting-push race is FIXED** — `ViewportRenderer::set_lighting_params` PARKS a push arriving before the async engine adapter exists (`pending_lighting_params`) and `init_engine_adapter` delivers it, so a push is never silently dropped and the caller's change-cache in `main.rs` stays truthful (pre-L.1 the World panel's frame-1 push was dropped + cached as delivered, leaving the panel displaying sun 2.2x while the renderer delivered 1.0x until a slider touch jumped the scene +42%; T2F_LIGHTING_RECON.md par.3). (2) **The World panel lighting defaults are reconciled to the DELIVERED state** via pinned constants in `viewport/types.rs` (`DEFAULT_SUN_*`/`DEFAULT_AMBIENT_*`/`DEFAULT_EXPOSURE`, single source for the panel struct defaults, `TerrainLightingParams::default()`, and the engine adapter's terrain-upload block; bit-identity of the pinned sun direction with the upload hardcode is asserted by test). (3) **The Exposure slider is LIVE end-to-end** — `TerrainLightingParams.exposure` -> `EngineRenderAdapter::set_lighting_params` -> `SceneEnvironment.exposure` -> the scene-env UBO pad float at offset 72 -> `uPostScene.exposure` in the POST shaders (default 1.35 = the former hardcode). (4) **Preset fictions deleted**: EditorTerrain/EditorDefault no longer claim SSAO, GameQuality no longer claims TAA — no such passes exist in this render path (only `bloom_enabled` is consumed); flags zeroed, enum/setter docs rewritten, dormant machinery untouched. Proof: `tests/l1_proof.rs` (neutrality: 0 differing pixels before/after at 4 stations; exposure 0.5/1.35/3.0 pairwise-different, byte-identical at the default; pre-init push lands after adapter init — both control tests FAIL at the pre-L.1 commit, demonstrated). Evidence: `docs/audits/L1_OUTCOME.md`. Prior v1.10, 2026-07-26 (ED-3: **all three settable-but-never-read surfaces CLOSED - every control now works or is hidden.** (1) The viewport shading dropdown is LIVE: `ShadingMode` grew `Normals`/`Uvs` (5 modes), `ViewportRenderer::render`'s formerly-dead `_shading_mode` param is consumed and forwarded via `EngineRenderAdapter::set_debug_shading` into the scene-env UBO's new `debug_mode` (a commandeered pad float, 96-B layout unchanged) plus a wireframe pipeline swap; all three live fragment shaders branch on it uniformly (no second render path). (2) The docked five-entry dropdown maps 1:1 onto the same enum - the silent Normals/UVs-to-Lit collapse is deleted (`main.rs` handler). Wireframe ships as polygon-mode-Line variants of the static-mesh + terrain-forward pipelines, feature-gated: `toolbar.wireframe_supported` (synced per frame from the renderer) hides the entry on devices without `POLYGON_MODE_LINE`. (3) The Terrain panel's dead absolute Amplitude slider is replaced by **"Amplitude x (spline scale)"** - `TerrainPanel::amplitude_scale` -> `TerrainState::set_amplitude_scale` -> `NoiseConfig::base_amplitude_scale` (default 1.0 = bit-identical; archetype splines stay the authority) - which makes T.3's amplitude-finality gate actionable. Proof: `tests/ed3_proof.rs` (2 GPU tests - five modes render 99.8-100% different from Lit; three amplitude scales differ pairwise ~99.5%; on pre-ED-3 code both collapse to byte-identical frames, the defect itself). Evidence: `docs/audits/ED3_OUTCOME.md`. Prior v1.9, 2026-07-25 (T.2d third pass `03f9d9a2d`: **three settable-but-never-read surfaces recorded in §11**, no code change. (1) The viewport shading dropdown is inert — `ShadingMode` is converted at `viewport/widget.rs:880` and handed to `ViewportRenderer::render`, whose parameter is `_shading_mode: u32` (`viewport/renderer.rs:570`) and is unused; `has_lighting()`/`is_wireframe()` have zero non-test callers. (2) The docked Viewport panel advertises five modes (`tab_viewer/mod.rs:2082`) of which, in that v1.9 record, **Normals** and **UVs** were silently mapped to `Lit` — debug visualisations promised but never built. The live match is `main.rs:5111-5119`: ED-3 maps arm 3 to `ShadingMode::Normals` and arm 4 to `ShadingMode::Uvs` (comment at `main.rs:5106-5108`). Those arms are real modes, not a silent map to `Lit`. (3) The Terrain panel's *Base Amplitude* slider is inert (trace: `docs/architecture/terrain.md` §11), proven by `t2d_camera_light.rs` Experiment F rendering three amplitudes byte-identical. Evidence: `docs/audits/T2D_CAMERA_LIGHT.md` §10. Prior v1.8, ED-2 `03f9d9a2d`: camera pin/restore + viewport capture, Invariants 30/31. Prior v1.7, 2026-07-24 (v1.7, T.W.2 `1e3d8f692`: **paintable water**. (1) **Carve Water brush** — `BrushMode::CarveWater` in the sculpt family (`terrain_panel.rs`; `name`/`icon`/`all()` touched); the shared `apply_brush`'s `flatten_target` arg generalized to `target_height`, its CarveWater arm blends terrain toward `water_level − carve_depth` DOWNWARD-ONLY (idempotent at depth, falloff→shore); the panel's `brush_target_height()` recomputes it per-application; carve-depth slider + water-off affordance; reuses the sculpt undo path verbatim (`end_brush_stroke`→`TerrainBrushCommand`, no carve-specific undo). A pure terrain op — touches no water config. (2) **WaterVolume entity** — `WaterVolume` archetype + `+ Add → Environment → Water Volume` + `show_water_volume_inspector` (extents + `WaterStyle`; entity Y = surface level) + AddComponent default (all registration surfaces touched); `viewport/widget.rs` collects `WaterVolumeSpec` from the `EntityManager` like lights, `viewport/renderer.rs`→`EngineRenderAdapter::set_water_volumes` resolves style via `water_style_params` (factored, shared plane+volume) and forwards to `Renderer::set_water_volumes`. (3) **Component persistence** — `EntityData` gained `components: HashMap` (serde default + skip-if-empty; pre-TW2 files parse); `save_scene_with_overlay`/`load_scene_with_overlay` carry the `EntityManager` overlay through the file, **fixing a pre-existing bug where Light/Camera components were dropped on every save/reload**. All save surfaces updated incl. the `Ctrl+S`/`Ctrl+Shift+S` hotkeys (`subsystems/hotkeys.rs` — a missed registration surface caught live); the drag-drop `.ron` + asset-browser load paths consolidated onto `load_scene_from_path`. New Invariant 29. Prior v1.6, T.W.1 `88c6ba588`: **editor water surfaced** — `set_water_enabled` format fix (`surface_format()`→`hdr_format()`; the old argument panicked wgpu against the Rgba16Float water pass, `TWR_WATER_RECON.md` §1.6) + W.2c.2 scaffolding-weave deletion (`engine_adapter.rs`); legacy `primary_biome` water gate in `main.rs` replaced by the aquatic-biome census default (`TerrainState::has_aquatic_biomes`) + Terrain-panel Water checkbox/level slider (level defaults `astraweave_terrain::SEA_LEVEL`; was a frozen 0.0 field with no UI); per-archetype `WaterStyle` map (`water_style_for_archetype`, coast→Ocean, Boreal/Desert→Lake) threaded through `widget`/`viewport::renderer` `set_water_enabled(enabled, style)`; ratified hygiene deletions — dead SPH-era panel fluid block (`FluidSimParams`/`WaterBodyPreset`/`FluidQualityPreset`/`DetectedWaterBodyInfo`/`FluidStats` + ~200 tested-but-uncalled tests) and zero-caller `apply_brush_paint`+`id_to_biome` (`chunk.biome_map_mut` retains its generation caller). New Invariant 28. Prior v1.5, T.0 trace-sync: **multi-biome terrain render integration — the E3 build's editor side** (`d506658d8`, 2026-07-03; landed BEFORE the v1.3/v1.4 passes but never traced — reconstruction at `docs/audits/E3_PREFLIGHT_2026-07.md`). `generate_terrain` threads per-vertex `chunk.biome_ids()` into `generate_heightmap_mesh` (`terrain_integration.rs:375-388`, param `:766`); `build_biome_slot_field` (`:1293-1370`) maps each vertex's Whittaker `BiomeId` through the exhaustive 19→8 `biome_id_to_slot` (`:1250-1274`), adds a slope-rock overlay toward slot 3 (consts `:1304-1306`) and a 1-ring box blur, and the result drives per-vertex `material_ids`/`material_weights` into `TerrainVertex` (`:837-840`, `:861-867`); the legacy single-`primary_biome` splat generator survives only as the fallback when biome data is absent (`:797-802`, `:841-852`). Biome-driven assignment emits pack-layer indices DIRECTLY (arrays.toml order matches `biome_id_to_slot` 1:1) and therefore bypasses the palette remap — the remap governs manual painting only (the two paths coexist; see Invariant 27). Also records the four `E3-terrain (temporary)` judging aids as REVERT-BEFORE-v1 debt owned by terrain beat T.3 (see §6). Prior v1.4 2026-07-15: AD.5.A Fix 3 — paint-palette→pack-layer name remap (AD.4.A §5a Option C, director-ratified). New `viewport/palette_remap.rs` (`PaletteRemap::resolve` joins `MATERIAL_NAMES` stems against the loaded pack's per-layer albedo stems; placeholder set gets identity 0..8); `CanonicalLayerBytes.albedo_stem` retained at load as the join key; `EngineRenderAdapter` re-resolves on every terrain-layer upload and exposes `palette_remap()`; `EditorApp::update` syncs it per frame (try_lock) into the live `dock_tab_viewer.terrain_panel`; both paint call sites write the REMAPPED layer index (raw-palette-id writes removed) and unresolved entries render disabled with tooltip. Prior pass 2026-07-02 v1.3: AstraWeave branded theme as default — palette single-source `ui/palette.rs`, dock chrome unified via `DockLayout::themed_style`, window icon + top-bar brand mark `ui/branding.rs`, splash video re-enabled with first-frame gate reverting the functional half of `1fc266c93`. Feedback pass 2026-07-02: palette re-tinted to neon sky-blue accent over black metallic-flake surfaces; `world_wizard.rs` theme-routed and made a true modal (Foreground order, input-swallowing dim, one-shot raise above HUD overlays — re-raising per frame would cover its own ComboBox popups); dark branded Win11 title bar via `DWMWA_CAPTION_COLOR`/`DWMWA_TEXT_COLOR` in the DWM composition helper. Prior full pass 2026-05-12 v1.2) | | **Status** | Active (mid-campaign — see Owner notes) | -| **Owner notes** | The editor is by far the largest workspace crate: 216 `.rs` files, ~224,584 LoC (including tests), 49 files in `panels/` (48 panel files + `mod.rs`), 41 `PanelType` enum variants (verified 2026-05-12 by reading `panel_type.rs:107-233`), 123 fields on the `EditorApp` god struct (verified 2026-05-12), 18 direct `astraweave-*` path dependencies (verified 2026-05-12 — earlier "24+" claim was wrong), 11 feature flags (`editor-core`, `editor-graphs`, `editor-materials`, `editor-terrain`, `editor-nav`, `editor-sim`, `editor-full`, `profiling`, `fast-alloc`, `terrain-splat-arrays`, `impostor-bake` — earlier "8 features" claim was wrong, list was always correct). Plus 20 `.md` files inside `tools/aw_editor/` itself and 19 `EDITOR_*.md` / `AW_EDITOR_*.md` files under `docs/current/` (verified counts 2026-05-12; earlier figures were estimates). It is mid-campaign on multiple architectural fronts as of `a2474c5b7`. Three load-bearing reference documents already exist that this trace builds on rather than duplicates: `docs/current/EDITOR_BEHAVIORAL_CORRECTNESS_AUDIT.md` (37-fix audit, 14 critical + 18 high findings, 2026-04-04), `docs/current/FIX27_UNIFIED_PIPELINE_CAMPAIGN.md` (7-phase eliminate-dual-pipeline campaign, 2026-04-05), `docs/current/EDITOR_MULTI_TOOL_ARCHITECTURE_CAMPAIGN.md` (Sub-phase 3 in flight as of 2026-05-08, "Round 8 Closure" — the §7.7 "wrapped-component resource identity trap" anti-pattern was elevated from candidate to structural axiom in this campaign). Read those for depth on specific concerns; this trace covers the structural shape. | +| **Owner notes** | The editor is by far the largest workspace crate: 216 `.rs` files, ~224,584 LoC (including tests), 49 files in `panels/` (48 panel files + `mod.rs`), 41 `PanelType` enum variants (verified 2026-05-12 by reading `panel_type.rs:107-233`), 133 fields on the `EditorApp` god struct (awk over `main.rs:295-535` at `401597d0`), 18 direct `astraweave-*` path dependencies (verified 2026-05-12 — earlier "24+" claim was wrong), 11 feature flags (`editor-core`, `editor-graphs`, `editor-materials`, `editor-terrain`, `editor-nav`, `editor-sim`, `editor-full`, `profiling`, `fast-alloc`, `terrain-splat-arrays`, `impostor-bake` — earlier "8 features" claim was wrong, list was always correct). Plus 20 `.md` files inside `tools/aw_editor/` itself and 19 `EDITOR_*.md` / `AW_EDITOR_*.md` files under `docs/current/` (verified counts 2026-05-12; earlier figures were estimates). It is mid-campaign on multiple architectural fronts as of `a2474c5b7`. Three load-bearing reference documents already exist that this trace builds on rather than duplicates: `docs/current/EDITOR_BEHAVIORAL_CORRECTNESS_AUDIT.md` (37-fix audit, 14 critical + 18 high findings, 2026-04-04), `docs/current/FIX27_UNIFIED_PIPELINE_CAMPAIGN.md` (7-phase eliminate-dual-pipeline campaign, 2026-04-05), `docs/current/EDITOR_MULTI_TOOL_ARCHITECTURE_CAMPAIGN.md` (Sub-phase 3 in flight as of 2026-05-08, "Round 8 Closure" — the §7.7 "wrapped-component resource identity trap" anti-pattern was elevated from candidate to structural axiom in this campaign). Read those for depth on specific concerns; this trace covers the structural shape. | --- @@ -41,8 +41,8 @@ A full-featured GUI editor for AstraWeave game content: levels (`LevelDoc` TOML) Per `tools/aw_editor/README.md:1-3`: "A non-programmer friendly GUI tool for creating and editing levels, encounters, and boss fights in AstraWeave." The scope has expanded substantially since that line was written — the README still describes only the level-editing surface, but the actual crate spans visual editing, asset authoring, blueprint design, build management, plugin hosting, performance profiling, and game runtime hosting. The aspirational scope is documented at `tools/aw_editor/EDITOR_ROADMAP_TO_WORLD_CLASS.md` and `tools/aw_editor/INTEGRATION_ROADMAP.md`. **Where it primarily lives:** -- `tools/aw_editor/src/main.rs` — 9,681 lines, contains the `EditorApp` god struct (123 fields verified 2026-05-12 by `awk 'NR==216,/^\}$/' | awk '/^[[:space:]]+(pub )?[a-z_]+: /'`, lines 216-?) and `impl eframe::App for EditorApp` (line 9119). `fn main()` at line 9582. -- `tools/aw_editor/src/lib.rs` — 109 lines, re-export surface for tests/benches. +- `tools/aw_editor/src/main.rs` — 10,409 lines, contains the `EditorApp` god struct (133 fields verified at `401597d0` by `awk 'NR==295,/^\}$/' | awk '/^[[:space:]]+(pub )?[a-z_]+: /'`, lines 295-535) and `impl eframe::App for EditorApp` (line 9617). `fn main()` at line 10211. +- `tools/aw_editor/src/lib.rs` — 115 lines, re-export surface for tests/benches. - `tools/aw_editor/src/tab_viewer/mod.rs` — 8,185 lines, 157 functions. The `egui_dock::TabViewer` impl that translates `PanelType` enum variants to per-panel `.ui()` calls + per-panel state. - `tools/aw_editor/src/panel_type.rs` — 794 lines, the `PanelType` enum with **41 variants** (one per dockable panel) and `PanelCategory` enum with 6 categories (`Scene`, `Assets`, `Debug`, `Tools`, `System`, `Content`). - `tools/aw_editor/src/panels/` — **49 panel files** (one per authoring domain). @@ -75,7 +75,7 @@ The editor is an `eframe`/`egui` application driven by a single per-frame update │ │ eframe wraps the egui Context; calls update() once per redraw request ▼ -[EditorApp::update(ctx, frame)] (main.rs:9119-9120) +[EditorApp::update(ctx, frame)] (main.rs:9617-9618) │ │ 1. Splash screen check (until first frame after splash ends) │ 2. Tutorial overlay check @@ -166,15 +166,15 @@ The editor is an `eframe`/`egui` application driven by a single per-frame update ### Stage-by-stage detail #### Stage 1: Construction (`EditorApp::default` and `EditorApp::new`) -**Files:** `main.rs:425-2635` (Default::default), `main.rs:2636-2742` (new). +**Files:** `main.rs:538-777` (`Default::default`), `main.rs:2699-2823` (`new`). **Role:** Build the god-object with default values, attempt asset manifest load, register plugins, wire panel structs. **Notes:** -- `EditorApp::default` runs first: tries `asset_db.load_manifest("assets/assets.json")` (line 431) — if no manifest exists, starts empty (scanning 10.9 GB / 112K files at startup was prohibitive per inline comment). User must trigger scan via Asset Inspector. +- `EditorApp::default` runs first: tries `asset_db.load_manifest("assets/assets.json")` (line 543) — if no manifest exists, starts empty (scanning 10.9 GB / 112K files at startup was prohibitive per inline comment). User must trigger scan via Asset Inspector. - `EditorApp::new` (called from `fn main` via `eframe::run_native`) does GPU-dependent init: wgpu device, viewport widget creation, splash screen. -- The struct declaration spans `main.rs:216-?` and has 123 fields (verified 2026-05-12 via `awk` field-pattern count over the struct body). Some fields are gated by `#[cfg(target_os = "windows")]` (e.g. `hwnd_cache` at line 417). The `ARCHITECTURAL_AUDIT_REPORT.md:22` (2025-12-22) reported 55+ fields; the count has more than doubled since. +- The struct declaration spans `main.rs:295-535` and has 133 fields (verified at `401597d0` via that awk field-pattern count over lines 295-535). Some fields are gated by `#[cfg(target_os = "windows")]` (e.g. `hwnd_cache` at line 529). The `ARCHITECTURAL_AUDIT_REPORT.md:22` (2025-12-22) reported 55+ fields; the count has more than doubled since. #### Stage 2: Per-frame update entrypoint (`impl eframe::App for EditorApp::update`) -**File:** `main.rs:9119-9120` (impl block at line 9119; `fn update` immediately follows). +**File:** `main.rs:9617-9618` (impl block at line 9617; `fn update` immediately follows). **Role:** The eframe-mandated entry point. Single function but very long — receives `&egui::Context` and `&mut eframe::Frame`, performs the entire frame's logic. **Notes:** - Calls into the `subsystems/` modules (extracted in commit `0de315693`, 2026-04-08) for audio, animation, movement, hotkeys, scene stats. @@ -252,12 +252,12 @@ The editor is an `eframe`/`egui` application driven by a single per-frame update | Term | Definition | Used in | |---|---|---| -| **EditorApp** | The god struct. Owns scene state, all panel state, viewport, runtime, undo stack, dock state, plugin manager, asset DB, settings, dialog flags, cached UI values. 123 fields (verified 2026-05-12). | `main.rs:216-?` | +| **EditorApp** | The god struct. Owns scene state, all panel state, viewport, runtime, undo stack, dock state, plugin manager, asset DB, settings, dialog flags, cached UI values. 133 fields (verified at `401597d0`). | `main.rs:295-535` | | **PanelType** | Enum with 41 variants (one per dockable panel) + 6 category variants. Used as the key for `egui_dock` tab identification. | `panel_type.rs:107-` | | **PanelEvent** | Enum of cross-panel events. Drained per-frame from `EditorTabViewer.take_*_actions()` and dispatched to bridges, services, or other panels. | `tab_viewer/panel_event.rs` | | **EditorRuntime** | Owns the active simulation `App` during Play-in-Editor mode. Holds `RuntimeState` + snapshot for stop-restore. | `runtime.rs:1-1690` | | **EditorSceneState** | The canonical edit-mode world owner (Week 1 work, 2025-09 era). Holds the `World` instance that panels read from / write to during Editing mode. | `scene_state.rs:1-714` | -| **EntityManager** | Independent registry mapping `EntityId: u64` to `EditorEntity` (per-entity transform + selection state). Bridged to `World::Entity: u32` via `entity_id_to_world` at `main.rs:139-150` with overflow check. | `entity_manager.rs` | +| **EntityManager** | Independent registry mapping `EntityId: u64` to `EditorEntity` (per-entity transform + selection state). Bridged to `World::Entity: u32` via `entity_id_to_world` at `main.rs:141-154` with overflow check. | `entity_manager.rs` | | **SelectionSet** | The set of currently-selected entities. Drives gizmo + inspector behavior. | `entity_manager.rs` | | **LevelDoc** | The canonical level-document TOML schema: `{ title, biome, seed, sky, biome_paints, obstacles, npcs, fate_threads, boss }`. | `level_doc.rs` | | **SceneData** | Phase 2.2 scene-save format (RON), distinct from `LevelDoc`. The two coexist (see §6). | `scene_serialization.rs` | @@ -285,11 +285,11 @@ The editor is an `eframe`/`egui` application driven by a single per-frame update - **`World` (live game world) vs `EditorSceneState` (edit-mode owner) vs `EntityManager` (separate registry) vs `SceneData` (serialization format) vs `LevelDoc` (level TOML):** Five distinct representations of "the scene." Per Behavioral Correctness Audit §1.2 line 80: "Cache inconsistency risk" — this is the trap. `World` is what the simulation sees; `EntityManager` is the editor's overlay (per-entity selection, material slots, etc.); `EditorSceneState` is the edit-mode owner; `SceneData` is what `scene_serialization.rs` reads/writes (RON); `LevelDoc` is what the legacy level TOML reads/writes. -- **`EntityId: u64` (EntityManager) vs `Entity: u32` (World):** Bridged by `entity_id_to_world` at `main.rs:139-150` with explicit overflow check that warns and returns `None` if `EntityId > u32::MAX`. Most editor APIs traffic in the `u64` form. +- **`EntityId: u64` (EntityManager) vs `Entity: u32` (World):** Bridged by `entity_id_to_world` at `main.rs:141-154` with explicit overflow check that warns and returns `None` if `EntityId > u32::MAX`. Most editor APIs traffic in the `u64` form. - **`PanelType` (enum, 41 variants) vs Panel structs in `panels/` (49 files):** Most panels have a 1:1 mapping (one `PanelType` variant per panel), but several `panels/*.rs` files do not appear in `PanelType`'s match (e.g., `WorldWizard`, `PluginManagerPanel`, `ThemeManagerPanel`'s in-line variant, `EntityCatalog`). The set of variants is enumerated at `panel_type.rs:109-232`. -- **`tab_viewer/mod.rs::EditorTabViewer` vs `tab_viewer/mod.rs::SimpleTabViewer`:** `EditorTabViewer` is the production tab viewer that holds all panel state. `SimpleTabViewer` (also re-exported at `lib.rs:74`) is a lighter-weight placeholder used for tests / library consumers. +- **`tab_viewer/mod.rs::EditorTabViewer` vs `tab_viewer/mod.rs::SimpleTabViewer`:** `EditorTabViewer` is the production tab viewer that holds all panel state. `SimpleTabViewer` (also re-exported at `lib.rs:77`) is a lighter-weight placeholder used for tests / library consumers. - **`docking_sync` subsystem vs `dock_layout` module vs `dock_panels` module:** Three different things. `subsystems/docking_sync.rs` is the per-frame sync between `DockLayout` and `EditorTabViewer`. `dock_layout.rs` is the persistent layout state + presets. `dock_panels.rs` is the registration table. @@ -333,7 +333,7 @@ The editor is an `eframe`/`egui` application driven by a single per-frame update | Consumer system | Interface | Data | Notes | |---|---|---|---| | Filesystem (`.toml` levels, `.ron` scenes, `.blend` outputs, `.awsv` saves, etc.) | `LevelDoc` TOML write, `SceneData` RON write, package_demos export | Authored content. | Saved via `MenuBar::on_save` → `EditorApp::save_*` family. | -| `aw_game_runtime` binary (`Cargo.toml:122-126`) | Reads the saved scene/level files via `aw_editor_lib::game_project::GameProject` | Standalone game-runner binary at `src/bin/aw_game_runtime.rs` (336 lines, clap-based CLI). | NOT headless — creates a winit window + wgpu device + surface (`aw_game_runtime.rs:91-165`). Earlier description in this doc was incorrect. | +| `aw_game_runtime` binary (`Cargo.toml:147-151`) | Reads the saved scene/level files via `aw_editor_lib::game_project::GameProject` | Standalone game-runner binary at `src/bin/aw_game_runtime.rs` (336 lines, clap-based CLI). | NOT headless — creates a winit window + wgpu device + surface (`aw_game_runtime.rs:91-165`). Earlier description in this doc was incorrect. | | Plugin system (any `EditorPlugin` impl) | `PluginEvent` + plugin context API | Runtime-loaded extensions. | `plugin.rs::PluginManager`. | | Distribution + package_demos | `distribution.rs` + `panels/distribution_panel.rs` | Game-build outputs ready for distribution. | Heavy on cross-crate orchestration. | @@ -369,8 +369,8 @@ The editor has 216 `.rs` files. This map captures the **load-bearing structural | File / Directory | Role | Status | Notes | |---|---|---|---| -| `src/main.rs` | Binary entrypoint + `EditorApp` god struct + 182 impl methods + `impl eframe::App` + `fn main` | Active | 9,681 lines. `EditorApp::default` at line 425; `EditorApp::new` at 2636; `impl eframe::App for EditorApp` at 9119; `fn main` at 9582. 123-field god struct (verified 2026-05-12; flagged at 55+ fields in `ARCHITECTURAL_AUDIT_REPORT.md:22` 2025-12-22). | -| `src/lib.rs` | Library entry; module declarations + re-exports for tests/benches | Active | 109 lines. Allows `aw_editor_lib` to be consumed for testing without compiling the binary. | +| `src/main.rs` | Binary entrypoint + `EditorApp` god struct + 182 impl methods + `impl eframe::App` + `fn main` | Active | 10,409 lines. `EditorApp::default` at line 538; `EditorApp::new` at 2699; `impl eframe::App for EditorApp` at 9617; `fn main` at 10211. 133-field god struct (`main.rs:295-535`, verified at `401597d0`; flagged at 55+ fields in `ARCHITECTURAL_AUDIT_REPORT.md:22` 2025-12-22). `hwnd_cache` is line 529. | +| `src/lib.rs` | Library entry; module declarations + re-exports for tests/benches | Active | 115 lines. Allows `aw_editor_lib` to be consumed for testing without compiling the binary. | | `src/panels/` (49 files) | One file per dockable panel; each implements `Panel` trait + companion `*Action` enum | Active (per-panel: some are stubs, some are production-grade, see audits) | The audit at `EDITOR_BEHAVIORAL_CORRECTNESS_AUDIT.md` Phase 7 enumerates "18 stub PanelEvent handlers" — agents should read that doc for per-panel maturity. | | `src/panels/mod.rs` | Panel trait + re-exports of all 49 panel structs | Active | Defines the cross-panel contract. | | `src/tab_viewer/mod.rs` | `EditorTabViewer` + `SimpleTabViewer` + `egui_dock::TabViewer` impl; 157 functions | Active | 8,185 lines. The central panel-state-holder + dispatch hub. | @@ -423,12 +423,12 @@ The editor has 216 `.rs` files. This map captures the **load-bearing structural | `src/plugin.rs` | `EditorPlugin` trait + `PluginManager` | Active | Phase 5.3 deliverable. | | `src/tutorial.rs` | First-run tutorial walkthrough | Active | 344 lines. | | `src/splash.rs` | Startup splash screen with logo + cinematic video | Active | Uses `mp4` + `openh264` deps from Cargo.toml:94-95. Video playback re-enabled 2026-07 (reverts the functional half of `1fc266c93`): decoder thread `splash-video-decode` spawns at construction; phase 0 advances to video only once the first frame is buffered (capped at `VIDEO_WAIT_CAP_SECS`); video phase ends on stream-end or the 8.5 s cap; skip-on-click preserved. | -| `src/headless.rs` | Headless testing infrastructure | Active (tests) | Exposed via `lib.rs:107`. | +| `src/headless.rs` | Headless testing infrastructure | Active (tests) | Exposed via `lib.rs:113`. | | `src/interaction.rs` | Gizmo interaction helpers (auto-tracking) | Active | Phase 8.1 Week 5 Day 3 deliverable. | | `src/telemetry.rs` | Telemetry collection (`EditorTelemetryEvent` enum: `SelectionChanged`, `GridSettingsChanged`, `GizmoStarted`, `GizmoCommitted`, `GizmoCancelled`) | Active | 615 lines. Routes events through the `tracing` crate (`use tracing::info;` at line 4). Verified — exports `EditorTelemetryEvent` enum + `EDITOR_TELEMETRY` `OnceLock` singleton. Consumed by selection/grid/gizmo paths. | | `src/mutation_tests.rs` | Mutation-resistance test harness | Active (tests) | Test-only module. | | `src/tests_*.rs` (asset_pack, dock_layout, game_project, polish) | Per-module test files | Active (tests) | Test-only modules; total ~440 lines. | -| `src/bin/aw_game_runtime.rs` | Standalone windowed game runner binary | Active (separate bin) | Per `Cargo.toml:122-126`. 336 lines; clap CLI; creates winit window + wgpu surface. First-commit `32eb5a26c` (2026-01-14, "Chore/root level cleanup #169"). Reuses `aw_editor_lib::game_project::GameProject`. | +| `src/bin/aw_game_runtime.rs` | Standalone windowed game runner binary | Active (separate bin) | Per `Cargo.toml:147-151`. 336 lines; clap CLI; creates winit window + wgpu surface. First-commit `32eb5a26c` (2026-01-14, "Chore/root level cleanup #169"). Reuses `aw_editor_lib::game_project::GameProject`. | | `tests/` (~80 files including `wave3_mutation_remediation.rs` at 1213 lines, `workflow_project_lifecycle.rs`) | Integration tests | Active (tests) | | | `tests/common/mod.rs` | Shared L-series relief arithmetic (`min_castable_relief`, `prominence`, `main_grid`) | Active (test support) | NOT a test target — Cargo auto-discovers `tests/*.rs`, not `tests/*/mod.rs`. Included by `mod common;` from `l3c_relief_census.rs` and `l3a_proof.rs` so the CPU census and the GPU perf leg cannot disagree about `h_min` (L.3.C published one derived from a modelled ortho pad the renderer did not use). | | `tests/l3_proof.rs` · `l3a_proof.rs` · `l3c_relief_census.rs` | Terrain-CSM verification harnesses (L.3 → L.3.C-resolution) | Active (tests, `#[ignore]`d GPU) | `l3_proof`: pinned station A/B (byte-identity guarantee) + min-spec perf. `l3a_proof`: camera-MOTION leg (`l3a_boundary_evidence`), CONTINUOUS per-frame leg with per-far-cascade refresh telemetry (`l3b_continuous_flight`), and min-spec survey-framing timing + emitted-fit relief census (`l3c_perf_survey`). `l3c_relief_census`: CPU-only relief distribution + layout pricing. Twin-flight differencing lives in `scripts/l3b/`; exact station diffs in `scripts/l3b/l3_station_diff.py`. | @@ -454,11 +454,11 @@ The editor accumulates substantial historical residue. The Behavioral Correctnes | Abstraction | Files | Status | Disposition | |---|---|---|---| | Five representations of "the scene": `LevelDoc` (TOML) vs `SceneData` (RON) vs `World` (live) vs `EditorSceneState` (edit-mode owner) vs `EntityManager` (overlay) | `level_doc.rs` vs `scene_serialization.rs` vs `astraweave-core::World` vs `scene_state.rs:1-714` vs `entity_manager.rs` | Five coexisting representations | The legacy `LevelDoc` TOML (per `README.md`) was the original scene format. `SceneData` (Phase 2.2, RON-based) is the newer scene-save format. `EditorSceneState` is the edit-mode owner of a `World` instance. `EntityManager` overlays per-entity editor metadata (selection, material slots) on top of `World`. Audit §1.2 flagged this as "cache inconsistency risk" with circular-dep concern. | -| God-struct `EditorApp` (123 fields, 9,681-line main.rs) | `main.rs:216-?` | Acknowledged anti-pattern | Documented as the highest-priority architectural issue in `ARCHITECTURAL_AUDIT_REPORT.md:22` (55+ fields when audited 2025-12-22; verified at 123 fields on 2026-05-12 — more than doubled). Several extractions have occurred: `subsystems/` (5 helpers, commit `0de315693` 2026-04-08), `tab_viewer/` (panel state holder, commit `faf8ef439` 2026-01-13), `ui/` (menu bar etc.), but the core struct retains the bulk of state. | +| God-struct `EditorApp` (133 fields, 10,409-line main.rs) | `main.rs:295-535` | Acknowledged anti-pattern | Documented as the highest-priority architectural issue in `ARCHITECTURAL_AUDIT_REPORT.md:22` (55+ fields when audited 2025-12-22; verified at 133 fields at `401597d0` — more than doubled). Several extractions have occurred: `subsystems/` (5 helpers, commit `0de315693` 2026-04-08), `tab_viewer/` (panel state holder, commit `faf8ef439` 2026-01-13), `ui/` (menu bar etc.), but the core struct retains the bulk of state. | | **§7.7 "wrapped-component resource identity trap" anti-pattern — four distinct instances** | (1) `viewport/engine_adapter.rs` depth target vs `aw_editor`'s `self.depth_texture` (FIXED Real-Fix.A `0f569d212`, 2026-05-07); (2) `astraweave-render::Renderer::terrain_forward.chunks` HashMap vs editor's `terrain_clusters` Vec / `self.models["terrain_cluster_*"]` (FIXED Real-Fix.B `eaaa53433`, 2026-05-07); (3) `TerrainVertex.biome_weights_0/1` vs `material_ids/material_weights` (FIXED Real-Fix.C `ded9a0457`, 2026-05-08); (4) UI material library (22 items) vs splat-build cap (8 items) vs renderer texture-array (8 slots) — Andrew-gate pending decision (d) per `EDITOR_MULTI_TOOL_ARCHITECTURE_CAMPAIGN.md` Round-8-Closure | Multi-layer architectural pattern | Elevated from "candidate" to "structural axiom" by 4-layer evidence in same campaign. The campaign doc proposes elevating this to first-class CLAUDE.md Edit. Each instance has same shape: same logical role represented in two places; bug at the boundary. | | Per-frame mediator code in `main.rs:3833-3877` (legacy) vs `active_tool::Dispatcher` (newer canonical) | `main.rs:3833-3877` vs `active_tool/dispatcher.rs` | Mid-migration | Mediator code currently routes brush input for TerrainPanel (legacy path). Dispatcher routes the same input for the registered ActiveTool (new path). Both run currently. Mediator Removal session deferred (Andrew-gated) per Multi-Tool Architecture campaign §0. | | **Parallel input system in `panels/input_bindings_panel.rs`** (2,511 lines, reimplements 13 input-domain types) | `panels/input_bindings_panel.rs` | Standalone, never drained | Documented at length in `docs/architecture/input.md` §6: the editor defines its own `InputBindingAction`, `InputDevice`, `BindingPreset`, `GamepadButton`, `KeyboardKey`, `MouseButton`, `ActionBinding`, `AxisBinding`, `BindingConflict`, `InputBindingsPanel`, `InputTarget`, `InputTab` types. The editor's `Cargo.toml` does not declare `astraweave-input` as a dep. The panel renders in the dock but its `pending_actions` queue is never drained externally (verified by workspace grep). | -| `EditorTabViewer` (production) vs `SimpleTabViewer` (lighter test/library variant) | `tab_viewer/mod.rs::EditorTabViewer` + `SimpleTabViewer`, both re-exported at `lib.rs:74` | Two viewers in same module | Documented at `tab_viewer/mod.rs:5-9`: "Acts as a bridge between the docking system and the actual panel implementations. It renders panel placeholders and can be extended to render actual panel content." | +| `EditorTabViewer` (production) vs `SimpleTabViewer` (lighter test/library variant) | `tab_viewer/mod.rs::EditorTabViewer` + `SimpleTabViewer`, both re-exported at `lib.rs:77` | Two viewers in same module | Documented at `tab_viewer/mod.rs:5-9`: "Acts as a bridge between the docking system and the actual panel implementations. It renders panel placeholders and can be extended to render actual panel content." | | `MenuActionHandler` trait + `EditorApp` impl at `main.rs:8520` vs in-place menu logic in `ui/menu_bar.rs` | `main.rs:8520` vs `ui/menu_bar.rs` | Indirection layer (intentional) | The trait lets `MenuBar` be unit-tested without `EditorApp`. Not residue — documented architectural choice. Listed here for orientation only. | | `use_docking: bool` field on `EditorApp` (legacy non-docked path preserved) | `main.rs` (EditorApp field) | Fallback path | Pre-docking-system layouts (floating panels) coexist with the docking system. The non-docked path is preserved for fallback but the dock path is the canonical UX. | | Aspirational test artifacts checked into repo | `persistence/aw-save/slot*.awsv` (5 files); `astraweave-persistence-ecs/savegame.bin` | Inadvertent commits | Documented in `docs/architecture/persistence_ecs.md`. The editor doesn't own these but is the most likely producer (via `save_integration` example or `aw_save_cli`). | @@ -467,7 +467,7 @@ The editor accumulates substantial historical residue. The Behavioral Correctnes ### Naming collisions - **`World` (4+ meanings):** `astraweave-core::World` (grid simulation); `astraweave-ecs::World` (the ECS world inside the Play-in-Editor `App`); `WorldPanel` (an editor panel); `WorldWizard` (modal dialog). All four appear in the same `EditorApp` struct. -- **`Entity`:** `astraweave-core::Entity = u32` (live world); `EditorEntity` struct (entity_manager.rs); `EntityId = u64` (entity_manager.rs); `EntityPanel`, `EntityCatalog` (panels). `entity_id_to_world` (`main.rs:139-150`) bridges with overflow check. +- **`Entity`:** `astraweave-core::Entity = u32` (live world); `EditorEntity` struct (entity_manager.rs); `EntityId = u64` (entity_manager.rs); `EntityPanel`, `EntityCatalog` (panels). `entity_id_to_world` (`main.rs:141-154`) bridges with overflow check. - **`Snapshot`:** `EditorRuntime`'s play-stop snapshot; `astraweave-net::Snapshot` (transitively present via render deps?); various per-panel "snapshot" methods. Not in the same scope as cross-imports but confusing in cross-crate discussions. - **`Plugin`:** `EditorPlugin` (editor's extension trait, `plugin.rs`); `astraweave_ecs::Plugin` (ECS Plugin trait used in the runtime); various external plugin systems. The names don't conflict in code but appear in different contexts. - **`State`:** `RuntimeState` (4-state); `EditorSceneState` (the edit-mode `World` owner); `EditorMode` (a 3-state thing called `Mode` not `State`, but reads like one); per-panel `state` fields throughout. The audit's "circular dependencies risk" finding traces here. @@ -475,10 +475,10 @@ The editor accumulates substantial historical residue. The Behavioral Correctnes ### Known cognitive traps -- **Trap:** `EditorApp` has 123 fields including ~15 Windows-specific DWM/HWND fields, ~10 cache-invalidation generation fields, ~5 splash/tutorial/timing fields. Many fields look unused but are referenced from far-off methods in the 9,681-line `main.rs`. - - **What's actually true:** The `#[allow(dead_code)]` on the struct itself (`main.rs:215`) means rustc cannot prove field liveness across the binary surface. The library target (via `lib.rs`) compiles without `dead_code` warnings — per the cleanup comment at `main.rs:1-8`. Searching for usage requires reading `main.rs` end-to-end. +- **Trap:** `EditorApp` has 133 fields including ~15 Windows-specific DWM/HWND fields, ~10 cache-invalidation generation fields, ~5 splash/tutorial/timing fields. Many fields look unused but are referenced from far-off methods in the 10,409-line `main.rs`. + - **What's actually true:** The `#[allow(dead_code)]` on the struct itself (`main.rs:294`) means rustc cannot prove field liveness across the binary surface. The library target (via `lib.rs`) compiles without `dead_code` warnings — per the cleanup comment at `main.rs:1-8`. Searching for usage requires reading `main.rs` end-to-end. -- **Trap:** `entity_id_to_world` silently returns `None` on overflow (`main.rs:139-150`). +- **Trap:** `entity_id_to_world` silently returns `None` on overflow (`main.rs:141-154`). - **Why it's confusing:** It logs a `warn!` but doesn't error — callers must handle the `Option`. With `EntityId: u64` and growing entity counts in stress tests, overflow into the >`u32::MAX` range is theoretically possible. - **What's actually true:** The bridge function is well-tested and the warn-fallback is intentional, but agents who pattern-match `entity_id_to_world(id).unwrap()` will hit a panic at the overflow boundary. @@ -487,7 +487,7 @@ The editor accumulates substantial historical residue. The Behavioral Correctnes - **What's actually true:** Documented design. Edit-mode movement is via gizmos. - **Trap:** `auto_save_to_separate_dir` and `auto_save_keep_count` fields exist on `EditorApp` (Week 7 enhanced auto-save settings), but auto-save behavior was documented as a [NEEDS VERIFICATION] in the audit Phase 6 (silent failures). - - **What's actually true:** Auto-save fires when `auto_save_enabled` is true AND `now - last_auto_save >= auto_save_interval_secs` (`main.rs:9441-9445`). Both Week 7 enhancements are wired through: `auto_save_to_separate_dir = true` routes to `.autosave/` with timestamped filenames (`{base_name}_{YYYYMMDD_HHMMSS}.autosave.scene.ron`, `main.rs:1065-1088`); `auto_save_keep_count` rotation is enforced by `cleanup_old_autosaves` (`main.rs:1114-1170`) which sorts by mtime newest-first and removes everything past index `keep_count`. + - **What's actually true:** Auto-save fires when `auto_save_enabled` is true, the scene is dirty (`is_dirty`), and `last_auto_save.elapsed() > auto_save_interval_secs` (`main.rs:10010-10012`). `session_files::write_autosave` (`session_files.rs:49`) is called from `main.rs:10016`. `auto_save_to_separate_dir = true` routes to `.autosave/` with timestamped filenames (`{base_name}_{YYYYMMDD_HHMMSS}.autosave.scene.ron`, `session_files.rs:63-65`). `auto_save_keep_count` rotation is `cleanup_old_autosaves` (`session_files.rs:96`). `write_autosave` calls it only when `separate_dir` is set (`session_files.rs:81-89`). It sorts by mtime newest-first and removes everything past index `keep_count`. - **Trap:** The viewport widget creation is conditional on a successful GPU device init. If wgpu init fails, `viewport: Option` stays `None` (`main.rs:276`), and the editor runs without a 3D viewport — but most panels assume `viewport` is populated. - **What's actually true:** The fallback path renders panel placeholders. Audit Phase 6 flagged this as a "silent failure" pattern. @@ -504,7 +504,7 @@ The editor accumulates substantial historical residue. The Behavioral Correctnes - **Trap:** `Cargo.toml` declares `default = ["editor-core", "impostor-bake", "fast-alloc", "terrain-splat-arrays"]` (line 17). The `editor-full` feature exists (line 24) but is NOT in default. - **What's actually true:** Default builds include impostor + mimalloc + splat-arrays, but `editor-graphs`, `editor-materials`, `editor-terrain`, `editor-nav`, `editor-sim` (sub-feature flags of `editor-full`) are not enabled. **Verified 2026-05-12:** these sub-feature flags appear ONLY in `Cargo.toml` — `grep -rn "editor-graphs\|editor-materials\|editor-terrain\|editor-nav\|editor-sim\|editor-full"` across `tools/aw_editor/` returns no `.rs` file hits. No `#[cfg(feature = "editor-*")]` gates exist. They are dormant flags. -- **Trap:** The `aw_game_runtime` binary (`src/bin/aw_game_runtime.rs`) is built alongside `aw_editor` but is a separate executable. Per `Cargo.toml:122-126`: `test = false, bench = false`. +- **Trap:** The `aw_game_runtime` binary (`src/bin/aw_game_runtime.rs`) is built alongside `aw_editor` but is a separate executable. Per `Cargo.toml:147-151`: `test = false, bench = false`. - **What's actually true:** When users `cargo build -p aw_editor`, both binaries compile. Scope verified from `src/bin/aw_game_runtime.rs:1-15` doc comment: "standalone game runtime binary that runs games created with the AstraWeave Editor. It loads the game project configuration, initializes the engine systems, and runs the game loop." 336 lines; `clap`-based CLI with `--project`, `--dev`, `--width`, `--height`, `--fullscreen`, `--skip-splash` flags. Imports `aw_editor_lib::game_project::GameProject` (so it reuses the editor's project schema). NOT headless — it creates a winit window with wgpu surface. ### Temporary state — REVERT-BEFORE-v1 (owned by terrain beat T.3) @@ -565,7 +565,7 @@ The editor has accumulated dozens of small architectural decisions over 8 months - **Context:** The editor needs to test-run authored content; users may want to ship games separate from the editor. - **Decision:** Compile two binaries from the same crate. The game runtime gets `src/bin/aw_game_runtime.rs`; the editor is at `src/main.rs`. The runtime reuses `aw_editor_lib::game_project::GameProject` for project loading so editor and runtime stay schema-aligned. - **Alternatives considered:** [Reasoning not recovered from available sources] -- **Consequences:** Both binaries compile on every `cargo build -p aw_editor`. Game runtime has `test = false, bench = false` so doesn't slow tests. The runtime is windowed (winit + wgpu), not headless — for headless testing the crate exposes `src/headless.rs` instead. +- **Consequences:** Both binaries compile on every `cargo build -p aw_editor`. Game runtime has `test = false, bench = false`, so a default `cargo test` skips its harness. `cargo test --bins` still builds that harness. The harness has no tests. The runtime is windowed (winit + wgpu), not headless — for headless testing the crate exposes `src/headless.rs` instead. ### Decision: `fast-alloc` (mimalloc) in default features - **Date:** 2026-04-17 per Cargo.toml:13-16 comment ("the 2026-04-17 mimalloc experiment"). @@ -627,26 +627,26 @@ The editor has accumulated dozens of small architectural decisions over 8 months | # | Invariant | Checkable? | Enforced by | |---|---|---|---| -| 1 | `EntityManager.entity_id < u32::MAX` for entity IDs that need to be passed to `astraweave-core::World` | Yes (runtime) | `main.rs:139-150` `entity_id_to_world` — returns `None` and warns on overflow. | +| 1 | `EntityManager.entity_id < u32::MAX` for entity IDs that need to be passed to `astraweave-core::World` | Yes (runtime) | `main.rs:141-154` `entity_id_to_world` — returns `None` and warns on overflow. | | 2 | `RuntimeState` transitions follow the state machine at `runtime.rs:42-60` | Yes (compile-time guards + tests) | `RuntimeState::can_transition_to` method enforces; tests in `runtime.rs`. | | 3 | Movement scripts only tick when `runtime.is_playing()` | Yes | `subsystems/audio_animation.rs:92-96` early-return. | | 4 | `editor_mode` is updated in lock-step with `runtime_state` transitions: roughly `Edit` ↔ `RuntimeState::Editing`; `Play` ↔ `RuntimeState::{Playing, SteppingOneFrame}`; `Paused` ↔ `RuntimeState::Paused`. Naming differs between the two enums but the two transition together. | Yes (by-call-site convention; no compile-time assertion) | `main.rs:2370, 2390` set `EditorMode::Play` alongside runtime play-start; `main.rs:2402, 2451` set `EditorMode::Paused`; `main.rs:2423` sets `EditorMode::Edit` on stop. No central `debug_assert!` enforces consistency at transition points, but every transition call site updates both. | | 5 | `UndoStack` push must happen in the same `EditorApp::update` frame as the mutation | Yes (by construction) | Commands are pushed inside event-handler arms in `tab_viewer/mod.rs` and `main.rs`. | | 5b | Play mode records the integer 60 Hz step count of every `tick` / `step_frame` call, including zero. Replay reads `recorded_fixed_steps()` instead of re-deriving steps from wall-clock `dt`. `Instant` in this file measures frame cost only | Yes | `runtime.rs` `run_fixed_steps`; test `play_session_records_fixed_step_counts` | -| 6 | Auto-save triggered only when `auto_save_enabled` AND `now - last_auto_save >= auto_save_interval_secs` | Yes | `main.rs:9441-9445` (check inside `EditorApp::update`); fires `perform_auto_save` at `main.rs:1063-1111`. | +| 6 | Auto-save runs only when `auto_save_enabled`, `is_dirty`, and `last_auto_save.elapsed() > auto_save_interval_secs` | Yes | `main.rs:10010-10012` checks the flags and the interval; `session_files::write_autosave` at `session_files.rs:49` is called from `main.rs:10016`. | | 7 | `viewport: Option` is `None` only if wgpu init failed at startup | Yes | `main.rs:276` field type. `EditorApp::new` populates it on success. | | 8 | `egui` version across the editor matches `egui-wgpu = 0.32.0` | Yes (compile-time) | Cargo version resolution. `egui_kittest` is not linked. | | 9 | `PanelType::all()` returns all 41 variants and `PanelType::in_category(c)` partitions cleanly | Yes (tests) | `panel_type.rs:505` `all`; `panel_type.rs:496` `in_category`. | | 10 | `EditorAudioBridge` panel-actions are drained per frame via `tick_audio_subsystem` | Yes | `subsystems/audio_animation.rs:10-34`. | | 11 | The 49 panels in `panels/` each implement the `Panel` trait declared in `panels/mod.rs` | Yes (compile-time) | Trait bound checked by rust compiler when each panel is constructed. | -| 12 | `EditorApp` is `eframe::App` | Yes (compile-time) | `main.rs:9119` `impl eframe::App for EditorApp`. | -| 13 | The editor binary `aw_editor` lives at `src/main.rs`; the runtime binary at `src/bin/aw_game_runtime.rs` | Yes | `Cargo.toml:116-126`. | -| 14 | `#![forbid(unsafe_code)]` is NOT declared at the crate root | Yes (compile-time) | Editor uses raw-window-handle, wgpu raw resources, and Windows-specific HWND access (`main.rs:417`); cannot forbid unsafe. | +| 12 | `EditorApp` is `eframe::App` | Yes (compile-time) | `main.rs:9617` `impl eframe::App for EditorApp`. | +| 13 | The editor binary `aw_editor` lives at `src/main.rs`; the runtime binary at `src/bin/aw_game_runtime.rs` | Yes | `Cargo.toml:142-151`. | +| 14 | `#![forbid(unsafe_code)]` is NOT declared at the crate root | Yes (compile-time) | Editor uses raw-window-handle, wgpu raw resources, and Windows-specific HWND access (`hwnd_cache` at `main.rs:529`, `set_window_class_cursor` at `main.rs:2491`, `force_window_composition` at `main.rs:2537`); cannot forbid unsafe. | | 15 | The `library` target (`lib.rs`) compiles with zero `dead_code` warnings | Yes (compile-time) | Per `main.rs:1-7` cleanup-comment claim; the binary target uses targeted allows. | | 16 | Plugin events go through `PluginManager`, not direct trait calls | Yes | `plugin.rs::PluginManager`. | -| 17 | Auto-save snapshot count is bounded by `auto_save_keep_count` field | Yes (runtime, when `auto_save_to_separate_dir = true`) | `cleanup_old_autosaves` (`main.rs:1114-1170`) sorts `.autosave/` entries matching `{base}_*.autosave.scene.ron` by mtime newest-first and `fs::remove_file`'s every entry past index `auto_save_keep_count`. Only invoked when separate-dir mode is on (`main.rs:1101-1103`); same-path-overwrite mode trivially keeps 1 file. | +| 17 | Auto-save snapshot count is bounded by `auto_save_keep_count` field | Yes (runtime, when `auto_save_to_separate_dir = true`) | `cleanup_old_autosaves` (`session_files.rs:96`) sorts `.autosave/` entries matching `{base}_*.autosave.scene.ron` by mtime newest-first and `fs::remove_file`s every entry past index `auto_save_keep_count`. `write_autosave` (`session_files.rs:49`) calls it only when `separate_dir` is set (`session_files.rs:81-89`). Same-path-overwrite mode keeps 1 file. | | 18 | The lock file (`lock_file_path` field) prevents concurrent editor instances on the same project | Yes (runtime) | `main.rs` lock-file creation + check (Week 7 Day 5 crash recovery). | -| 19 | Production-path `.unwrap()` count remains low. Audit baseline was 110+; closed by Wave-3 mutation remediation campaign (`tests/wave3_mutation_remediation.rs`). Verified 2026-05-12: **only ~12 `.unwrap()` calls remain before the first `#[cfg(test)]` boundary across `tools/aw_editor/src/`** — distributed as `mutation_tests.rs` (8, itself a test-harness module), `terrain_integration.rs` (3), `runtime.rs` (1). Zero unwraps in the 9,681-line `main.rs`. | Yes (per-commit measurable) | `grep -c '\.unwrap()' file` + `#[cfg(test)]` boundary heuristic; CI lint `unwrap_used = "allow"` per Cargo.toml:9-10 (test code uses unwrap extensively for clarity). | +| 19 | Production-path `.unwrap()` count remains low. Audit baseline was 110+; closed by Wave-3 mutation remediation campaign (`tests/wave3_mutation_remediation.rs`). Verified 2026-05-12: **only ~12 `.unwrap()` calls remain before the first `#[cfg(test)]` boundary across `tools/aw_editor/src/`** — distributed as `mutation_tests.rs` (8, itself a test-harness module), `terrain_integration.rs` (3), `runtime.rs` (1). Zero unwraps in the 10,409-line `main.rs`. | Yes (per-commit measurable) | `grep -c '\.unwrap()' file` + `#[cfg(test)]` boundary heuristic; CI lint `unwrap_used = "allow"` per Cargo.toml:9-10 (test code uses unwrap extensively for clarity). | | 20 | The editor accent color rides `Visuals::hyperlink_color` for ALL themes — call sites read it via `ui::palette::accent(visuals)` and never hard-code teal (or any accent) inline. | Yes (greppable) | `ui/palette.rs` routing conventions header; consumers in dock_layout, toolbar, tab_viewer, main.rs. | | 21 | `ui::palette::astraweave_visuals()` never sets `Visuals::override_text_color` — doing so flattens the weak/faint text tiers and severity colors. (`CustomColors::to_visuals()` DOES set it; that is Custom-theme behavior, not a bug.) | Yes (unit test) | `ui/palette.rs` test `astraweave_visuals_never_overrides_text_color`. | | 22 | Perf/FPS/memory indicator tier thresholds (16.67/33.33 ms frame budget; ≥55/≥30 FPS; <50/<80 % memory) are functional semantics, not styling — restyles may remap the colors (SUCCESS/WARNING/ERROR palette constants) but must not alter the thresholds. | Yes (guard comments at each site) | `viewport/toolbar.rs` histogram, `ui/status_bar.rs` `show_fps`/`show_resource_usage`, `main.rs` top-bar FPS. | @@ -708,9 +708,10 @@ The editor is performance-sensitive: many panels render every frame, the viewpor - **Mutation testing**: `tools/aw_editor/src/mutation_tests.rs` (test-only module) + 16+ `tests/mutation_resistant_*.rs` integration suites + `tests/wave3_mutation_remediation.rs`. Per `tools/aw_editor/AW_EDITOR_MUTATION_VULNERABILITY_REPORT.md` and `docs/current/EDITOR_MUTATION_TESTING_VULNERABILITY_REPORT.md`, the editor has dedicated mutation-resistance analysis. - **Benchmarks**: `benches/gizmo_benchmarks_simple.rs` + `benches/editor_performance.rs` (Cargo.toml:102-110). Run via `cargo bench -p aw_editor`. - **CI**: - - `.github/workflows/aw-editor-tests.yml` — verified present. - - `.github/workflows/editor-ci.yml` — verified present. -- **Headless testing infrastructure**: `src/headless.rs` (re-exported at `lib.rs:107`). + - A pull request that is not docs-only, and whose affected set is the full workspace or at least one package, runs `cargo test --locked -p aw_editor --all-features --bins` in `.github/workflows/ci.yml`, job `Test (ubuntu, build archive)`. The `PR Rust checks` job needs that job. Ruleset enforcement is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). The step has no `continue-on-error`, and the job has none. The archive still passes `--exclude aw_editor`. `--bins` builds every bin harness, including `aw_game_runtime` (`test = false` at `Cargo.toml:150`). That harness has no `#[test]`, so it runs 0 tests. Cargo 1.89 does not skip `test = false` for `--bins`. On [run 44916883830](https://github.com/lazyxeon/AstraWeave/actions/runs/44916883830/job/136885744997) the log runs `src/bin/aw_game_runtime.rs` and reports `0 passed`, after `3767 passed` for `aw_editor`. At `401597d0` the harness is 3,767 tests, including the library modules `main.rs` redeclares, not only `recovery_tests` (`main.rs:10341`) and `voxel_tools` (`main.rs:93`). + - `.github/workflows/aw-editor-tests.yml` runs `cargo test -p aw_editor --all-features --bin aw_editor` on Ubuntu, Windows, and macOS. That step has no `continue-on-error`. The workflow is not on `pull_request`. It runs on push to `main` when `tools/aw_editor/**`, `astraweave-core/**`, or the workflow file changes, on the `35 6 * * *` schedule, and on `workflow_dispatch`. The `test` job keeps step-level `continue-on-error` on `--lib`, integration, fmt, and clippy. The `coverage` job keeps it on `Generate Coverage Report` and `Upload Coverage to Codecov`. `docs/current/CI_ARCHITECTURE.md:34`, `:44`, `:51`, and `:66` record that schedule and the archive-job step. + - `.github/workflows/editor-ci.yml` runs the same bin command on Ubuntu. That step has no `continue-on-error`, and the job has none, so fmt, `clippy -D warnings`, `cargo check`, `--lib`, the headless smoke tests, and llvm-cov fail the workflow. It is not on `pull_request`. It runs on push to `main` when `tools/aw_editor/**`, the workflow file, `Cargo.toml`, `Cargo.lock`, or `llvm-cov.toml` changes, on the `50 6 * * *` schedule, and on `workflow_dispatch`. +- **Headless testing infrastructure**: `src/headless.rs` (re-exported at `lib.rs:113`). - **Headless egui frames** (`tests/ui_automation_smoke.rs`, `tests/ui_menu_interactions.rs`, `tests/common/egui_click.rs`): paint `ViewportToolbar` and `MenuBar` on a persistent `egui::Context`. Clicks are `RawInput` pointer events at text rects from the previous frame. Covered: Grid toggle, shading combo → Wireframe, Grid Snap `2.0`, File → New, Edit → Undo, Edit → Group (and Group with one entity selected does not fire). `egui_kittest` is not a dependency. - **Audit-driven validation**: The Behavioral Correctness Audit (37 fixes from `EDITOR_BEHAVIORAL_CORRECTNESS_AUDIT.md`) and the Multi-Tool Architecture campaign (Sub-phase 3 instrumentation rounds with megabyte-scale `brush-dbg-r*.txt` log files) constitute a runtime-evidence validation regime alongside unit tests. @@ -724,7 +725,7 @@ The editor accumulates open questions at a much higher rate than smaller systems ### From `ARCHITECTURAL_AUDIT_REPORT.md` (2025-12-22) -- **God-struct refactor.** `EditorApp` 55+ → 123 fields (verified 2026-05-12). Should this be extracted into `SceneManager`, `SelectionService`, `AssetService`, `ToolService` per audit §1.1 lines 61-67? The audit recommends; no campaign has been launched for this. Decisional — Andrew's call. +- **God-struct refactor.** `EditorApp` 55+ → 133 fields (verified at `401597d0`). Should this be extracted into `SceneManager`, `SelectionService`, `AssetService`, `ToolService` per audit §1.1 lines 61-67? The audit recommends; no campaign has been launched for this. Decisional — Andrew's call. - ~~**Mutex poisoning in `file_watcher.rs`.** 5 `.lock().unwrap()` calls flagged.~~ **CLOSED 2026-05-12 by deep-investigation pass.** All 5 sites now use `.lock().unwrap_or_else(|p| p.into_inner())` for graceful poison recovery (`file_watcher.rs:363, 375, 388, 398, 424`). Resolution lives in §2 Stage 11 and §5 file_watcher row. - ~~**110+ `unwrap()` calls in production code.**~~ **CLOSED 2026-05-12 by deep-investigation pass.** Audit baseline was 110+. Verified production-path count is now ~12 (`mutation_tests.rs:8` — itself a test-harness module; `terrain_integration.rs:3`; `runtime.rs:1`). Zero in `main.rs`. Resolution lives in §8 Invariant 19. Methodology: counted lines before the first `#[cfg(test)]` boundary per file across all 49 unwrap-containing files in `tools/aw_editor/src/`. Decisional residue: whether the 3 `terrain_integration.rs` and 1 `runtime.rs` unwraps deserve `.context()`-wrap is a separate code-quality call. @@ -752,7 +753,7 @@ The editor accumulates open questions at a much higher rate than smaller systems - **`editor-full` feature flag (and sub-features `editor-graphs` / `editor-materials` / `editor-terrain` / `editor-nav` / `editor-sim`).** Should these be deleted or wired? Decisional — Andrew's call. **Factual context closed 2026-05-12:** these sub-feature flags appear ONLY in `Cargo.toml` (lines 19-24) — no `.rs` file references `#[cfg(feature = "editor-*")]` for any of them. They are dormant. The factual sub-question "whether any code checks these flags" is fully resolved (no). - **Aspirational docs proliferation.** 20 `.md` files inside `tools/aw_editor/` (verified 2026-05-12) + 19 files in `docs/current/EDITOR_*` / `AW_EDITOR_*` (verified 2026-05-12). Should some be archived into `docs/journey/` per CLAUDE.md documentation organization rules? Decisional — Andrew's call. - ~~**The `astract` UI library dependency** (`Cargo.toml:67`, path `../../crates/astract`). What is the scope of this library vs the rest of the editor's egui usage?~~ **CLOSED 2026-05-12 by deep-investigation pass.** `astract` is genuinely used (not just re-exported). Resolution lives in §4 upstream table; usage sites cataloged: `panels/animation.rs:11` (animation::*), `panels/charts_panel.rs:15` (charts::*), `panels/advanced_widgets_panel.rs:1` (advanced::*), `panels/entity_panel.rs:19` (prelude::*), `panels/graph_panel.rs:1` (graph::*), `panels/performance_panel.rs:5` (widgets::*), `tests/wave2_animation_easing_tests.rs:10` (animation::*). Introduced 2025-11-04 commit `7a5fcab74`. -- ~~**`telemetry.rs`** (re-exported at `lib.rs:109`). What does it collect, and where does it go?~~ **CLOSED 2026-05-12 by deep-investigation pass.** Resolution lives in §5 telemetry row. Collects 5 event types via `EditorTelemetryEvent` enum (`SelectionChanged`, `GridSettingsChanged`, `GizmoStarted`, `GizmoCommitted`, `GizmoCancelled`); routes through `tracing` (`use tracing::info;` at `telemetry.rs:4`); singleton via `OnceLock`. No remote endpoint. +- ~~**`telemetry.rs`** (re-exported at `lib.rs:115`). What does it collect, and where does it go?~~ **CLOSED 2026-05-12 by deep-investigation pass.** Resolution lives in §5 telemetry row. Collects 5 event types via `EditorTelemetryEvent` enum (`SelectionChanged`, `GridSettingsChanged`, `GizmoStarted`, `GizmoCommitted`, `GizmoCancelled`); routes through `tracing` (`use tracing::info;` at `telemetry.rs:4`); singleton via `OnceLock`. No remote endpoint. ### Hot-path / performance questions @@ -803,7 +804,7 @@ Three found in one diagnostic session; all are Integration-Completeness §3 viol 1. **The editor is massive.** Don't try to hold it all in your head. Use this trace as the structural map and dive into the relevant `panels/.rs` or subdirectory only for the specific concern at hand. -2. **`EditorApp` is the god struct.** Adding state means adding a field to a 123-field struct (verified 2026-05-12). Per audit §1.1, extraction is a multi-month effort; in the meantime, follow the existing pattern. +2. **`EditorApp` is the god struct.** Adding state means adding a field to a 133-field struct (verified at `401597d0`). Per audit §1.1, extraction is a multi-month effort; in the meantime, follow the existing pattern. 3. **`PanelType` adding/removing has 4-5 sites to touch** (enum, helpers, dock_panels, tab_viewer match, sometimes `EditorApp` field). Use existing panels as templates. diff --git a/docs/architecture/net_ecs.md b/docs/architecture/net_ecs.md index cc61969b30..5b30fb5b36 100644 --- a/docs/architecture/net_ecs.md +++ b/docs/architecture/net_ecs.md @@ -30,7 +30,7 @@ last_verified_commit: 6b571a58 | **Last verified date** | 2026-10-29 | | **Status** | Active (mixed: production-grade standalone binary; dormant ECS Plugin layer). **Standalone-trio input signing is real and enforced:** client and server both compute HMAC-SHA256 over the canonical `aw-net-proto` signing surface; the server verifies FIRST (before any per-player state mutation) and kicks by default on failure. The historical `sign16`/XOR-vs-HMAC mismatch is RESOLVED (Net-Trio-Remediation, see revision 1.3). | | **Revision history** | 1.18 (2026-10-29): Verified at `6b571a58`. `MAX_PLAYERS_PER_ROOM` is 4 (`lib.rs:45`). `try_seat` (`:70-77`) checks the cap and inserts through `new_player` (`:47-60`, `tokens: BUCKET_SIZE` at `:56`) under the caller's `rooms` lock. `FindOrCreate` calls it before that lock drops (`:590`) and starts `spawn_room_tick` only for a room this call opened (`:602-604`). `JoinRoom` calls `try_seat` at `:649` and sends `ProtocolError` `"room full"` at `:686` with no insert. `FindOrCreate` binds `PlayerMembership` after the choosing lock drops (`:639-644`). `JoinRoom` seats and binds under its own lock (`:646-662`). Both bind before `MatchResult` (`:697`). Regression: `net/aw-net-server/tests/room_cap.rs`. Line cites in 1.15–1.17 describe `0a2d93ea` and earlier. 1.17 text is unchanged. 1.17 (2026-10-29): Verified at `0a2d93ea`. A drop leaves the window when its age is at least `DROP_WINDOW` (`lib.rs:847`, `>=`). `decode_msg` in the select loop is `:686`. `acceptor.accept` is `:401`. The room scan is `:521-522`. `tls_enabled: true` is `:163`. `snap_tx` is created at `:528` and `spawn_room_tick` is `:544-546`. `PlayerMembership::drop` is `:449-458`. Protocol mismatch is `:485-494`. The non-Hello `ProtocolError` is `:496-505`. `Codec::PostcardLz4` is `:318`. `compressed: true` is `:799`. Line numbers inside the 1.14 sentence describe that revision. 1.16 text is unchanged. 1.16 (2026-10-29): Verified at `0a2d93ea`. Cite correction on the 64/s server. `handle_socket` is `:472-744` and `handle_socket_tls` is `:461-469`. `sled::open` is `:313-314`, default `db_path` is `:166`, and `AppState.db` is `#[allow(dead_code)]` at `:254-255`. `load_certs` is `:263`, `load_private_key` is `:270`, and the generation-script warning is `:360`. `accept_loop_tls` is `:390` (`accept_hdr_async` `:409`) and `accept_loop_plain` is `:423` (`:428`). `HelloAck` is `:483`. The player insert is `:588-601`, `MatchResult` is `:631-638`, and `JoinAccepted` is `:639-647`. `verify` is `:948`. Warn charges and does not apply (`:956-958`). Text and Pong are charged (`:729`). `Player` is `:215-231`, `Room` is `:234-248`, and `AppState` is `:251-260`. `expired_drops_leave_the_window_and_one_more_stays_open` returns Kick if the drop-window `pop_front` is removed. 1.15 text is unchanged. 1.15 (2026-10-29): Verified at `4e2e7352`. The bucket refills at 64/s with capacity 64, and a new player starts full (`lib.rs:808-809`, insert `:597`). InputFrame, protocol Ping, Ack, Hello, FindOrCreate, JoinRoom, undecodable binary, WebSocket Ping, Text, and Pong are charged. WebSocket Close is not. HMAC verify runs before any charge (`:944-966`). Kick returns before a charge. Warn charges a bad tag and does not apply it (`:956-958`). Thirty-two unpaid messages inside one second close 1008 (`:813-814`, `:853`). `RateLimited` is not sent. A paid WebSocket Ping is one Pong; a dropped Ping still emits the Pong tungstenite queued while parsing. `send_policy_close` (`:881`) drains before and after the Close. `prequeued_frames_advance_exactly_one_tick_per_period` keeps the socket readable and requires `server_tick` to step by 1. Putting `ws.next()` first under `biased` (`:665`) delivered 1 snapshot in 500 ms. `room.tick += 2` and `room.tick *= 1` fail that step. Removing `biased` skipped a tick on 6 of 8 two-second runs and on 5 of 8 half-second runs; one window does not promise the skip. 1.14 (2026-10-29): Verified at `2b3347ae`. Server bytes are still `f931c184`. Invariant 9's ready-socket case sends one protocol Ping every 20 ms from its own task. Ping is uncharged here (`lib.rs:821-823` sends `Pong` and leaves the bucket alone). The bucket refills at 8/s and charges only `InputFrame` (`:795-797`). 50/s was picked to fit #526's 64/s refill and to stay shorter than `tick_dt`, so a fresh per-connection `sleep` is cancelled. Measured against this server's 8/s refill, 50/s would be over the limit if Ping were charged. Fewer than half the due snapshots in 500 ms fails `paid_frame_inside_limit_still_receives_snapshots`. Restoring the biased `select!` with a fresh `sleep(tick_dt)` delivered 1 snapshot in 500 ms, three runs out of three. One ping per tick on the same task still receives snapshots. 1.13 (2026-10-29): Verified at `74a9ef0b`. Server bytes are still `f931c184`. Invariant 9's ready-socket case sends WebSocket text, which this server does not charge, so a frame is ready on every poll. Fewer than half the due snapshots in 500 ms fails `text_flood_still_receives_snapshots`. One protocol Ping per tick also receives snapshots. 1.12 (2026-10-29): Verified at `f931c184`. One `spawn_room_tick` (`lib.rs:693-712`) publishes snapshots for a room. `FindOrCreate` starts it once (`:519`). `build_snapshot` (`:714-746`) still increments `room.tick` once per call (`:720`), and only that owner calls it. The connection selects `snaps.changed()` first under `biased` (`:638`). `Room` carries `snap_tx` (`:223-225`, struct `:212-226`). Four connections advance `server_tick` once per period. Regression: `net/aw-net-server/tests/room_tick_owner.rs`. Line cites in 1.11 describe the per-connection `sleep` at `de6f2725`.

1.11 (2026-10-28): Verified at `de6f2725`. Plain and TLS sessions share `handle_socket`. `handle_socket_tls` delegates to it. `PlayerMembership` removes the player, and an empty room, on every exit from that handler, including a failed `MatchResult` or `JoinAccepted` send. The trailing cleanup block, `send_tls`, `recv_tls`, and `on_client_msg_tls` are gone. Line cites in 1.10 describe the duplicated handlers at `28ef548c`.

1.10 (2026-10-28): Line cites were read against main 28ef548c. HelloAck and JoinAccepted are not the same lines. The player insert happens before either send. Warn writes last_input_seq and last_seen only while the token bucket stays non-negative. The client TLS feature is rustls-tls-native-roots. spawn_server refuses the published key outside debug and test builds. --sig-failure-policy parses on every build.

1.9 (2026-10-28): A release server does not see the client's key. A published-key client joins; the first InputFrame is Close 1008 under Kick, and under --sig-failure-policy warn the connection can stay up after a bad tag (see 1.10 for bucket-gated last_input_seq/last_seen). A debug server keeps dev_default() when --shared-key-hex is absent. The client TLS feature is rustls-tls-native-roots. Checked against main b6f6c654.

1.8 (2026-10-27): `decode_msg` for `Codec::Bincode` uses `standard().with_limit::()` (4 MiB). The parent `99382af7` uses `standard()` with no limit, so a length prefix allocates before the payload bytes exist. The LZ4 declared-size cap is unchanged. 1.7 (2026-10-16): `astraweave-net-ecs` opts into `tokio` feature `net`. The workspace dependency does not enable it.

1.6 (2026-10-15): `aw-net-server` uses rustls 0.23 with the ring provider. Certificate PEM is parsed with `rustls-pki-types`.

1.5 (2026-10-15): `/healthz` and `/regions` require `ServerConfig.admin_token` as a bearer token. `None` rejects every admin request. The listener still binds so `RunningServer.http_addr` stays valid. CLI flag `--admin-token`. 1.4 (2026-10-15): `ServerConfig::default` binds `127.0.0.1`. `spawn_server` refuses the published dev signing key outside debug and test builds. `decode_msg` rejects an LZ4 declared output above 4 MiB. 1.3 (2026-06-10): **Net-Trio-Remediation closeout.** The standalone trio's signature defect — client signed with the XOR `sign16` (16-byte tag) while the server verified HMAC-SHA256 (32-byte tag), so every verification failed and the server only `warn!`ed — is FIXED and ENFORCED. `aw-net-proto` now exposes a canonical signing surface (`SigningKey` with a private 32-byte field + redacted `Debug`; `sign`/`verify` (constant-time via `Mac::verify_slice`); `hmac_sha256`; `input_frame_sig_payload(seq, tick_ms, blob)`; `SIG_LEN = 32`). The `sign16` XOR stub, the `SessionKey` type, and the `session_key_hint` fields on `MatchResult`/`JoinAccepted` are DELETED; `InputFrame.sig` is now `[u8; 32]`. Both client (sign) and server (verify) build the MAC'd bytes via the single shared `input_frame_sig_payload`. The server is now lib+bin (`aw-net-server/src/lib.rs` ~1080 lines holds all logic; `src/main.rs` is a thin arg-parse → `run_server`). Verification runs FIRST in both plain and TLS handlers and applies `SignatureFailurePolicy { Kick (DEFAULT), Warn }`: Kick sends a WebSocket Close (code 1008) and routes the disconnect through the existing cleanup path; Warn retains legacy log-and-continue. Regression net: 104 tests (proto 59, server 41 across families 1-5 + w2b_fix1, client 4); a §5 adversarial refute pass ran and CONVERGED. Commit ledger: `561b20957` (W.1 canonical HMAC; stub deleted), `79424389e` (W.2.a client adopts), `066cd6cfd` (W.2.b server verifies + policy + lib/bin split), `9a3fc94e3` (W.2.b-fix1 graceful unknown-room + cleanup-preserving snapshot path), `7029d7d7f`/`a2b494942`/`0e702738e`/`68a9a1936` (W.3.1-3.4 test families 1-4), `420a6f61b` (W.5.1 SigningKey encapsulation + RFC 4231), `2955cd14c` (W.5.2 TLS test family), `eb9977b88` (W.5.3 S2C trust note). Known deliberate boundaries (NOT open defects): replay protection / nonces / sequence-number freshness is not implemented (HMAC proves authenticity, not freshness — a captured valid frame can be replayed); server→client messages are not signature-verified (authoritative-server asymmetric trust — a shared symmetric key cannot meaningfully authenticate S2C); the shipped client binary over TLS is untested (rustls cert validation rejects the self-signed dev cert — a cert-validation concern), though the server's TLS verify/kick path IS now tested. Full audit: `docs/audits/net_trio_signature_remediation_findings_2026-06.md`.

1.2 (2026-05-12): Deep investigation pass. Enriched §11 Open Questions 1, 4, 8, 9 with comprehensive factual context. Recovered creation commit for `astraweave-net-ecs` dep in `astraweave-stress-test` (commit `08befc6ec` — same as net-ecs's own birth commit). Verified Q8 dual-TLS-version situation factually via `Cargo.lock` (both `tokio-rustls 0.25.0` and `tokio-rustls 0.26.4` are present) and via `cargo tree` (0.26 comes from reqwest→hyper-rustls used by many crates including `astraweave-llm`, `astraweave-assets`; 0.25 is exclusive to `aw-net-server`). Q4 factual finding: empty `entity_states: HashMap::new()` was present from the crate's birth commit `08befc6ec` (2025-10-01) — stub from day one. Resolved the last `[INFERRED]` marker (§5 TLS_IMPLEMENTATION_SUMMARY.txt content). Added new §6 row: a third copy of `lib.rs`-like content exists at `archive/temp_files/temp/temp_lib.rs` (a `use aw_net_proto` archive).

1.1 (2026-05-12): Verification pass. Corrected §2 Stage 6 HMAC mechanism — `hmac::verify_slice` (via `digest-0.10.7/src/mac.rs:168-179`) strict-rejects any tag length ≠ `OutputSize`; the previous `[INFERRED]` "truncated comparison" claim was wrong. The real mechanism: `Sha256::OutputSize == 32`, sig is 16 bytes, so `verify_slice` returns `MacError` immediately on length mismatch — **all client signatures fail length validation before any byte comparison happens**. Resolved §7 Decision 5 Date marker — HMAC verification landed in commit `88434f3a2` (2025-11-18, "security: fix critical vulnerabilities in network server (Priority 1)"). Resolved §7 Decision 7 Date marker — TLS-by-default in release added in commit `4889a9a33` (2025-11-13, "feat: Integrate astraweave-security…"). Noted that `parking_lot::Mutex` (not `std::sync::Mutex`) is used in §3 and §9. | -| **Owner notes** | As of 1.18, current line cites match `6b571a58`. `try_seat` is the only player insert. `FindOrCreate` seats under the choosing lock and binds `PlayerMembership` after that lock drops. `JoinRoom` seats and binds under its own lock. A full `JoinRoom` is `ProtocolError` `"room full"`. A new player still starts with `tokens: BUCKET_SIZE`. As of 1.17, a drop that is one second old leaves the kick window (`>= DROP_WINDOW`). The 1.16 note's "older than" is that comparison. Line numbers in the 1.14 sentence describe that revision's server. As of 1.16, current line cites match `0a2d93ea`. Drops older than one second leave the kick window before the next unpaid message. Warn charges a bad tag and does not apply it. Text and Pong are charged. As of 1.15, the bucket is 64/s with capacity 64. A paid message does not clear the drop window. Thirty-two unpaid messages in one second close 1008. Protocol Ping is charged, and one ping every 20 ms stays under the refill. The 33 ms demo client pays every frame. `prequeued_frames_advance_exactly_one_tick_per_period` keeps a readable socket from skipping the room tick. As of 1.14, the ready-socket check is one protocol Ping every 20 ms, read on another task. Ping is uncharged here (`lib.rs:821-823`). The 50/s rate was picked to fit #526's 64/s refill. As of 1.12, each room has one tick owner. Connections subscribe to `snap_tx` and do not call `build_snapshot`. As of 1.11, `aw-net-server` has one connection handler. `handle_socket_tls` calls `handle_socket`. `PlayerMembership` removes the player when that task leaves, so a failed join send cannot leave a ghost. Two distinct integration paths share `aw-net-proto`: (1) the standalone `aw-net-server` / `aw-net-client` binaries communicate end-to-end over WSS with HMAC-SHA256 input signatures, token-bucket rate limiting, sled persistence, and matchmaking. As of revision 1.3 the signing is real and enforced: client and server agree on bytes via the canonical proto surface (`SigningKey` + `sign`/`verify` + `input_frame_sig_payload`), the server verifies FIRST, and the default `SignatureFailurePolicy::Kick` closes the connection (Close 1008) on a bad tag. (2) `astraweave-net-ecs` provides ECS Plugin scaffolding (`NetworkClientPlugin`, `NetworkServerPlugin`, components, simulation-stub systems) — but **workspace grep finds zero `use astraweave_net_ecs` outside the crate's own tests and benches**, including in `astraweave-stress-test` which declares the dep in `Cargo.toml`. The ECS layer is currently dormant code. There is no dedicated workflow for these four crates. Comprehensive CI runs the client binaries (`ci.yml:203`, `:319`, `:568`; nextest at `:215`, `:325`, and `:574`). `fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. | +| **Owner notes** | As of 1.18, current line cites match `6b571a58`. `try_seat` is the only player insert. `FindOrCreate` seats under the choosing lock and binds `PlayerMembership` after that lock drops. `JoinRoom` seats and binds under its own lock. A full `JoinRoom` is `ProtocolError` `"room full"`. A new player still starts with `tokens: BUCKET_SIZE`. As of 1.17, a drop that is one second old leaves the kick window (`>= DROP_WINDOW`). The 1.16 note's "older than" is that comparison. Line numbers in the 1.14 sentence describe that revision's server. As of 1.16, current line cites match `0a2d93ea`. Drops older than one second leave the kick window before the next unpaid message. Warn charges a bad tag and does not apply it. Text and Pong are charged. As of 1.15, the bucket is 64/s with capacity 64. A paid message does not clear the drop window. Thirty-two unpaid messages in one second close 1008. Protocol Ping is charged, and one ping every 20 ms stays under the refill. The 33 ms demo client pays every frame. `prequeued_frames_advance_exactly_one_tick_per_period` keeps a readable socket from skipping the room tick. As of 1.14, the ready-socket check is one protocol Ping every 20 ms, read on another task. Ping is uncharged here (`lib.rs:821-823`). The 50/s rate was picked to fit #526's 64/s refill. As of 1.12, each room has one tick owner. Connections subscribe to `snap_tx` and do not call `build_snapshot`. As of 1.11, `aw-net-server` has one connection handler. `handle_socket_tls` calls `handle_socket`. `PlayerMembership` removes the player when that task leaves, so a failed join send cannot leave a ghost. Two distinct integration paths share `aw-net-proto`: (1) the standalone `aw-net-server` / `aw-net-client` binaries communicate end-to-end over WSS with HMAC-SHA256 input signatures, token-bucket rate limiting, sled persistence, and matchmaking. As of revision 1.3 the signing is real and enforced: client and server agree on bytes via the canonical proto surface (`SigningKey` + `sign`/`verify` + `input_frame_sig_payload`), the server verifies FIRST, and the default `SignatureFailurePolicy::Kick` closes the connection (Close 1008) on a bad tag. (2) `astraweave-net-ecs` provides ECS Plugin scaffolding (`NetworkClientPlugin`, `NetworkServerPlugin`, components, simulation-stub systems) — but **workspace grep finds zero `use astraweave_net_ecs` outside the crate's own tests and benches**, including in `astraweave-stress-test` which declares the dep in `Cargo.toml`. The ECS layer is currently dormant code. There is no dedicated workflow for these four crates. Comprehensive CI runs the client binaries (`ci.yml:213`, `:352`, `:618`; nextest at `:225`, `:358`, and `:624`). `fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. | --- @@ -622,7 +622,7 @@ The standalone server/client binaries are functional and tested by hand (`net/RE - `astraweave-net-ecs/benches/net_ecs_adversarial.rs`: 9 `bench_function` + 7 `bench_with_input` call sites (worst-case shapes). - `net/aw-net-proto/benches/proto_bench.rs`: 12 `bench_function` + 10 `bench_with_input` call sites. - **Total bench cases:** 55 (`bench_function` + `bench_with_input` call sites across those three files). -- **CI presence:** There is no dedicated workflow for these four crates. Comprehensive CI runs the client binaries on the archive machine: `.github/workflows/ci.yml:203` (`Net client binaries on this machine`; `--profile ci-pr` at `:215` when the diff is full or `aw-net-client` is affected), `:319` (Windows pull-request archive; `--profile ci` at `:325`), and `:568` (Windows Test full archive; `--profile ci` at `:574`). `.github/workflows/fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. The older `astraweave-net` crate still has `.github/workflows/net-tests.yml`. +- **CI presence:** There is no dedicated workflow for these four crates. Comprehensive CI runs the client binaries on the archive machine: `.github/workflows/ci.yml:213` (`Net client binaries on this machine`; `--profile ci-pr` at `:225` when the diff is full or `aw-net-client` is affected), `:352` (Windows pull-request archive; `--profile ci` at `:358`), and `:618` (Windows Test full archive; `--profile ci` at `:624`). `.github/workflows/fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. The older `astraweave-net` crate still has `.github/workflows/net-tests.yml`. - **Mutation testing:** Per-crate inline mutation-resistance test suites (27 in `astraweave-net-ecs`, 59 in `aw-net-proto`); not run from a centralized workflow. - **Miri / Kani validation:** Not in `.github/workflows/miri.yml` or `kani.yml`. The library crates carry `#![forbid(unsafe_code)]`; the binaries do not but contain no observable unsafe blocks. - **Manual validation:** `net/README.md:13-30` is the smoke-test workflow: `cargo run -p aw-net-server` (`:17`) then `cargo run -p aw-net-client` (`:29`). The client logs `joined; tick_hz=` at `net/aw-net-client/src/main.rs:67`. @@ -652,7 +652,7 @@ The standalone server/client binaries are functional and tested by hand (`net/RE - **Why are the TLS stack versions one major behind the other workspace crate? — RESOLVED.** `aw-net-server` and `astraweave-net` both use `tokio-rustls` 0.26 and `rustls` 0.23 with the ring provider. `rustls` 0.22 and `tokio-rustls` 0.25 are not in `Cargo.lock`. Certificate PEM is parsed with `rustls-pki-types` (`CertificateDer::pem_file_iter`, `PrivateKeyDer::from_pem_file`). -- **Why is there no dedicated CI workflow for these four crates?** There still is not one. Comprehensive CI runs the client binaries (`ci.yml:203`, `:319`, `:568`; nextest at `:215`, `:325`, and `:574`). `fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. The 2026-05-12 grep that reported zero matches under `.github/` is no longer true. The older `astraweave-net` crate still has `net-tests.yml`. Is the missing dedicated workflow intentional? +- **Why is there no dedicated CI workflow for these four crates?** There still is not one. Comprehensive CI runs the client binaries (`ci.yml:213`, `:352`, `:618`; nextest at `:225`, `:358`, and `:624`). `fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. The 2026-05-12 grep that reported zero matches under `.github/` is no longer true. The older `astraweave-net` crate still has `net-tests.yml`. Is the missing dedicated workflow intentional? - **Should `handle_socket_tls` / `handle_socket` be unified? — RESOLVED** at `de6f2725`. `handle_socket` is generic over `AsyncRead + AsyncWrite + Unpin`. `handle_socket_tls` delegates. `PlayerMembership` is the shared cleanup. @@ -690,7 +690,7 @@ The standalone server/client binaries are functional and tested by hand (`net/RE 4. **`sled::Db` is opened but unused** — the README's persistence claim is unbacked. 5. **Token bucket is 64/s, capacity 64.** A 30 Hz input pays every frame. About 96 messages/s closes 1008. `RateLimited` is not sent. 6. **`lib_temp.rs` is orphan source** — not declared, not compiled. -7. **There is no dedicated workflow for these four crates.** Comprehensive CI runs the client binaries (`ci.yml:203`, `:319`, `:568`; nextest at `:215`, `:325`, and `:574`). `fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. +7. **There is no dedicated workflow for these four crates.** Comprehensive CI runs the client binaries (`ci.yml:213`, `:352`, `:618`; nextest at `:225`, `:358`, and `:624`). `fuzz-nightly.yml:35` lists `net/aw-net-proto/fuzz`. **Files you'll most likely touch:** - `net/aw-net-proto/src/lib.rs` — wire-protocol changes (always coordinated with both client and server). diff --git a/docs/campaigns/doc-truth/CLOSED_VOCABULARY_ALLOWLIST.md b/docs/campaigns/doc-truth/CLOSED_VOCABULARY_ALLOWLIST.md index dcd1bdb679..411c9e4201 100644 --- a/docs/campaigns/doc-truth/CLOSED_VOCABULARY_ALLOWLIST.md +++ b/docs/campaigns/doc-truth/CLOSED_VOCABULARY_ALLOWLIST.md @@ -338,6 +338,10 @@ Every KEEP occurrence from the closed-vocabulary triage (D.1.C), **updated by D. | `docs/audits/CI_WORKSHOP_2026-07.md` | `clippy-all` | quoted-defect-alias | permanent | | `CHANGELOG.md` | `59 library crates` | dated-record | permanent | + +| `docs/current/ARAVATH_DISTRIBUTION.md` | `quinn` | supply-chain-pin | permanent | +| `docs/current/ENGINE_STATUS.md` | `quinn` | supply-chain-pin | permanent | +| `docs/current/SECURITY_AUDIT.md` | `quinn` | supply-chain-pin | permanent | diff --git a/docs/current/ARAVATH_DISTRIBUTION.md b/docs/current/ARAVATH_DISTRIBUTION.md index 999c8425fd..b3581f41c5 100644 --- a/docs/current/ARAVATH_DISTRIBUTION.md +++ b/docs/current/ARAVATH_DISTRIBUTION.md @@ -128,7 +128,7 @@ The advisory check passes because the leftovers are ignored, not because they ar | `RUSTSEC-2024-0384` | `instant` 0.1.13 | [#322](https://github.com/lazyxeon/AstraWeave/issues/322) | | `RUSTSEC-2024-0436` | `paste` 1.0.15 | [#323](https://github.com/lazyxeon/AstraWeave/issues/323) | -[#324](https://github.com/lazyxeon/AstraWeave/issues/324) is closed. It tracked yanked `zip` 1.1.4 via `candle-core` 0.8.4. The fix is #353. No candle release through 0.11.0, and not current candle main, depends on `zip >= 9`. `third_party/candle-core` is that 0.8.4 crate pinned to the workspace `zip` 9.0.3, which is the patched line for RUSTSEC-2026-0367, 0368, and 0369. Delete the directory and the `[patch.crates-io]` entry once candle upstream depends on `zip >= 9`. Asset packs stay on `zip` 9.0.3. There is no audit ignore for those three zip IDs. [#303](https://github.com/lazyxeon/AstraWeave/issues/303) is the older note that deny advisory and license failures were warnings. On the #325 commit, deny advisories and `cargo audit` passed with the ignore list above. +[#324](https://github.com/lazyxeon/AstraWeave/issues/324) is closed. It tracked yanked `zip` 1.1.4 via `candle-core` 0.8.4. The fix is #353. No candle release through 0.11.0, and not current candle main, depends on `zip >= 9`. `third_party/candle-core` is that 0.8.4 crate pinned to the workspace `zip` 9.7.0 ([PR #758](https://github.com/lazyxeon/AstraWeave/pull/758)), patched for the advisories it addresses. Delete the directory and the `[patch.crates-io]` entry once candle upstream depends on `zip >= 9`. Asset packs stay on that same `zip` release. There is no audit ignore for those three zip IDs. [PR #758](https://github.com/lazyxeon/AstraWeave/pull/758) pins `url` 2.5.9 and `form_urlencoded` 1.2.3, which that `url` release requires, moves `quinn-udp` to 0.5.16, and removes `chrono`. [#756](https://github.com/lazyxeon/AstraWeave/issues/756) tracks the `main` audit failure: privilege escalation, RUSTSEC-2026-0548 (`zip`); denial of service, RUSTSEC-2026-0538 (`quinn-udp`); unmaintained, RUSTSEC-2026-0543 (`chrono`). `url` 2.5.9 also fixes stack overflow, RUSTSEC-2026-0592, a later advisory. No ignore was added. [#303](https://github.com/lazyxeon/AstraWeave/issues/303) is the older note that deny advisory and license failures were warnings. On the #325 commit, deny advisories and `cargo audit` passed with the ignore list above. `scripts/check-aravath-network.sh` is the greybox supply-chain check. On `d6903d3a` the workspace `tokio` features are `fs`, `io-util`, `macros`, `rt`, `rt-multi-thread`, `sync`, and `time`. [#327](https://github.com/lazyxeon/AstraWeave/pull/327) (`87fbe079`) removed `net` from that list. `astraweave-net`, `astraweave-ipc`, and `astraweave-net-ecs` opt in. [#326](https://github.com/lazyxeon/AstraWeave/issues/326) is closed. The script still rejects `reqwest`, `hyper`, `openssl`, `socket2`, and a `tokio` `net` feature in the `aravath_runtime` graph. #217 removed the `openssl` package from the lockfile. Some example and tool manifests still request `tokio` `full` on their own; that is outside the workspace dependency the greybox graph uses. diff --git a/docs/current/AUTONOMOUS_GAMEPLAY_QA.md b/docs/current/AUTONOMOUS_GAMEPLAY_QA.md index a85956e161..03a5f77a0d 100644 --- a/docs/current/AUTONOMOUS_GAMEPLAY_QA.md +++ b/docs/current/AUTONOMOUS_GAMEPLAY_QA.md @@ -98,7 +98,7 @@ The greybox checkpoint (`aravath_runtime/src/save.rs`) stores voxel edits, playe `docs/architecture/quests.md` records two quest implementations. - `astraweave-weaving::quest::QuestManager` is the gameplay one: `ObjectiveType` (kill, repair, fetch, explore, escort, defend, time trial, boss, collect), prerequisites, one active quest. Storage is a `HashMap` keyed by id, so a bot addresses quests by id and does not walk the map. Starter quests are `quest_stabilize_anchors`, `quest_clear_corruption` (requires the first), and `quest_restore_beacon` (requires the second), in `astraweave-weaving/src/starter_quests.rs`. They are not registered on the slice or the greybox. -- `astraweave-quests` is the LLM and terrain layer. The trace marks it in-design aside from the basic `Quest` / `QuestStep` pair the editor uses. `CActiveQuest`, journal entries, and generators call `chrono::Utc::now()`. `systems.rs` also times work with `Instant::now()`. Those clocks cannot enter a hashed sim. +- `astraweave-quests` is the LLM and terrain layer. The trace marks it in-design aside from the basic `Quest` / `QuestStep` pair the editor uses. `astraweave-quests` does not depend on a wall-clock crate. A wall clock still cannot enter a hashed sim. A third quest type would violate the one-implementation rule. Scenario quests use `QuestManager`. @@ -110,7 +110,7 @@ No save blob stores the runner's current node or history. A dialogue save/reload ### CI tiers (PR #223, merged) -`docs/current/CI_ARCHITECTURE.md` is the contract. Pull requests require a short set: `PR Rust checks`, `determinism-replay / compare`, the three `hash (*)` jobs, cargo-deny, cargo-audit, pack guard, scorecard. `cancel-in-progress` is on for `pull_request` only. PBR, editor, and full integration tests do not run on pull requests. Docs-only diffs skip the Rust compile. Determinism still runs. +`docs/current/CI_ARCHITECTURE.md` is the contract. `PR Rust checks` is the rollup for the Rust rows. Ruleset enforcement that would make that context block a merge is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). Partition jobs `Test (ubuntu, ${{ matrix.partition }}/3)` (`.github/workflows/ci.yml:276`, job-level `if:` at `:280-285`, matrix at `:286-289`) and `Test (windows, ${{ matrix.partition }}/3)` (`:406`, job-level `if:` at `:410-414`, matrix at `:415-418`) are matrix jobs. When that `if:` is false, the matrix never expands. On docs-only #720 head `5d53e10c`, the Checks API showed runs named `Test (ubuntu, ${{ matrix.partition }}/3)` and `Test (windows, ${{ matrix.partition }}/3)`, both skipped, and did not create `Test (ubuntu, 1/3)`, `2/3`, or `3/3`. A required check of an expanded `N/3` name would stay pending and block the merge. `docs/ci/bottlenecks.md:33` says a matrix that does not expand does not create those names. Stable-name jobs `Test (ubuntu, build archive)`, `Test (windows, build archive)`, and `Minimum Supported Rust Version` still report a check run when skipped, and that skipped status counts as success, so requiring those names would let a docs-only pull request pass them without running them. The rollup runs on every pull request. `Detect affected crates` must succeed (`.github/workflows/ci.yml:518`), and the gate must succeed (`:519`). The rollup passes when the diff is docs-only, or when `full` is not true and the package list is empty. Otherwise (`full` is `true`, or the package list is non-empty), it requires success for `test-linux-build`, `test-linux`, `test-windows`, and `msrv` (`:528-531`). A `full=true` path with an empty package list (a pull-request `full=true` row: rows 83, 84, 86 and 89 of the table at `CI_ARCHITECTURE.md:82-89`) is that otherwise branch. A skipped or cancelled job is without success and fails those checks. The same contract lists `determinism-replay / compare`, the three `hash (*)` jobs, cargo-deny, cargo-audit, pack guard, and scorecard. `cancel-in-progress` is on for `pull_request` only. PBR and full integration tests do not run on pull requests. `editor-ci.yml` and `aw-editor-tests.yml` stay off `pull_request`. A pull request that is not docs-only, and whose affected set is the full workspace or at least one package, runs the editor bin harness as a step of `Test (ubuntu, build archive)`: `cargo test --locked -p aw_editor --all-features --bins`, with no `continue-on-error`. Docs-only diffs skip the Rust compile. Determinism still runs. Profile `ci-pr` excludes the tests still listed in `scripts/ci/deferred_pr_tests.txt`. #333 removed the terrain goldens and the AI planning rows. The file still names GPU render passes, lavapipe fluid smokes, and `test_qwen3_variants`. #254 stays open. Profile `ci` on `main` and nightly does not exclude that file. Replay tests match `test(/determinism/) | test(/replay/) | test(/deterministic/)` and get `retries = 0`. The determinism workflow does not call nextest. @@ -327,7 +327,7 @@ These block a claim that "gameplay replay" is already cross-OS. They are not fix | `.awsv` names and bundles include `Uuid::new_v4()` and `OffsetDateTime::now_utc()`. Greybox `WorldState.tick` is 0 and `state_hash` is the edit count | `persistence/aw-save`, greybox `save.rs` on #205 | QA hashes restored gameplay state, never file bytes. A later save API takes the id, the timestamp, and the tick from the sim | | Greybox checkpoint omits enemies, motor mode, attack phase, lock, tick, and `cover_broken` | PR #275 / #205 | `greybox_combat_save` is expected to fail until the checkpoint stores those fields. Implement the fields with the scenario, or accept the deferred issue and skip the check | | `auto_save_system` is empty and `replay_system` does not apply events | `astraweave-persistence-ecs` | QA does not call `PersistencePlugin` | -| `astraweave-quests` stamps `Utc::now()` and `Instant::now()` | quests trace, crate `astraweave-quests` | Quest scenarios use `astraweave-weaving::QuestManager` and tick counts. The LLM quest layer stays out of the hashed sim until its clocks are tick fields | +| `astraweave-quests` has no wall-clock crate. `generated_at` is a `u64` (`llm_quests.rs:434` sets `0`) | quests trace, crate `astraweave-quests` | Quest scenarios use `astraweave-weaving::QuestManager` and tick counts. The LLM quest layer stays out of the hashed sim | | The audio rapid-volume test shared `tests/assets` with cleanup | this branch, same fix as #289 | The beep is written in a private temp directory | | Two dialogue graphs (crate runner and editor panel) and two quest crates | quests trace | Bots bind the crate types named above. No third graph and no third quest type | diff --git a/docs/current/CAUSAL_WORLD_DESIGN.md b/docs/current/CAUSAL_WORLD_DESIGN.md index 274ec0ab1d..9eb55471da 100644 --- a/docs/current/CAUSAL_WORLD_DESIGN.md +++ b/docs/current/CAUSAL_WORLD_DESIGN.md @@ -40,9 +40,9 @@ Surveyed on `main` at `f1109340` unless a PR ref is named. "Wired" means a non-t | Piece | Real or stub | On a tick? | |---|---|---| -| `WorldEvent` in `agent.rs` | Real POD-shaped struct: `String` id, `String` type, `serde_json::Value` payload, `DateTime` timestamp, `EventSeverity`. | No. `Agent::handle_world_event` has no impl outside the crate's tests. | -| `WorldEventGenerator` | Real async generator. `generate_event` calls the LLM, scores coherence as `f32`, and stamps `Utc::now()`. Default interval is 30_000 ms. `EconomicState.trade_routes_status` is a `HashMap` inside that generator's private world. It is not a route graph. Fields are `dead_code`. Constructors in this file are the unit tests. | No. | -| `NarrativeCoherenceEngine` | Real async validator. Same four `Arc` handles (`LlmClient`, `RagPipeline`, conversation history, prompt library). Plot points use `DateTime`. | No. | +| `WorldEvent` in `agent.rs` | Real POD-shaped struct: `String` id, `String` type, `serde_json::Value` payload, `time::OffsetDateTime` timestamp, `EventSeverity`. | No. `Agent::handle_world_event` has no impl outside the crate's tests. | +| `WorldEventGenerator` | Real async generator. `generate_event` calls the LLM, scores coherence as `f32`, and stamps `OffsetDateTime::now_utc()`. Default interval is 30_000 ms. `EconomicState.trade_routes_status` is a `HashMap` inside that generator's private world. It is not a route graph. Fields are `dead_code`. Constructors in this file are the unit tests. | No. | +| `NarrativeCoherenceEngine` | Real async validator. Same four `Arc` handles (`LlmClient`, `RagPipeline`, conversation history, prompt library). Plot points use `time::OffsetDateTime`. | No. | | `AgentCoordinator` | Real tokio router. `Transform` is a placeholder action. | No. | | Editor `WorldEvent` in `tools/aw_editor/src/panels/world_panel.rs` | A different struct. `Instant` timestamp and a closed editor enum (terrain generated, weather, time, biome, settings). Presentation history for the world panel. | Editor UI only. Not sim. | @@ -303,7 +303,7 @@ A cast stays a `WeaveCommand` on #252. Structural decay stays a `DestructionComm Allowed: a recorded line for a template the rules already emitted. Allowed later, still off-tick: a proposed rule row that the baker hashes into the rule table before the session starts. A rule that arrives mid-session is a new session seed, not a live patch. -Forbidden on the tick: `generate_event`, `generate_storyline`, `QuestLlmSystem::update`, `NarrativeCoherenceEngine`, HTTP, `Utc::now`, and any write into stock or stance from parsed model text. +Forbidden on the tick: `generate_event`, `generate_storyline`, `QuestLlmSystem::update`, `NarrativeCoherenceEngine`, HTTP, `OffsetDateTime::now_utc`, and any write into stock or stance from parsed model text. ## 7. First vertical slice in the Aravath demo diff --git a/docs/current/CI_ARCHITECTURE.md b/docs/current/CI_ARCHITECTURE.md index e59ef1513e..bbda42acf0 100644 --- a/docs/current/CI_ARCHITECTURE.md +++ b/docs/current/CI_ARCHITECTURE.md @@ -31,7 +31,7 @@ A new push cancels the previous pull-request run. Pushes to main, tags, and sche 3. **Every job has `timeout-minutes`.** Typical jobs are 30–45. The fast gate is `Gate (fmt, clippy, check)`. The Linux archive, the Windows archive, their partitions, and MSRV `needs` that gate, so a format or compile failure does not start those runners. 4. **Two tiers.** Nightly Failure Issue (`workflow_run`) opens or updates a GitHub issue when a nightly or main run of the heavy workflows fails. `workflow_run` fires only after this file is on the default branch. 5. **Duplicates are gone.** `rust-cache-optimized.yml` is folded into `ci.yml` and deleted. The 15-job unwrap matrix is deleted. One `cargo clippy --lib --no-deps` pass reads `[lints.clippy]` on each crate. sccache (GitHub Actions cache backend) plus one Swatinem `shared-key` per OS (`${{ runner.os }}-astraweave`), `cache-targets: false`, `save-if` only on `refs/heads/main`. Affected crates come from `scripts/ci/affected_crates.py`. Docs-only diffs skip the Rust compile. Windows and Linux pull-request tests each compile once (`cargo nextest archive`, debuginfo off so the archive stays uploadable) and then run three `count:N/3` partitions against that archive. The Linux archive starts when the gate finishes, in parallel with the Windows archive. It is not built inside the gate. Profile `ci-pr-linux-archive` keeps the Linux GPU tests that `ci-pr-archive` skips, and drops only the four `CARGO_BIN_EXE` binaries, which the archive job runs on the build machine. Determinism tests are not retried. PR partitions on Linux and Windows set `AW_PERF_ASSERTS=1`, which enforces the astraweave-nav stress ceilings (about 10× the old debug bounds, #575). Nightly and push `test-full` don't set it, and Criterion `stress_latency` tracks latency. -6. **Required jobs are not queued behind optional compiles.** PBR, Editor CI, and AW Editor tests do not run on `pull_request`. They run on push, their nightly schedule, and `workflow_dispatch`. `cancel-in-progress` is still `${{ github.event_name == 'pull_request' }}` on every workflow that has the block, so a push to `main` or a schedule is never cancelled. +6. **Compile jobs are not queued behind optional workflows.** PBR, Editor CI, and AW Editor tests do not run on `pull_request`. They run on push, their nightly schedules, and `workflow_dispatch`. Editor CI's schedule is `50 6 * * *`. AW Editor tests' schedule is `35 6 * * *`. Those two workflows stay off `pull_request`. A pull request that is not docs-only, and whose affected set is the full workspace or at least one package, runs the editor bin harness as a step of `Test (ubuntu, build archive)`: `cargo test --locked -p aw_editor --all-features --bins`, with no `continue-on-error`. `--bins` builds every bin harness, including `aw_game_runtime` (`test = false` at `tools/aw_editor/Cargo.toml:150`), and that harness has no tests. The `PR Rust checks` job needs the archive job. Ruleset enforcement is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). The archive job is skipped on a docs-only pull request and when no crate is selected (`full` is not set and the package list is empty). `cancel-in-progress` is still `${{ github.event_name == 'pull_request' }}` on every workflow that has the block, so a push to `main` or a schedule is never cancelled. ## Tiers @@ -41,16 +41,16 @@ A new push cancels the previous pull-request run. Pushes to main, tags, and sche |---|---| | Affected-crate detect | `Detect affected crates` | | fmt, one clippy, cargo check | `Gate (fmt, clippy, check)` | -| Linux archive, then 3 partitions | `Test (ubuntu, build archive)`, then `Test (ubuntu, 1/3)`, `Test (ubuntu, 2/3)`, `Test (ubuntu, 3/3)` | +| Linux archive, then 3 partitions. The archive job also runs `cargo test --locked -p aw_editor --all-features --bins` (no `continue-on-error`). `--bins` builds the `aw_game_runtime` harness, which has no tests. The `PR Rust checks` job needs this job. Ruleset enforcement is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). The job is skipped on a docs-only pull request and when no crate is selected (`full` is not set and the package list is empty). | `Test (ubuntu, build archive)`, then `Test (ubuntu, 1/3)`, `Test (ubuntu, 2/3)`, `Test (ubuntu, 3/3)` | | Windows archive, then 3 partitions | `Test (windows, build archive)`, then `Test (windows, 1/3)`, `Test (windows, 2/3)`, `Test (windows, 3/3)` | | MSRV (`rust-version` in the workspace manifest, 1.89.0) | `Minimum Supported Rust Version` | | Rollup of the rows above | `PR Rust checks` | | Replay hash, Ubuntu / Windows / macOS, then compare. Nineteen required cases: `planner_pure`, `perception_world`, `gameplay_rng`, `fixed64`, `combat_resolve`, `destruction`, `gameplay_qa_aravath_slice`, `nav_reroute`, `causal_bridge`, `scripted_system`, `weaving`, `traversal`, `traversal_deformed`, `worldgen_columns`, `deformed_chunk`, `local_sim`, `greybox_checkpoint`, `quest_ticks`, `persist_replay`. No path filter. | `hash (ubuntu-latest)`, `hash (windows-latest)`, `hash (macos-latest)`, `compare` | | cargo-deny, cargo-audit | `Cargo Deny Check`, `Security Audit (cargo-audit)` | -These path-filtered workflows are not in the required set because a filter would skip them and leave a check pending: trace sync, doc-truth lint, docs, and Miri job `miri-ecs-hotpath` (`miri.yml`; paths `astraweave-ecs/src/blob_vec.rs`, `sparse_set.rs`, and `archetype.rs`). That Miri job is not required. `net-tests.yml` still triggers on every pull request; its job is scope-conditional (`--scope net`), not path-filtered (see below). Pack guard and OpenSSF Scorecard run on every pull request. PBR, Editor CI, and AW Editor tests do not run on pull requests. +These path-filtered workflows are not in the required set because a filter would skip them and leave a check pending: trace sync, doc-truth lint, docs, and Miri job `miri-ecs-hotpath` (`miri.yml`; paths `astraweave-ecs/src/blob_vec.rs`, `sparse_set.rs`, and `archetype.rs`). That Miri job is not required. `net-tests.yml` still triggers on every pull request; its job is scope-conditional (`--scope net`), not path-filtered (see below). Pack guard and OpenSSF Scorecard run on every pull request. `editor-ci.yml` and `aw-editor-tests.yml` do not run on pull requests. `Test (ubuntu, build archive)` also runs `cargo test --locked -p aw_editor --all-features --bins`, with no `continue-on-error`. `--bins` builds the `aw_game_runtime` harness, which has no tests. The `PR Rust checks` job needs that archive job. Ruleset enforcement is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). The archive job is skipped on a docs-only pull request and when no crate is selected (`full` is not set and the package list is empty). -`PR Rust checks` is the status to require for the Rust rows. The heavy jobs are skipped on a docs-only pull request (they do not compile). GitHub treats a skipped required check as missing, which blocks the merge. The rollup runs on every pull request: it fails if the gate failed or if a crate change left a test job red, and it passes when the heavy jobs were correctly skipped. +`PR Rust checks` is the rollup for the Rust rows. Ruleset enforcement that would make that context block a merge is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). The heavy jobs are skipped by their `if:` on a docs-only pull request and when no crate is selected (they do not compile). Partition jobs `Test (ubuntu, ${{ matrix.partition }}/3)` (`.github/workflows/ci.yml:276`, job-level `if:` at `:280-285`, matrix at `:286-289`) and `Test (windows, ${{ matrix.partition }}/3)` (`:406`, job-level `if:` at `:410-414`, matrix at `:415-418`) are matrix jobs. When that `if:` is false, the matrix never expands. On docs-only #720 head `5d53e10c`, the Checks API showed runs named `Test (ubuntu, ${{ matrix.partition }}/3)` and `Test (windows, ${{ matrix.partition }}/3)`, both skipped, and did not create `Test (ubuntu, 1/3)`, `2/3`, or `3/3`. A required check of an expanded `N/3` name would stay pending and block the merge. `docs/ci/bottlenecks.md:33` says a matrix that does not expand does not create those names. Stable-name jobs `Test (ubuntu, build archive)`, `Test (windows, build archive)`, and `Minimum Supported Rust Version` still report a check run when skipped, and that skipped status counts as success, so requiring those names would let a docs-only pull request pass them without running them. The rollup runs on every pull request. `Detect affected crates` must succeed (`.github/workflows/ci.yml:518`), and the gate must succeed (`:519`). The rollup passes when the diff is docs-only, or when `full` is not true and the package list is empty. Otherwise (`full` is `true`, or the package list is non-empty), it requires success for `test-linux-build`, `test-linux`, `test-windows`, and `msrv` (`:528-531`). A `full=true` path with an empty package list (a pull-request `full=true` row: rows 83, 84, 86 and 89 of the table at `CI_ARCHITECTURE.md:82-89`) is that otherwise branch. A skipped or cancelled job is without success and fails those checks. ### Main, nightly, workflow_dispatch @@ -63,7 +63,7 @@ These path-filtered workflows are not in the required set because a filter would | CodeQL | push to main and weekly (Sunday 03:00 UTC). Not on pull requests. | | Benchmarks, including `aw_build` | see item 1 above. Shard count is 16 (`shard_index` 0–15, `--shard-count 16`). Shards 13, 14, and 15 are `astraweave-render@a`, `@b`, and `@c` (explicit thirds of that crate's bench targets). #374 flat-samples `fluid_baseline_50k` and is on main. Shard 0 is `astraweave-net`, `astraweave-profiling`, `astraweave-water`, and `astraweave-localsim` (#351). Each sharded bench target gets `timeout 600` after `cargo bench --no-run`. Compilation is outside that limit. The `aw_build` job is separate and uses its 30-minute job timeout. The aggregate expects 53 package records. `github-action-benchmark` stores `dev/bench` on branch `benchmark-data`. `gh-pages` is the docs site, and main also has a `gh-pages/` directory, so the old checkout never published that history. The PR comment step clones `github.com//`, does not auto-push, and comments only when a result exceeds the alert threshold. | | Integration tests other than the replay hash | `integration-tests.yml` on push and schedule 04:00 UTC. | -| PBR build and editor tests, all three OS | `pbr-pipeline-ci.yml`, `editor-ci.yml`, `aw-editor-tests.yml` on push, their nightly schedules, and `workflow_dispatch`. Not on pull requests. | +| PBR build and editor tests, all three OS | `pbr-pipeline-ci.yml`, `editor-ci.yml`, and `aw-editor-tests.yml` run on push, their nightly schedules (`editor-ci.yml` is `50 6 * * *`, `aw-editor-tests.yml` is `35 6 * * *`), and `workflow_dispatch`. Those workflows are not on pull requests. A pull request that is not docs-only, and whose affected set is the full workspace or at least one package, also runs `cargo test --locked -p aw_editor --all-features --bins` in `ci.yml` job `Test (ubuntu, build archive)`, with no `continue-on-error`. `--bins` builds the `aw_game_runtime` harness, which has no tests. The `PR Rust checks` job needs that job. Ruleset enforcement is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). | | Allocation ceilings, zero-alloc hot paths, CPU tick-time artifact | `allocation-measurement.yml` on push to `main`, schedule 05:45 UTC, and `workflow_dispatch`. Not on pull requests. The 11 ms GTX 1660 Ti check is the `gpu_frame_budget` dispatch input on a self-hosted runner labeled `gpu`. #216 is on main. The recorded heavy scene on a GTX 1660 Ti Max-Q is `median_gpu_frame_ms=3.688`, `budget_11ms=pass`, with the amortized cloud shadow at 0.323 ms. #371 and #372 stay open. | | SDK C harness | push to main, schedule 06:25 UTC, dispatch. | @@ -122,7 +122,7 @@ Most jobs are 30 or 45 minutes. Longer than 45, on purpose: | Job | Minutes | Why | |---|---|---| -| `Test (ubuntu, build archive)` | 60 | Run 40235303264 compiled the test profile in 24m 12s and then spent 6m 05s running tests. A dev-profile audio probe before that compile took another 7m 15s. This job compiles once with debuginfo off, builds the probe in the test profile, and uploads both. The three partition jobs are 30 minutes and do not compile. | +| `Test (ubuntu, build archive)` | 60 | Run 40235303264 compiled the test profile in 24m 12s and then spent 6m 05s running tests. A dev-profile audio probe before that compile took another 7m 15s. The nextest archive is one compile with debuginfo off. The job also builds the audio probe in the test profile, uploads both, and runs `cargo test --locked -p aw_editor --all-features --bins`, which compiles `aw_editor` again with `--all-features`. On run 44916883830 (head `3ba61d474970150b7ca5454c3bfe1f88e340f39a`, job 136885744997) that step took 6m 06s (15:37:24Z to 15:43:30Z) and the job took 37m 24s (15:06:10Z to 15:43:34Z), inside this 60-minute timeout. The three partition jobs are 30 minutes and do not compile. | | `Test (windows, build archive)` | 75 | One Windows debug compile of this workspace is about 50 minutes. The old per-partition jobs each compiled and were cancelled at 45. This job compiles once, archives, and uploads. `CARGO_PROFILE_TEST_DEBUG=0` keeps the archive small enough to upload. The three partition jobs are 30 minutes and do not compile. | | `Test full (${{ matrix.os }})` | 60 | The old Windows debug workspace test ran about 50 minutes. Nightly only. | | Benchmark shard | 60 | Existing job cap. Each bench target still gets 600s after compilation. | @@ -192,9 +192,9 @@ Require: - `pack-managed paths untracked + ignore surfaces current` - `OpenSSF Scorecard Analysis` -Do not require the individual `Test (ubuntu, N/3)`, `Test (windows, N/3)`, or `Gate` names as branch-protection checks. On a docs-only pull request the archive and partition jobs are skipped, and a skipped required check blocks the merge. `Gate (fmt, clippy, check)` still runs (player-facing name check and workflow policy); only its `Rust CI setup` step is conditional (`.github/workflows/ci.yml:122`). `PR Rust checks` is the rollup. +Do not require the individual `Test (ubuntu, N/3)`, `Test (windows, N/3)`, or `Gate` names as branch-protection checks. Partition jobs are matrix jobs with a job-level `if:` (`.github/workflows/ci.yml:280-285`, matrix at `:286-289`; the Windows twin `if:` is `:410-414`, matrix at `:415-418`). When that `if:` is false, the matrix never expands. On docs-only #720 head `5d53e10c`, the Checks API showed runs named `Test (ubuntu, ${{ matrix.partition }}/3)` and `Test (windows, ${{ matrix.partition }}/3)`, both skipped, and did not create `Test (ubuntu, 1/3)`, `2/3`, or `3/3`. A required check of an expanded `N/3` name would stay pending and block the merge. `docs/ci/bottlenecks.md:33` says a matrix that does not expand does not create those names. Stable-name jobs `Test (ubuntu, build archive)`, `Test (windows, build archive)`, and `Minimum Supported Rust Version` still report a check run when skipped, and that skipped status counts as success, so requiring those names would let a docs-only pull request pass them without running them. `Gate (fmt, clippy, check)` still runs (player-facing name check and workflow policy). Its `Rust CI setup` step is conditional (`.github/workflows/ci.yml:131`; the step name is `:130`), and `sccache stats` is conditional (`:142-144`, `always() && needs.changes.outputs.docs_only != 'true'`, ending in `|| true`). `PR Rust checks` is the rollup. Ruleset enforcement that would make that rollup block a merge is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). -Do not require `Test (ubuntu, build archive)`, `Test (windows, build archive)`, or either platform's `Test (*, N/3)` jobs individually. The rollup fails if an archive build fails or any partition fails. Do not require scope- or path-gated jobs individually: `net-tests` (every pull request; job skipped when scope is cold), trace sync, doc-truth, docs, Miri `miri-ecs-hotpath`. PBR, Editor CI, and AW Editor tests do not run on pull requests. +Do not require `Test (ubuntu, build archive)`, `Test (windows, build archive)`, or either platform's `Test (*, N/3)` jobs individually. The rollup fails if an archive build fails or any partition fails. Do not require scope- or path-gated jobs individually: `net-tests` (every pull request; job skipped when scope is cold), trace sync, doc-truth, docs, Miri `miri-ecs-hotpath`. `editor-ci.yml` and `aw-editor-tests.yml` do not run on pull requests. The editor bin command runs inside `Test (ubuntu, build archive)`, and the rollup is `PR Rust checks`. Ruleset enforcement is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). `Cargo Deny Check` is safe to require. TLS for reqwest, the websocket client, hf-hub, and ort is rustls, so the `openssl` / `openssl-sys` bans in `deny.toml` are not tripped. diff --git a/docs/current/ENGINE_STATUS.md b/docs/current/ENGINE_STATUS.md index 1394608445..9a75f9821d 100644 --- a/docs/current/ENGINE_STATUS.md +++ b/docs/current/ENGINE_STATUS.md @@ -1,4 +1,4 @@ -> This page moved from the repository root README on 2026-10-21. The root [README](../../README.md) is the short summary. The claims below were checked against `main` at `556a305c`, except the weave-origin notes, which were checked at `43b1b48f` (#388), the #394, #397, #389, and #393 notes, which were checked at `49d289eb`, and the 3.117 ms GTX 1660 Ti Max-Q capture, which was checked at `3855715ea6fd4649a144ee72d2e851956ed1ad3f`. #390 (`5a52b039`) removed the Clippy unwrap-prevention badge: that workflow was deleted in #223. `astraweave-ai` mutants run as 8 round-robin shards. The 70% gate is caught / (caught + missed). Timeouts are not caught. `cargo-mutants` is 27.1.0. #388 closed #295. `queue_weave` rejects an origin outside ±2048 cells and does not saturate. The `weaving` replay case still hashes `NullField`. +> This page moved from the repository root README on 2026-10-21. The root [README](../../README.md) is the short summary. The claims below were checked against `main` at `556a305c`, except the weave-origin notes, which were checked at `43b1b48f` (#388), the #394, #397, #389, and #393 notes, which were checked at `49d289eb`, and the 3.117 ms GTX 1660 Ti Max-Q capture, which was checked at `3855715ea6fd4649a144ee72d2e851956ed1ad3f`, and the supply-chain sentences tagged [PR #758](https://github.com/lazyxeon/AstraWeave/pull/758). #390 (`5a52b039`) removed the Clippy unwrap-prevention badge: that workflow was deleted in #223. `astraweave-ai` mutants run as 8 round-robin shards. The 70% gate is caught / (caught + missed). Timeouts are not caught. `cargo-mutants` is 27.1.0. #388 closed #295. `queue_weave` rejects an origin outside ±2048 cells and does not saturate. The `weaving` replay case still hashes `NullField`.

AstraWeave nebula logomark @@ -30,7 +30,7 @@ The game this engine is being built for is **Aravath**. ## Current state (2026-10-20) -Checked against `main` at `556a305c`, except the #388 weave-origin sentences, which were checked at `43b1b48f`, the #394, #397, #389, and #393 bullets, which were checked at `49d289eb`, and the 3.117 ms GTX 1660 Ti Max-Q capture, which was checked at `3855715ea6fd4649a144ee72d2e851956ed1ad3f`. The trace-version clause in the #397 bullet names `79122e78`. Numbers that were not re-measured in this pass are dated below. This page does not assign a letter grade. +Checked against `main` at `556a305c`, except the #388 weave-origin sentences, which were checked at `43b1b48f`, the #394, #397, #389, and #393 bullets, which were checked at `49d289eb`, and the 3.117 ms GTX 1660 Ti Max-Q capture, which was checked at `3855715ea6fd4649a144ee72d2e851956ed1ad3f`, and the supply-chain sentences tagged [PR #758](https://github.com/lazyxeon/AstraWeave/pull/758). The trace-version clause in the #397 bullet names `79122e78`. Numbers that were not re-measured in this pass are dated below. This page does not assign a letter grade. | Topic | What is true on this commit | | --- | --- | @@ -43,7 +43,7 @@ Checked against `main` at `556a305c`, except the #388 weave-origin sentences, wh | **Frame time** | The target is under 11 ms per frame on a GTX 1660 Ti-class GPU. #216 is on main. The later heavy-scene capture is a GTX 1660 Ti Max-Q, Vulkan, clean `main` `3855715ea6fd4649a144ee72d2e851956ed1ad3f`, 1920×1080, 120 samples ([#372 comment](https://github.com/lazyxeon/AstraWeave/issues/372#issuecomment-6330621189)). `gpu_cull=gpu` (`reason=indirect`), 448 batches, 175 visible. The `gpu_cull` pass median is 0.020 ms. The median GPU frame is 3.117 ms. `budget_11ms=pass`. The earlier heavy scene on that card, Vulkan, 1920×1080, 30 warmup + 120 samples, measured `median_gpu_frame_ms=3.688` at `939a21bb`, with `gpu_cull=cpu_fallback` because group 3 was per model. `budget_11ms=pass` on that capture. The amortized `cloud_shadow` pass on that earlier capture is 0.323 ms. `CLOUD_SHADOW_STRENGTH` is 4 (#384). The heavy scene still draws no water (#371). Do not treat the older CPU `profiling_demo` times as this measurement. The root README must not repeat a frame figure. `aw_doc_lint` fails if it does. | | **Coverage and Miri** | Whole-workspace line coverage **57.35%** was measured 2026-06-29 and has not been re-run on the 141-member tree. Miri **1,059** tests, 0 UB, was measured 2026-06-27 across ecs, math, core, and sdk. The February 2026 report records an older, smaller run. Kani proof attributes were **69** on 2026-06-13 and were not re-counted here. | | **Build** | This pass did not run `cargo check --workspace`. The last clean workspace check written into these docs is 2026-06-10, at 130 members. | -| **Supply chain** | #325 (`8e5dd73c`) makes `cargo deny` advisories and `cargo audit` pass aside from later advisories. Patched crates are locked (`rustls` 0.23.46, `tokio-rustls` 0.26.4, `openh264` 0.9.9). Ignored leftovers are #305, #309, #310, and #321–#323. #308 no longer has an ignore: `wayland-scanner` 0.31.11 uses `quick-xml` 0.41.0. #306 no longer has an ignore: `mikktspace` uses its `glam` backend, so `nalgebra` 0.26 is gone. #320 no longer has an ignore: postcard is `default-features = false` plus `alloc`, so `atomic-polyfill` is gone. #320 is closed. The fix is #387. `rustls-webpki` is 0.103.16 and `webpki-roots` is 1.0.10. RUSTSEC-2026-0381 and RUSTSEC-2026-0382 are fixed with no ignore. #311 no longer has an ignore: `aw_trace_sync` uses `yaml_serde`. #307 no longer has an ignore: `indicatif` 0.18 replaces `number_prefix`. #353 vendors `third_party/candle-core` (crates.io `candle-core` 0.8.4) and pins it to `zip` 9.0.3. #350 vendors `third_party/rapier3d` (crates.io `rapier3d` 0.22) on the same `[patch.crates-io]` table so a settled `PhysicsWorld::step` allocates nothing. An in-house physics engine is not planned work. Re-apply steps are in [VENDORED.md](../../third_party/rapier3d/VENDORED.md). The maintainer draft is [RAPIER_BUFFER_REUSE_UPSTREAM.md](RAPIER_BUFFER_REUSE_UPSTREAM.md) and is not filed upstream. That is the patched line for RUSTSEC-2026-0367, 0368, and 0369. `Cargo.lock` has no `zip` 1.1.4. There is no audit ignore for those three zip IDs. #324 is closed. The fix is #353. #365 resolved RUSTSEC-2026-0370, 0371, and 0372 with no ignore: `eframe` is built without AccessKit, so screen readers do not receive the egui tree, and editor file dialogs are `rfd` 0.17 (`libdbus` or `zenity` on Linux). The editor `kittest` feature is gone. #368 covers the six toolbar and menu clicks with synthetic `RawInput` on a plain `egui::Context`. #366 stays open for step 2: bring `egui_kittest` back once `accesskit_unix` uses zbus 6. Drop the vendor directory and the `[patch.crates-io]` entry once candle upstream depends on `zip >= 9`. #217 removed `openssl` from the lockfile. `deny.toml` still bans `openssl` and `openssl-sys`. #219 and #256 are closed. #327 (`87fbe079`) drops `net` from the workspace `tokio` features. `astraweave-net`, `astraweave-ipc`, and `astraweave-net-ecs` opt in. #326 is closed. | +| **Supply chain** | #325 (`8e5dd73c`) makes `cargo deny` advisories and `cargo audit` pass aside from later advisories. Patched crates are locked (`rustls` 0.23.46, `tokio-rustls` 0.26.4, `openh264` 0.9.9). Ignored leftovers are #305, #309, #310, and #321–#323. #308 no longer has an ignore: `wayland-scanner` 0.31.11 uses `quick-xml` 0.41.0. #306 no longer has an ignore: `mikktspace` uses its `glam` backend, so `nalgebra` 0.26 is gone. #320 no longer has an ignore: postcard is `default-features = false` plus `alloc`, so `atomic-polyfill` is gone. #320 is closed. The fix is #387. `rustls-webpki` is 0.103.16 and `webpki-roots` is 1.0.10. RUSTSEC-2026-0381 and RUSTSEC-2026-0382 are fixed with no ignore. #311 no longer has an ignore: `aw_trace_sync` uses `yaml_serde`. #307 no longer has an ignore: `indicatif` 0.18 replaces `number_prefix`. #353 vendors `third_party/candle-core` (crates.io `candle-core` 0.8.4) and pins it to `zip` 9.7.0 ([PR #758](https://github.com/lazyxeon/AstraWeave/pull/758)). #350 vendors `third_party/rapier3d` (crates.io `rapier3d` 0.22) on the same `[patch.crates-io]` table so a settled `PhysicsWorld::step` allocates nothing. An in-house physics engine is not planned work. Re-apply steps are in [VENDORED.md](../../third_party/rapier3d/VENDORED.md). The maintainer draft is [RAPIER_BUFFER_REUSE_UPSTREAM.md](RAPIER_BUFFER_REUSE_UPSTREAM.md) and is not filed upstream. That is the patched line for RUSTSEC-2026-0367, 0368, and 0369. `Cargo.lock` has no `zip` 1.1.4. There is no audit ignore for those three zip IDs. [PR #758](https://github.com/lazyxeon/AstraWeave/pull/758) pins `url` 2.5.9 and `form_urlencoded` 1.2.3, which that `url` release requires, moves `quinn-udp` to 0.5.16, and removes `chrono`. [#756](https://github.com/lazyxeon/AstraWeave/issues/756) tracks the `main` audit failure: privilege escalation, RUSTSEC-2026-0548 (`zip`); denial of service, RUSTSEC-2026-0538 (`quinn-udp`); unmaintained, RUSTSEC-2026-0543 (`chrono`). `url` 2.5.9 also fixes stack overflow, RUSTSEC-2026-0592, a later advisory. No ignore was added. #324 is closed. The fix is #353. #365 resolved RUSTSEC-2026-0370, 0371, and 0372 with no ignore: `eframe` is built without AccessKit, so screen readers do not receive the egui tree, and editor file dialogs are `rfd` 0.17 (`libdbus` or `zenity` on Linux). The editor `kittest` feature is gone. #368 covers the six toolbar and menu clicks with synthetic `RawInput` on a plain `egui::Context`. #366 stays open for step 2: bring `egui_kittest` back once `accesskit_unix` uses zbus 6. Drop the vendor directory and the `[patch.crates-io]` entry once candle upstream depends on `zip >= 9`. #217 removed `openssl` from the lockfile. `deny.toml` still bans `openssl` and `openssl-sys`. #219 and #256 are closed. #327 (`87fbe079`) drops `net` from the workspace `tokio` features. `astraweave-net`, `astraweave-ipc`, and `astraweave-net-ecs` opt in. #326 is closed. | | **Traces** | **31** subsystem traces under `docs/architecture/`, including `veil.md`, listed in the generated table in `CLAUDE.md`. The June "13 traces" figure is the original campaign, not the current set. | ### On main since the June snapshot diff --git a/docs/current/SECURITY_AUDIT.md b/docs/current/SECURITY_AUDIT.md index b89ba0b016..8819986c9b 100644 --- a/docs/current/SECURITY_AUDIT.md +++ b/docs/current/SECURITY_AUDIT.md @@ -2,7 +2,7 @@ > **2026-10-16 survey:** This survey is pinned to `f1109340`. #205, #214, #217, #244, #252, #275, #312, #316, #318, #325, #327, #329, and #331 are on main at `84d3888a`. Sentences below that say those pulls are not on main, or that `llm_dialogue.rs` is an undeclared orphan with `thread_rng`, are the survey, not the current tree. -> **Current as of 2026-10-21** (`main` @ `49d289eb` for the #388 and #397 sentences in this banner. The survey body was checked at `556a305c` unless a sentence names a later commit). #325 cleared the patched supply-chain advisories. #365 resolved RUSTSEC-2026-0370, 0371, and 0372 with no ignore. `eframe` is built without AccessKit. Editor file dialogs are `rfd` 0.17. The editor `kittest` feature is gone. #368 covers the six clicks with synthetic `RawInput`. #366 step 2, `egui_kittest`, waits on upstream AccessKit and zbus 6. The ignored leftovers are #305, #309, #310, and #321–#323. #308 no longer has an ignore: `wayland-scanner` 0.31.11 uses `quick-xml` 0.41.0. #306 no longer has an ignore: `mikktspace` uses its `glam` backend, so `nalgebra` 0.26 is gone. #320 no longer has an ignore: postcard is `default-features = false` plus `alloc`, so `atomic-polyfill` is gone. #320 is closed. The fix is #387. `rustls-webpki` is 0.103.16 and `webpki-roots` is 1.0.10. RUSTSEC-2026-0381 and RUSTSEC-2026-0382 are fixed with no ignore. #311 no longer has an ignore: `aw_trace_sync` parses trace front-matter with `yaml_serde`. #307 no longer has an ignore: `indicatif` 0.18 replaces `number_prefix`. #353 vendors `third_party/candle-core` (crates.io 0.8.4) pinned to `zip` 9.0.3. `zip` 1.1.4 is not in `Cargo.lock`. There is no audit ignore for RUSTSEC-2026-0367, 0368, or 0369. #324 is closed. The fix is #353. #217 closed #219 and #256: `openssl` is not in `Cargo.lock`, and `deny.toml` still bans it. #327 dropped `net` from the workspace `tokio` features. #326 is closed. `dig_sphere` applies a sphere `Subtract` brush (#329). The greybox golden is `b6a9d5a2c5da28a6` (#330). `gravity.rs` is deleted. #336 and #253 are closed. Greybox startup runs `run_aravath_slice` once (#275, #343). Each sword hit reuses that `sword_hp`. A checkpoint stores the demolition command log. #331 declares `llm_dialogue` and removes `thread_rng`. `recorded_line` is a pure helper with no non-test caller yet. `AIArbiter`, `GoapPlanner`, and `GravityManager` stay off the tick. #257 and #258 are closed. The fix is #382. #225 and #259 stay open. #253 is closed. The local field is required case `local_sim`. #340 closed #273 and #338. #333 closed #218. #254, #242, #314, #304, and #274 stay open. Profile `ci-pr` still excludes GPU render passes, lavapipe fluid smokes, and `test_qwen3_variants`. #388 (`43b1b48f`) closed #295. SEC-WEAVE-1 is on main: `queue_weave` returns `OutsideIsland` outside ±2048 cells and does not saturate. `meters_to_cell` returns `None` before the cast when the metre value is non-finite or `m * 1000` is below `i32::MIN as f32` or at or above `i32::MAX as f32`. `compile_legacy` drops those origins and a non-finite or non-positive-square wind delta. `push_ice` `debug_assert`s the island bound and still emits the sheet. In-range weaving replay bytes stay on `NullField`. #397 (`49d289eb`) closed #260. GitHub linked the issue to that pull. The mod host rejects an origin outside ±2048 before the cast is stored. A failed `run_one` drops that call's casts. An earlier script for the same agent that already returned `Ok` stays applied. +> **Current as of 2026-10-21** (`main` @ `49d289eb` for the #388 and #397 sentences in this banner. The survey body was checked at `556a305c` unless a sentence names a later commit or [PR #758](https://github.com/lazyxeon/AstraWeave/pull/758)). #325 cleared the patched supply-chain advisories. #365 resolved RUSTSEC-2026-0370, 0371, and 0372 with no ignore. `eframe` is built without AccessKit. Editor file dialogs are `rfd` 0.17. The editor `kittest` feature is gone. #368 covers the six clicks with synthetic `RawInput`. #366 step 2, `egui_kittest`, waits on upstream AccessKit and zbus 6. The ignored leftovers are #305, #309, #310, and #321–#323. #308 no longer has an ignore: `wayland-scanner` 0.31.11 uses `quick-xml` 0.41.0. #306 no longer has an ignore: `mikktspace` uses its `glam` backend, so `nalgebra` 0.26 is gone. #320 no longer has an ignore: postcard is `default-features = false` plus `alloc`, so `atomic-polyfill` is gone. #320 is closed. The fix is #387. `rustls-webpki` is 0.103.16 and `webpki-roots` is 1.0.10. RUSTSEC-2026-0381 and RUSTSEC-2026-0382 are fixed with no ignore. #311 no longer has an ignore: `aw_trace_sync` parses trace front-matter with `yaml_serde`. #307 no longer has an ignore: `indicatif` 0.18 replaces `number_prefix`. #353 vendors `third_party/candle-core` (crates.io 0.8.4) pinned to `zip` 9.7.0 ([PR #758](https://github.com/lazyxeon/AstraWeave/pull/758)). `zip` 1.1.4 is not in `Cargo.lock`. There is no audit ignore for RUSTSEC-2026-0367, 0368, or 0369. [PR #758](https://github.com/lazyxeon/AstraWeave/pull/758) pins `url` 2.5.9 and `form_urlencoded` 1.2.3, which that `url` release requires, moves `quinn-udp` to 0.5.16, and removes `chrono`. [#756](https://github.com/lazyxeon/AstraWeave/issues/756) tracks the `main` audit failure: privilege escalation, RUSTSEC-2026-0548 (`zip`); denial of service, RUSTSEC-2026-0538 (`quinn-udp`); unmaintained, RUSTSEC-2026-0543 (`chrono`). `url` 2.5.9 also fixes stack overflow, RUSTSEC-2026-0592, a later advisory. No ignore was added. #324 is closed. The fix is #353. #217 closed #219 and #256: `openssl` is not in `Cargo.lock`, and `deny.toml` still bans it. #327 dropped `net` from the workspace `tokio` features. #326 is closed. `dig_sphere` applies a sphere `Subtract` brush (#329). The greybox golden is `b6a9d5a2c5da28a6` (#330). `gravity.rs` is deleted. #336 and #253 are closed. Greybox startup runs `run_aravath_slice` once (#275, #343). Each sword hit reuses that `sword_hp`. A checkpoint stores the demolition command log. #331 declares `llm_dialogue` and removes `thread_rng`. `recorded_line` is a pure helper with no non-test caller yet. `AIArbiter`, `GoapPlanner`, and `GravityManager` stay off the tick. #257 and #258 are closed. The fix is #382. #225 and #259 stay open. #253 is closed. The local field is required case `local_sim`. #340 closed #273 and #338. #333 closed #218. #254, #242, #314, #304, and #274 stay open. Profile `ci-pr` still excludes GPU render passes, lavapipe fluid smokes, and `test_qwen3_variants`. #388 (`43b1b48f`) closed #295. SEC-WEAVE-1 is on main: `queue_weave` returns `OutsideIsland` outside ±2048 cells and does not saturate. `meters_to_cell` returns `None` before the cast when the metre value is non-finite or `m * 1000` is below `i32::MIN as f32` or at or above `i32::MAX as f32`. `compile_legacy` drops those origins and a non-finite or non-positive-square wind delta. `push_ice` `debug_assert`s the island bound and still emits the sheet. In-range weaving replay bytes stay on `NullField`. #397 (`49d289eb`) closed #260. GitHub linked the issue to that pull. The mod host rejects an origin outside ±2048 before the cast is stored. A failed `run_one` drops that call's casts. An earlier script for the same agent that already returned `Ok` stays applied. **Status:** Caps from this audit that already had a failing proof on `main` are landed. PR-side items stay on their branches. **Date:** 2026-10-15 **Secret scanning:** GitHub secret scanning and push protection are enabled on this repository. No further settings change is required for SEC-SUPPLY-2. @@ -216,7 +216,7 @@ Searched the LLM, quest, dialogue, memory, and coordination crates for `Command: | `load_persona_zip` | Yes | `load_persona_zip` is `astraweave-persona/src/lib.rs:56`. It opens a caller-supplied path (`:57`). Model text is not passed in. The zip member is selected by `by_name("persona_manifest.toml")`, so member names are not a traversal. The manifest is capped at 1 MiB (`MAX_PERSONA_MANIFEST_BYTES` at `:54`, with the zip budgets at `:52-53`). The size check is `:80-84` and the read is `take` at `:87-88`. Callers: `examples/persona_loader` and tests. | | PR #213 memory / RAG / persona | Not on `main` | `git grep` of `origin/pr213` under `astraweave-memory`, `astraweave-rag`, `astraweave-persona`, and `astraweave-npc` found no new `Command` or script eval. Persona still opens a path the caller passes. | -**SEC-LLM-2.** If a later PR wires `QuestLlmSystem` or `WorldEventGenerator` into the tick, model JSON becomes state with no byte cap and, for world events, no range check on the floats. `validation_script` must stay data. Do not pass it to Rhai. Quest ids are assigned with `Uuid::new_v4()` and timestamps with `Utc::now()` (`llm_quests.rs:433-434`). That is a wall clock. It is dormant. Do not move it onto the deterministic tick as part of the security fix. +**SEC-LLM-2.** If a later PR wires `QuestLlmSystem` or `WorldEventGenerator` into the tick, model JSON becomes state with no byte cap and, for world events, no range check on the floats. `validation_script` must stay data. Do not pass it to Rhai. Quest ids are assigned with `Uuid::new_v4()` and `generated_at` is set to `0` (`llm_quests.rs:433-434`). That field is a `u64`. The generator is dormant. Do not add a wall clock to the deterministic tick as part of the security fix. **SEC-LLM-3.** `OllamaClient::complete` prints the full prompt and the URL (`astraweave-llm/src/lib.rs:175-184`). That is S0-2, still live. `sanitize_llm_prompt` prefixes `"SAFE: "` and returns the original text (`astraweave-security/src/lib.rs:358-364`). `LLMValidator.allowed_domains` includes `openai.com` and `anthropic.com` (`:163-166`). The validator has no production caller. Delete those domains when the validator is touched so a future caller cannot treat them as policy. @@ -295,7 +295,7 @@ None in `aw-net-proto`, `astraweave-net`, or `astraweave-ipc`. `.github/workflows/security-audit.yml` runs on pushes and pull requests to `main` and `develop`, and on a Sunday cron. `contents: read`. Two jobs: - `cargo deny check` runs bans, sources, advisories, and licenses. `set -e` fails the job on the first error (`security-audit.yml:38-55`). -- `cargo audit` is `run: cargo audit` (`security-audit.yml:72`). The workflow step has no `--ignore`. cargo-audit 0.22.2 still reads `.cargo/audit.toml` and ignores six IDs: `RUSTSEC-2025-0141`, `RUSTSEC-2026-0249`, `RUSTSEC-2026-0192`, `RUSTSEC-2025-0057`, `RUSTSEC-2024-0384`, and `RUSTSEC-2024-0436` (`.cargo/audit.toml:14-29`). The same six are the `deny.toml` ignore array (`deny.toml:100-113`). Passing `cargo audit` still skips those six. +- `cargo audit` is `run: cargo audit` (`security-audit.yml:72`). The workflow step has no `--ignore`. cargo-audit 0.22.2 still reads `.cargo/audit.toml` and ignores six IDs: `RUSTSEC-2025-0141`, `RUSTSEC-2026-0249`, `RUSTSEC-2026-0192`, `RUSTSEC-2025-0057`, `RUSTSEC-2024-0384`, and `RUSTSEC-2024-0436` (`.cargo/audit.toml:23-39`). The same six are the `deny.toml` ignore array (`deny.toml:100-113`). Passing `cargo audit` still skips those six. `deny.toml`: diff --git a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md index 0e41c77a57..05e067b063 100644 --- a/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md +++ b/docs/current/SEMANTIC_AI_DECISION_DEBUGGER.md @@ -93,7 +93,7 @@ The trace copies the buffer the planner received. On `main` that includes the co On `main`, `astraweave-memory` is a full pipeline (records, episodes, consolidation, forgetting, retrieval, persona) and it is DORMANT for the planning tick. Nothing in `astraweave-ai` calls it. -`MemoryDebugComponent` (`astraweave-memory/src/components.rs`) looks like a debugger and is the wrong one to extend. `recent_operations` is a `Vec`. Each operation stores a `String` id, a `chrono` UTC timestamp, and a `String` detail. That is a wall clock and a heap growth on every operation. +`MemoryDebugComponent` (`astraweave-memory/src/components.rs`) looks like a debugger and is the wrong one to extend. `recent_operations` is a `Vec`. Each operation stores a `String` id, a UTC timestamp, and a `String` detail. That is a wall clock and a heap growth on every operation. PR #213 (`cursor/engine-ws-ai2`, draft, tip `61ebe2fa`) owns the wiring. `astraweave-dialogue/src/depth_tick.rs` on that branch defines `AiDepthState` and `sys_ai_depth`. One step calls `MemoryManager`, the embedding store, RAG consolidation, prompts, context, persona, the NPC `RulePlanner`, and coordination. A missing log line becomes `scripted:` plus the rendered prompt. `SimRng` is seeded with `(world_seed, tick, SIM_SYSTEM_LLM_DIALOGUE + entity)` and is not drawn. The branch's own `TickTrace` is a growing `Vec` of `String`s (`memory_ids`, prompt, dialogue, note). That trace allocates, and it is the depth tick's replay payload, so this debugger does not write into it and does not read it from inside `plan_route`. @@ -161,14 +161,14 @@ The hash this design adds is a local equality test (trace on versus trace off). `tools/aw_editor` has no AI decision panel. Debug panels today are `Console`, `Profiler`, `Performance`, and `SceneStats` (`tools/aw_editor/src/panel_type.rs`). `PanelType` is `#[non_exhaustive]`. Adding a variant touches every match in that file: `title`, `icon`, `is_closable`, `has_scroll`, `category`, `description`, `shortcut_hint`, `is_debug_panel`, and `all`. The Debug menu already iterates `PanelType::all()` (`tools/aw_editor/src/ui/menu_bar.rs`). `default_left_panels`, `default_right_panels`, `default_bottom_panels`, and `default_center_panel` stay as they are so dock tests keep their current tabs. The new panel opens from the menu and stays out of the default layout. -Editor CI on `main` is partly red, and both failures already have owners: +The table is the failure record this section was written against. #273 is closed (`aab4c84b`, #340). #265 stays open. Both editor workflows install `libudev-dev`, and the nightlies at `64da1085` passed every step of `editor-ci.yml` ([run 44691005363](https://github.com/lazyxeon/AstraWeave/actions/runs/44691005363)) and `aw-editor-tests.yml` ([run 44689787164](https://github.com/lazyxeon/AstraWeave/actions/runs/44689787164)). | Issue | Failure | Owner and plan | |---|---|---| | #273 `deferred-failure` | `editor_engine_render_parity` hashes diverge on llvmpipe. Engine and editor LDR SHA-256 differ; overlay isolation holds. Mean SAD 1.538 over 262144 pixels | Editor render parity. Find the setter that still differs for the 512×512 grassland fixture. Do not widen the assert | | #265 `deferred-failure` | Ubuntu and macOS editor jobs fail in `libudev-sys` because `libudev.pc` is missing | CI cleanup, PR #217. Install `pkg-config`, `libudev-dev`, and `libasound2-dev` | -`editor-ci.yml` and `aw-editor-tests.yml` on `main` still do not install `libudev-dev`. Both workflows set `continue-on-error: true` and do not run on pull requests. A decision panel in `aw_editor` would build in those jobs. This design leaves `tools/aw_editor` untouched until #265 and #273 are closed. +`editor-ci.yml` and `aw-editor-tests.yml` do not run on pull requests. Both install `libudev-dev`: `aw-editor-tests.yml` in its Linux apt step, and `editor-ci.yml` through `rust-ci-setup` (that action installs `libudev-dev`). Neither workflow sets job-level `continue-on-error`. In `aw-editor-tests.yml`, the `test` job still sets step-level `continue-on-error` on `--lib`, integration, fmt, and clippy, and the `coverage` job sets it on `Generate Coverage Report` and `Upload Coverage to Codecov`. The editor bin step is `cargo test --locked -p aw_editor --all-features --bins` in `ci.yml` job `Test (ubuntu, build archive)`, which the `PR Rust checks` job needs. Ruleset enforcement is tracked in [PR #702](https://github.com/lazyxeon/AstraWeave/pull/702). That job is skipped on a docs-only pull request and when no crate is selected (`full` is not set and the package list is empty). The step has no `continue-on-error`. `--bins` builds every bin harness, including `aw_game_runtime`, whose harness has no tests. A decision panel in `aw_editor` would build in those jobs. ### 2.8 Aravath agents that already exist @@ -192,7 +192,7 @@ Rejected: | Option | Why it loses | |---|---| -| Extend `MemoryDebugComponent` | `Vec`, `String`, and `chrono::Utc`. Wall clock in a sim debug path | +| Extend `MemoryDebugComponent` | `Vec`, `String`, and a UTC timestamp. Wall clock in a sim debug path | | Extend `goap::TelemetryCollector` | `String`, `VecDeque`, `Instant`, and it lives in the dormant advanced GOAP tree | | Send reasons through `message!` or `tracing` | Allocates when the sink is on, and a global subscriber can change timing | | Put the ring inside `SpatialTick` or `World` | A new field changes the bytes of a sim struct the moment the feature is on | diff --git a/examples/hello_companion/Cargo.toml b/examples/hello_companion/Cargo.toml index 069dd809ec..11d8821ec7 100644 --- a/examples/hello_companion/Cargo.toml +++ b/examples/hello_companion/Cargo.toml @@ -20,7 +20,9 @@ tokio = { workspace = true, optional = true } serde = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } reqwest = { workspace = true, optional = true } -chrono = { version = "0.4", features = ["serde"], optional = true } +time = { version = "0.3", optional = true } +# Marks the windowed entry so mutation testing leaves it alone. No runtime effect. +mutants = { version = "0.0.4", optional = true } # Visual demo dependencies (enable with --features visual) astraweave-render = { path = "../../astraweave-render", features = ["gltf-assets", "assets", "textures"], optional = true } @@ -39,6 +41,9 @@ egui-winit = { workspace = true, optional = true } egui-wgpu = { workspace = true, optional = true } rand = { workspace = true, optional = true } +[dev-dependencies] +time = { version = "0.3" } + [features] # mimalloc is on by default per the 2026-04-17 experiment (+43% FPS on the # profiling_demo reference workload; no regression on any measured bench). Opt @@ -49,7 +54,7 @@ default = ["fast-alloc"] fast-alloc = ["dep:astraweave-alloc", "astraweave-alloc/fast-alloc"] llm = ["astraweave-llm", "astraweave-llm/llm_cache", "tokio"] ollama = ["llm", "astraweave-llm/ollama", "reqwest", "serde_json"] -metrics = ["serde", "serde_json", "chrono"] +metrics = ["serde", "serde_json", "time"] llm_orchestrator = ["astraweave-ai/llm_orchestrator", "ollama"] decision-trace = ["astraweave-ai/decision-trace"] # Visual demo with full rendering + LLM support @@ -69,7 +74,8 @@ visual = [ "egui-wgpu", "rand", "ollama", - "tokio" + "tokio", + "dep:mutants", ] diff --git a/examples/hello_companion/src/main.rs b/examples/hello_companion/src/main.rs index 757f4163d3..377602b3dc 100644 --- a/examples/hello_companion/src/main.rs +++ b/examples/hello_companion/src/main.rs @@ -119,8 +119,6 @@ impl std::fmt::Display for AIMode { // METRICS TRACKING // ============================================================================ -#[cfg(feature = "metrics")] -use chrono::Utc; #[cfg(feature = "metrics")] use serde::{Deserialize, Serialize}; @@ -157,7 +155,7 @@ impl AIMetrics { mode: mode.to_string(), plan_steps, latency_ms, - timestamp: Utc::now().to_rfc3339(), + timestamp: format_utc_rfc3339(time::OffsetDateTime::now_utc()), success, error, tools_used: None, @@ -167,6 +165,7 @@ impl AIMetrics { } } + #[cfg(feature = "llm")] fn with_phase7_data( mut self, tools_used: Vec, @@ -186,7 +185,9 @@ impl AIMetrics { // MAIN ENTRY POINT // ============================================================================ +/// Opens a window and needs a GPU, so mutation testing leaves this entry alone. #[cfg(feature = "visual")] +#[mutants::skip] fn main() -> Result<()> { visual_demo::run_visual_demo() } @@ -201,10 +202,12 @@ fn main() -> Result<()> { // Parse command-line arguments let args: Vec = std::env::args().collect(); let demo_all = args.contains(&"--demo-all".to_string()); - let _show_metrics = args.contains(&"--metrics".to_string()); - let _export_metrics = args.contains(&"--export-metrics".to_string()); - #[cfg(feature = "metrics")] + let show_metrics = args.contains(&"--metrics".to_string()); + #[cfg(feature = "metrics")] + let export_metrics = args.contains(&"--export-metrics".to_string()); + + #[cfg(all(feature = "metrics", feature = "llm"))] let mut all_metrics: Vec = Vec::new(); if demo_all { @@ -274,7 +277,7 @@ fn main() -> Result<()> { #[cfg(feature = "metrics")] { if show_metrics { - print_metrics_table(&[metrics.clone()]); + print_metrics_table(std::slice::from_ref(&metrics)); } if export_metrics { export_metrics_to_files(&[metrics])?; @@ -409,7 +412,7 @@ fn run_single_demo(mode: AIMode) -> Result { println!("Enemy HP: {}", enemy_hp.hp); } - let mut metrics = AIMetrics::new( + let metrics = AIMetrics::new( &mode.to_string(), plan.steps.len(), latency_ms, @@ -418,10 +421,10 @@ fn run_single_demo(mode: AIMode) -> Result { ); #[cfg(feature = "llm")] - { + let metrics = { let tools = extract_tools_used(&plan); - metrics = metrics.with_phase7_data(tools, None, None, None); - } + metrics.with_phase7_data(tools, None, None, None) + }; Ok(metrics) } @@ -1424,3 +1427,113 @@ fn export_metrics_to_files(metrics: &[AIMetrics]) -> Result<()> { Ok(()) } + +#[cfg(any(feature = "metrics", test))] +/// Four digits for years `0..=9999`. Any other year keeps a sign and at least +/// four digits of magnitude. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +#[cfg(any(feature = "metrics", test))] +fn format_utc_rfc3339(dt: time::OffsetDateTime) -> String { + let utc = dt.to_offset(time::UtcOffset::UTC); + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + let nano = utc.nanosecond(); + if nano != 0 { + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } + } + out.push_str("+00:00"); + out +} + +#[cfg(any(feature = "metrics", test))] +mod utc_rfc3339_pins { + #[cfg_attr(not(test), allow(unused_imports))] + use super::{format_utc_rfc3339, year_text}; + + #[cfg_attr(not(test), allow(dead_code))] + fn at(nanos: i128) -> time::OffsetDateTime { + time::OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn rfc3339_matches_pinned_strings() { + assert_eq!(format_utc_rfc3339(at(0)), "2020-01-02T03:04:05+00:00"); + assert_eq!( + format_utc_rfc3339(at(100_000_000)), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(100_000)), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(1_000_000)), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(1)), + "2020-01-02T03:04:05.000000001+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(123_456_789)), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(123_400_000)), + "2020-01-02T03:04:05.123400+00:00" + ); + } + + #[cfg_attr(not(test), allow(dead_code))] + fn civil(year: i32) -> time::OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(format_utc_rfc3339(civil(-1)), "-0001-01-02T03:04:05+00:00"); + assert_eq!(format_utc_rfc3339(civil(0)), "0000-01-02T03:04:05+00:00"); + assert_eq!(format_utc_rfc3339(civil(9999)), "9999-01-02T03:04:05+00:00"); + assert_eq!( + format_utc_rfc3339(civil(-9999)), + "-9999-01-02T03:04:05+00:00" + ); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + } +} + +#[cfg(all(test, feature = "metrics"))] +mod metrics_tests { + use super::*; + + #[test] + fn single_demo_records_classical_metrics() { + let metrics = run_single_demo(AIMode::Classical).expect("classical demo"); + assert_eq!(metrics.mode, "Classical (RuleOrchestrator)"); + assert!(metrics.success); + assert!(!metrics.timestamp.is_empty()); + } +} diff --git a/examples/hello_companion/tests/console_demo.rs b/examples/hello_companion/tests/console_demo.rs new file mode 100644 index 0000000000..0c5b4a0f0e --- /dev/null +++ b/examples/hello_companion/tests/console_demo.rs @@ -0,0 +1,69 @@ +#![cfg(not(feature = "visual"))] + +use std::path::PathBuf; +use std::process::Command; + +/// Console `hello_companion` as nextest extracted it, or the compile-time path. +/// +/// `env!("CARGO_BIN_EXE_hello_companion")` is an absolute path on the machine +/// that compiled the test. Pull-request partitions run from the nextest +/// archive, which does not have that directory. Nextest puts the console +/// binary in the archive and sets `CARGO_BIN_EXE_hello_companion` and +/// `NEXTEST_BIN_EXE_hello_companion` to the extracted file. `cargo test` on +/// this toolchain does not set those, so the compile-time path is the fallback +/// when it still names a file. +fn console_binary() -> PathBuf { + for key in [ + "CARGO_BIN_EXE_hello_companion", + "NEXTEST_BIN_EXE_hello_companion", + ] { + let Some(raw) = std::env::var_os(key) else { + continue; + }; + if raw.is_empty() { + continue; + } + if let Some(path) = existing_exe(PathBuf::from(raw)) { + return path; + } + } + PathBuf::from(env!("CARGO_BIN_EXE_hello_companion")) +} + +/// `CARGO_BIN_EXE_*` already ends in `.exe` on Windows. Try that suffix when a +/// toolchain omits it. +fn existing_exe(path: PathBuf) -> Option { + if path.is_file() { + return Some(path); + } + if path + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("exe")) + { + return None; + } + let mut with_suffix = path.into_os_string(); + with_suffix.push(".exe"); + let exe = PathBuf::from(with_suffix); + if exe.is_file() { + Some(exe) + } else { + None + } +} + +#[test] +fn console_demo_prints_the_banner() { + let exe = console_binary(); + let output = Command::new(&exe).output().unwrap_or_else(|err| { + panic!("hello_companion starts at {}: {err}", exe.display()); + }); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "status {}\n{stdout}\n{stderr}", + output.status + ); + assert!(stdout.contains("AstraWeave AI Companion Demo"), "{stdout}"); +} diff --git a/scripts/ci/feature-gated-tests.sh b/scripts/ci/feature-gated-tests.sh new file mode 100755 index 0000000000..6a78af93a1 --- /dev/null +++ b/scripts/ci/feature-gated-tests.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Tests the default nextest archive does not compile. +# astraweave-memory's component module is cfg(feature = "bevy"). +# hello_companion's metrics demo is cfg(feature = "metrics"). +set -euo pipefail + +profile="${AW_CI_PROFILE:-ci-pr}" +full="${AW_CI_FULL:-false}" +pkgs=",${AW_CI_PACKAGES:-}," + +ran=false +if [ "$full" = "true" ] || [[ "$pkgs" == *",astraweave-memory,"* ]]; then + cargo nextest run --locked --profile "$profile" -p astraweave-memory --features bevy --lib + ran=true +fi +if [ "$full" = "true" ] || [[ "$pkgs" == *",hello_companion,"* ]]; then + cargo nextest run --locked --profile "$profile" -p hello_companion --features metrics + ran=true +fi +if [ "$ran" = false ]; then + echo "astraweave-memory and hello_companion are not in the affected set; skipping feature-gated tests" +fi diff --git a/third_party/candle-core/Cargo.toml b/third_party/candle-core/Cargo.toml index 0d84f999c6..11f96f6178 100644 --- a/third_party/candle-core/Cargo.toml +++ b/third_party/candle-core/Cargo.toml @@ -198,11 +198,11 @@ optional = true version = "0.7.2" features = ["derive"] -# zip >= 9.0.0 is the patched line for RUSTSEC-2026-0367, 0368, and 0369. -# 1.1.4 is yanked and still vulnerable. default-features stays off, matching -# the crates.io 0.8.4 crate, so this copy does not enable new codecs. +# Pinned to the workspace zip release. Older lines are unpatched. +# default-features stays off, matching the crates.io 0.8.4 crate, so this +# copy does not enable new codecs. [dependencies.zip] -version = "=9.0.3" +version = "=9.7.0" default-features = false [dev-dependencies.anyhow] diff --git a/tools/ASSET_SIGNING_DESIGN.md b/tools/ASSET_SIGNING_DESIGN.md index a2fbb20f55..9f529a7656 100644 --- a/tools/ASSET_SIGNING_DESIGN.md +++ b/tools/ASSET_SIGNING_DESIGN.md @@ -425,8 +425,8 @@ async fn sign_with_kms(data: &[u8], key_id: &str) -> Result> { struct RootKeyRotation { old_root_pubkey: [u8; 32], new_root_pubkey: [u8; 32], - rotation_date: DateTime, - grace_period_end: DateTime, + rotation_date: time::OffsetDateTime, + grace_period_end: time::OffsetDateTime, signature_over_new: Vec, // Signed by old root key } ``` @@ -477,7 +477,7 @@ jobs: struct RevocationCertificate { revoked_pubkey: [u8; 32], reason: RevocationReason, - revocation_date: DateTime, + revocation_date: time::OffsetDateTime, signature: Vec, // Signed by root key } @@ -1003,8 +1003,8 @@ struct KeyCertificate { subject_pubkey: [u8; 32], subject_role: String, // "dev", "ci", "production" issuer_pubkey: [u8; 32], // Root key - valid_from: DateTime, - valid_until: DateTime, + valid_from: time::OffsetDateTime, + valid_until: time::OffsetDateTime, signature: Vec, // Signed by issuer } ``` @@ -1351,7 +1351,7 @@ cryptoki = "0.6" # PKCS11 (for YubiKey/HSM) ed25519-dalek = "2.0" # Already present sha2 = "0.10" # Already present serde = { version = "1", features = ["derive"] } -chrono = "0.4" # Timestamps, expiry +time = { version = "0.3", features = ["formatting"] } # Timestamps, expiry ``` ### 11.4 Testing Strategy @@ -1632,7 +1632,8 @@ pub fn sign_asset_file( asset_hash: hash_hex, signature: sig_b64, signer_role: key_role.to_string(), - signed_at: chrono::Utc::now().to_rfc3339(), + // `aw_asset_cli` writes this with `format_utc_rfc3339`, which ends in `+00:00`. + signed_at: format_utc_rfc3339(time::OffsetDateTime::now_utc()), tool_version: env!("CARGO_PKG_VERSION").to_string(), }) } diff --git a/tools/astraweave-assets/Cargo.toml b/tools/astraweave-assets/Cargo.toml index 25fce16dbc..ab93569d2d 100644 --- a/tools/astraweave-assets/Cargo.toml +++ b/tools/astraweave-assets/Cargo.toml @@ -41,7 +41,7 @@ serde_json = "1.0" prettytable-rs = "0.10" # Timestamps -chrono = { version = "0.4", features = ["serde"] } +time = "0.3" # Async stream utilities futures-util = "0.3" diff --git a/tools/astraweave-assets/src/kenney_provider.rs b/tools/astraweave-assets/src/kenney_provider.rs index 0c71c294e7..fe9fd77c51 100644 --- a/tools/astraweave-assets/src/kenney_provider.rs +++ b/tools/astraweave-assets/src/kenney_provider.rs @@ -261,7 +261,10 @@ impl AssetProvider for KenneyProvider { output.push_str( "However, attribution is appreciated: 'Assets by Kenney.nl (www.kenney.nl)'\n", ); - output.push_str(&format!("Generated: {}\n", chrono::Utc::now().to_rfc3339())); + output.push_str(&format!( + "Generated: {}\n", + crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()) + )); output } diff --git a/tools/astraweave-assets/src/lib.rs b/tools/astraweave-assets/src/lib.rs index 4e2a6e6616..88d18115e7 100644 --- a/tools/astraweave-assets/src/lib.rs +++ b/tools/astraweave-assets/src/lib.rs @@ -14,6 +14,8 @@ pub use summary::FetchSummary; use std::path::Path; +mod utc_stamp; + pub mod config; pub mod direct_url_provider; pub mod downloader; diff --git a/tools/astraweave-assets/src/organize.rs b/tools/astraweave-assets/src/organize.rs index e70f3e76ad..51a9f9559d 100644 --- a/tools/astraweave-assets/src/organize.rs +++ b/tools/astraweave-assets/src/organize.rs @@ -92,7 +92,7 @@ impl AssetOrganizer { urls, paths, hashes, - timestamp: chrono::Utc::now().to_rfc3339(), + timestamp: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), resolved_res: asset.resolution.clone(), }; @@ -318,7 +318,7 @@ impl AssetOrganizer { urls, paths, hashes, - timestamp: chrono::Utc::now().to_rfc3339(), + timestamp: crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()), resolved_res: asset .metadata .get("resolution") diff --git a/tools/astraweave-assets/src/provider.rs b/tools/astraweave-assets/src/provider.rs index 5b921dbeaf..dc1603c8af 100644 --- a/tools/astraweave-assets/src/provider.rs +++ b/tools/astraweave-assets/src/provider.rs @@ -581,7 +581,10 @@ pub fn generate_attribution_file( lines.push(String::new()); if existing_footer.is_empty() { lines.push("For full license texts, see URLs above.".to_string()); - lines.push(format!("Generated: {}", chrono::Utc::now().to_rfc3339())); + lines.push(format!( + "Generated: {}", + crate::utc_stamp::format_utc_rfc3339(time::OffsetDateTime::now_utc()) + )); } else { lines.extend(existing_footer); } diff --git a/tools/astraweave-assets/src/utc_stamp.rs b/tools/astraweave-assets/src/utc_stamp.rs new file mode 100644 index 0000000000..7d1704f6f2 --- /dev/null +++ b/tools/astraweave-assets/src/utc_stamp.rs @@ -0,0 +1,132 @@ +//! UTC text with the same digits the previous clock wrote. +//! +//! A whole second has no fraction. Milliseconds use three digits, microseconds +//! six, and anything finer nine. `zulu` selects the `Z` suffix; otherwise the +//! suffix is `+00:00`. Years in `0..=9999` use four digits. Every other year +//! keeps a sign and at least four digits of magnitude. +use time::{OffsetDateTime, UtcOffset}; + +/// Four digits for years `0..=9999`. Any other year keeps a sign and at least +/// four digits of magnitude. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub(crate) fn format_utc_rfc3339(dt: OffsetDateTime) -> String { + format_utc(dt, false) +} + +pub(crate) fn format_utc(dt: OffsetDateTime, zulu: bool) -> String { + let utc = dt.to_offset(UtcOffset::UTC); + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + push_fraction(&mut out, utc.nanosecond()); + if zulu { + out.push('Z'); + } else { + out.push_str("+00:00"); + } + out +} + +fn push_fraction(out: &mut String, nano: u32) { + if nano == 0 { + return; + } + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(nanos: i128) -> OffsetDateTime { + OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn utc_text_matches_pinned_strings() { + assert_eq!(format_utc(at(0), false), "2020-01-02T03:04:05+00:00"); + assert_eq!(format_utc(at(0), true), "2020-01-02T03:04:05Z"); + assert_eq!( + format_utc(at(100_000_000), false), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!( + format_utc(at(100_000_000), true), + "2020-01-02T03:04:05.100Z" + ); + assert_eq!( + format_utc(at(100_000), false), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!(format_utc(at(100_000), true), "2020-01-02T03:04:05.000100Z"); + assert_eq!( + format_utc(at(1_000_000), false), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!(format_utc(at(1_000_000), true), "2020-01-02T03:04:05.001Z"); + assert_eq!( + format_utc(at(1), false), + "2020-01-02T03:04:05.000000001+00:00" + ); + assert_eq!(format_utc(at(1), true), "2020-01-02T03:04:05.000000001Z"); + assert_eq!( + format_utc(at(123_456_789), false), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + format_utc(at(123_456_789), true), + "2020-01-02T03:04:05.123456789Z" + ); + assert_eq!( + format_utc(at(123_400_000), false), + "2020-01-02T03:04:05.123400+00:00" + ); + assert_eq!( + format_utc(at(123_400_000), true), + "2020-01-02T03:04:05.123400Z" + ); + assert_eq!( + format_utc_rfc3339(at(100_000_000)), + "2020-01-02T03:04:05.100+00:00" + ); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(format_utc(civil(-1), true), "-0001-01-02T03:04:05Z"); + assert_eq!(format_utc(civil(-1), false), "-0001-01-02T03:04:05+00:00"); + assert_eq!(format_utc(civil(0), true), "0000-01-02T03:04:05Z"); + assert_eq!(format_utc(civil(9999), true), "9999-01-02T03:04:05Z"); + assert_eq!(format_utc(civil(-9999), true), "-9999-01-02T03:04:05Z"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + assert_eq!(year_text(-1), "-0001"); + assert_eq!(year_text(2020), "2020"); + assert_eq!(format_utc_rfc3339(civil(-1)), "-0001-01-02T03:04:05+00:00"); + } +} diff --git a/tools/astraweave-assets/tests/lib_api_tests.rs b/tools/astraweave-assets/tests/lib_api_tests.rs index 722a6e46c3..ad7378d0ba 100644 --- a/tools/astraweave-assets/tests/lib_api_tests.rs +++ b/tools/astraweave-assets/tests/lib_api_tests.rs @@ -569,7 +569,7 @@ fn create_cached_lockfile(manifest: &AssetManifest, handle: &str, paths: Vec<(&s urls: url_map, paths: path_map, hashes: HashMap::new(), - timestamp: chrono::Utc::now().to_rfc3339(), + timestamp: "2020-01-02T03:04:05+00:00".to_string(), resolved_res: "1k".to_string(), }; @@ -765,7 +765,7 @@ async fn test_ensure_asset_partial_cache_redownloads() { urls: url_map, paths: path_map, hashes: HashMap::new(), - timestamp: chrono::Utc::now().to_rfc3339(), + timestamp: "2020-01-02T03:04:05+00:00".to_string(), resolved_res: "1k".to_string(), }; diff --git a/tools/aw_asset_cli/Cargo.toml b/tools/aw_asset_cli/Cargo.toml index 5758986499..4406d670d5 100644 --- a/tools/aw_asset_cli/Cargo.toml +++ b/tools/aw_asset_cli/Cargo.toml @@ -24,7 +24,7 @@ astraweave-security = { workspace = true } notify = "8" flate2 = "1" # for compression base64 = "0.22" -chrono = "0.4" +time = "0.3" asset_signing = { path = "../asset_signing" } ktx2 = "0.4" # for KTX2 texture container format # ktx2-rw = "0.2" # for writing true KTX2 files (requires cmake, temporarily disabled) diff --git a/tools/aw_asset_cli/src/main.rs b/tools/aw_asset_cli/src/main.rs index 61c533e283..3e74288ef1 100644 --- a/tools/aw_asset_cli/src/main.rs +++ b/tools/aw_asset_cli/src/main.rs @@ -523,7 +523,7 @@ fn sign_manifest(manifest: &[ManifestEntry]) -> Result { entries: manifest.to_vec(), signature, public_key: Some(public_key_pem), - signed_at: Some(chrono::Utc::now().to_rfc3339()), + signed_at: Some(format_utc_rfc3339(time::OffsetDateTime::now_utc())), }) } @@ -708,3 +708,95 @@ mod gltf_jail_tests { let _ = fs::remove_dir_all(&dir); } } + +/// Four digits for years `0..=9999`. Any other year keeps a sign and at least +/// four digits of magnitude. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +fn format_utc_rfc3339(dt: time::OffsetDateTime) -> String { + let utc = dt.to_offset(time::UtcOffset::UTC); + let mut out = format!( + "{}-{:02}-{:02}T{:02}:{:02}:{:02}", + year_text(utc.year()), + u8::from(utc.month()), + utc.day(), + utc.hour(), + utc.minute(), + utc.second() + ); + let nano = utc.nanosecond(); + if nano != 0 { + if nano % 1_000_000 == 0 { + out.push_str(&format!(".{:03}", nano / 1_000_000)); + } else if nano % 1_000 == 0 { + out.push_str(&format!(".{:06}", nano / 1_000)); + } else { + out.push_str(&format!(".{nano:09}")); + } + } + out.push_str("+00:00"); + out +} + +#[cfg(test)] +mod utc_rfc3339_pins { + use super::{format_utc_rfc3339, year_text}; + + fn at(nanos: i128) -> time::OffsetDateTime { + time::OffsetDateTime::from_unix_timestamp_nanos(1_577_934_245_000_000_000 + nanos).unwrap() + } + + #[test] + fn rfc3339_matches_pinned_strings() { + assert_eq!(format_utc_rfc3339(at(0)), "2020-01-02T03:04:05+00:00"); + assert_eq!( + format_utc_rfc3339(at(100_000_000)), + "2020-01-02T03:04:05.100+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(100_000)), + "2020-01-02T03:04:05.000100+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(1_000_000)), + "2020-01-02T03:04:05.001+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(1)), + "2020-01-02T03:04:05.000000001+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(123_456_789)), + "2020-01-02T03:04:05.123456789+00:00" + ); + assert_eq!( + format_utc_rfc3339(at(123_400_000)), + "2020-01-02T03:04:05.123400+00:00" + ); + } + + fn civil(year: i32) -> time::OffsetDateTime { + let date = time::Date::from_calendar_date(year, time::Month::January, 2).unwrap(); + let clock = time::Time::from_hms(3, 4, 5).unwrap(); + time::PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(format_utc_rfc3339(civil(-1)), "-0001-01-02T03:04:05+00:00"); + assert_eq!(format_utc_rfc3339(civil(0)), "0000-01-02T03:04:05+00:00"); + assert_eq!(format_utc_rfc3339(civil(9999)), "9999-01-02T03:04:05+00:00"); + assert_eq!( + format_utc_rfc3339(civil(-9999)), + "-9999-01-02T03:04:05+00:00" + ); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + } +} diff --git a/tools/aw_build/Cargo.toml b/tools/aw_build/Cargo.toml index 602df8673e..9ddf3ee609 100644 --- a/tools/aw_build/Cargo.toml +++ b/tools/aw_build/Cargo.toml @@ -14,7 +14,7 @@ sha2 = "0.10" hex = "0.4" serde = { version = "1", features = ["derive"] } serde_json = "1" -zip = { version = "9.0", default-features = false, features = ["deflate"] } +zip = { version = "9.7.0", default-features = false, features = ["deflate"] } time = { version = "0.3", features = ["formatting","macros"] } [dev-dependencies] diff --git a/tools/aw_editor/Cargo.toml b/tools/aw_editor/Cargo.toml index e022117c0e..567e79fc1d 100644 --- a/tools/aw_editor/Cargo.toml +++ b/tools/aw_editor/Cargo.toml @@ -67,7 +67,7 @@ rayon = "1.11" rfd = "0.17" tracing = { workspace = true } tracing-subscriber = { version = "0.3", features = ["env-filter"] } -chrono = "0.4" +time = { version = "0.3", features = ["local-offset"] } pollster = "0.4" astract = { path = "../../crates/astract" } astraweave-core = { path = "../../astraweave-core" } @@ -142,7 +142,6 @@ path = "src/lib.rs" [[bin]] name = "aw_editor" path = "src/main.rs" -test = false bench = false [[bin]] diff --git a/tools/aw_editor/WORLD_CLASS_EDITOR_PLAN.md b/tools/aw_editor/WORLD_CLASS_EDITOR_PLAN.md index df917209e5..7cc95996d0 100644 --- a/tools/aw_editor/WORLD_CLASS_EDITOR_PLAN.md +++ b/tools/aw_editor/WORLD_CLASS_EDITOR_PLAN.md @@ -362,8 +362,9 @@ fn on_close_request(&mut self) -> bool { // Auto-save every 5 minutes to .autosave/ fn auto_save(&mut self) { if self.auto_save_enabled && self.is_dirty { + let timestamp = local_clock::compact(local_clock::now()); let backup_path = self.content_root.join(".autosave") - .join(format!("scene_{}.ron", chrono::Utc::now().format("%Y%m%d_%H%M%S"))); + .join(format!("scene_{timestamp}.autosave.scene.ron")); // Keep last 3 auto-saves } } diff --git a/tools/aw_editor/src/lib.rs b/tools/aw_editor/src/lib.rs index 46713e33aa..194b981225 100644 --- a/tools/aw_editor/src/lib.rs +++ b/tools/aw_editor/src/lib.rs @@ -22,6 +22,7 @@ pub mod file_helpers; pub mod file_watcher; pub mod game_project; pub mod level_doc; +pub mod local_clock; pub mod movement_scripts; pub mod panel_type; pub mod panels; @@ -33,6 +34,7 @@ pub mod rhai_reload; pub mod runtime; pub mod scene_serialization; pub mod scene_state; +pub mod session_files; pub mod tab_viewer; pub mod terrain_integration; pub mod ui; diff --git a/tools/aw_editor/src/local_clock.rs b/tools/aw_editor/src/local_clock.rs new file mode 100644 index 0000000000..ce2e8db36a --- /dev/null +++ b/tools/aw_editor/src/local_clock.rs @@ -0,0 +1,81 @@ +//! Wall-clock stamps for autosave names and the session lock file. +//! +//! The numbers are the local civil time. If the platform cannot report a local +//! offset, the stamp uses UTC. + +use time::OffsetDateTime; + +/// Four digits for years `0..=9999`. Any other year keeps a sign and at least +/// four digits of magnitude. +fn year_text(year: i32) -> String { + if !(0..=9999).contains(&year) { + format!("{year:+05}") + } else { + format!("{year:04}") + } +} + +pub fn now() -> OffsetDateTime { + OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()) +} + +pub fn compact(dt: OffsetDateTime) -> String { + format!( + "{}{:02}{:02}_{:02}{:02}{:02}", + year_text(dt.year()), + u8::from(dt.month()), + dt.day(), + dt.hour(), + dt.minute(), + dt.second() + ) +} + +pub fn readable(dt: OffsetDateTime) -> String { + format!( + "{}-{:02}-{:02} {:02}:{:02}:{:02}", + year_text(dt.year()), + u8::from(dt.month()), + dt.day(), + dt.hour(), + dt.minute(), + dt.second() + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; + + fn wall(offset_hours: i8) -> OffsetDateTime { + let date = Date::from_calendar_date(2020, Month::January, 2).unwrap(); + let time_of_day = Time::from_hms(3, 4, 5).unwrap(); + PrimitiveDateTime::new(date, time_of_day) + .assume_offset(UtcOffset::from_hms(offset_hours, 0, 0).unwrap()) + } + + #[test] + fn wall_clock_stamps_keep_the_civil_time() { + assert_eq!(compact(wall(-5)), "20200102_030405"); + assert_eq!(readable(wall(-5)), "2020-01-02 03:04:05"); + assert_eq!(compact(wall(0)), "20200102_030405"); + assert_eq!(readable(wall(0)), "2020-01-02 03:04:05"); + } + + fn civil(year: i32) -> OffsetDateTime { + let date = Date::from_calendar_date(year, Month::January, 2).unwrap(); + let clock = Time::from_hms(3, 4, 5).unwrap(); + PrimitiveDateTime::new(date, clock).assume_utc() + } + + #[test] + fn year_width_keeps_a_sign_and_four_digit_magnitude() { + assert_eq!(compact(civil(-1)), "-00010102_030405"); + assert_eq!(readable(civil(-1)), "-0001-01-02 03:04:05"); + assert_eq!(compact(civil(0)), "00000102_030405"); + assert_eq!(readable(civil(9999)), "9999-01-02 03:04:05"); + assert_eq!(year_text(10_000), "+10000"); + assert_eq!(year_text(-10_000), "-10000"); + } +} diff --git a/tools/aw_editor/src/main.rs b/tools/aw_editor/src/main.rs index 06d477a5c0..17e13ba42b 100644 --- a/tools/aw_editor/src/main.rs +++ b/tools/aw_editor/src/main.rs @@ -56,6 +56,7 @@ mod gizmo; mod interaction; // Phase 8.1 Week 5 Day 3 - Gizmo interaction helpers (auto-tracking) #[allow(dead_code)] mod level_doc; // Level document types +mod local_clock; #[allow(dead_code)] mod material_inspector; #[allow(dead_code)] @@ -76,6 +77,7 @@ mod runtime; // Week 4 - Deterministic runtime integration mod scene_serialization; // Phase 2.2 - Scene Save/Load #[allow(dead_code)] mod scene_state; // Week 1 - Canonical edit-mode world owner +mod session_files; #[allow(dead_code)] mod splash; // Startup splash screen with logo + cinematic video mod subsystems; @@ -1194,118 +1196,6 @@ impl EditorApp { } } - /// Week 7: Enhanced auto-save with timestamped backups in .autosave/ directory - fn perform_auto_save(&mut self) { - if let Some(world) = self.edit_world() { - let auto_save_path = if self.auto_save_to_separate_dir { - // Save to .autosave/ directory with timestamp - let autosave_dir = self.content_root.join(".autosave"); - if let Err(e) = fs::create_dir_all(&autosave_dir) { - self.toast_error(format!("Failed to create autosave dir: {}", e)); - return; - } - - // Generate timestamped filename - let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S"); - let base_name = self - .current_scene_path - .as_ref() - .and_then(|p| p.file_stem()) - .and_then(|s| s.to_str()) - .unwrap_or("untitled"); - let filename = format!("{}_{}.autosave.scene.ron", base_name, timestamp); - autosave_dir.join(filename) - } else { - // Save to scene path or default - self.current_scene_path - .clone() - .unwrap_or_else(|| self.content_root.join("scenes/autosave.scene.ron")) - }; - - match scene_serialization::save_scene_with_overlay( - world, - &self.entity_manager, - &auto_save_path, - ) { - Ok(()) => { - self.last_auto_save = std::time::Instant::now(); - let filename = auto_save_path - .file_name() - .unwrap_or_default() - .to_string_lossy(); - self.toast_info(format!("Auto-saved: {}", filename)); - self.log(format!("Auto-saved to {}", filename)); - - // Cleanup old auto-saves if using separate directory - if self.auto_save_to_separate_dir { - self.cleanup_old_autosaves(); - } - } - Err(e) => { - self.toast_error(format!("Auto-save failed: {}", e)); - self.log(format!("Auto-save failed: {}", e)); - } - } - } - } - - /// Week 7: Remove old auto-save files, keeping only the most recent N - fn cleanup_old_autosaves(&mut self) { - let autosave_dir = self.content_root.join(".autosave"); - if !autosave_dir.exists() { - return; - } - - // Get the base name of the current scene - let base_name = self - .current_scene_path - .as_ref() - .and_then(|p| p.file_stem()) - .and_then(|s| s.to_str()) - .unwrap_or("untitled"); - - // Collect matching auto-save files - let mut autosaves: Vec<_> = match fs::read_dir(&autosave_dir) { - Ok(entries) => entries - .filter_map(|e| { - e.map_err(|err| tracing::debug!("Autosave dir entry error: {}", err)) - .ok() - }) - .map(|e| e.path()) - .filter(|p| { - p.file_name() - .and_then(|n| n.to_str()) - .map(|s| s.starts_with(base_name) && s.ends_with(".autosave.scene.ron")) - .unwrap_or(false) - }) - .collect(), - Err(_) => return, - }; - - // Sort by modification time (newest first) - autosaves.sort_by(|a, b| { - let a_time = fs::metadata(a).and_then(|m| m.modified()).ok(); - let b_time = fs::metadata(b).and_then(|m| m.modified()).ok(); - b_time.cmp(&a_time) - }); - - // Remove older files beyond keep_count - for old_file in autosaves.iter().skip(self.auto_save_keep_count) { - if let Err(e) = fs::remove_file(old_file) { - self.log(format!( - "Failed to remove old autosave {:?}: {}", - old_file.file_name().unwrap_or_default(), - e - )); - } else { - self.log(format!( - "Removed old autosave: {:?}", - old_file.file_name().unwrap_or_default() - )); - } - } - } - /// Week 7: Get the most recent auto-save file for crash recovery pub fn get_most_recent_autosave(&self) -> Option { let autosave_dir = self.content_root.join(".autosave"); @@ -1345,25 +1235,6 @@ impl EditorApp { autosaves.into_iter().next() } - /// Week 7 Day 5: Create lock file to detect crashes - fn create_lock_file(&self) { - use std::io::Write; - - // Create or overwrite lock file with current session info - if let Ok(mut file) = fs::File::create(&self.lock_file_path) { - let session_info = format!( - "pid={}\nstarted={}\nscene={}\n", - std::process::id(), - chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), - self.current_scene_path - .as_ref() - .and_then(|p| p.to_str()) - .unwrap_or("Untitled") - ); - let _ = file.write_all(session_info.as_bytes()); - } - } - /// Week 7 Day 5: Remove lock file on clean exit fn remove_lock_file(&self) { let _ = fs::remove_file(&self.lock_file_path); @@ -1419,7 +1290,13 @@ impl EditorApp { // Clear the recovery state and create new lock file self.show_recovery_dialog = false; self.remove_lock_file(); - self.create_lock_file(); + session_files::write_lock_file( + &self.lock_file_path, + self.current_scene_path + .as_ref() + .and_then(|path| path.to_str()) + .unwrap_or("Untitled"), + ); } } @@ -1428,7 +1305,13 @@ impl EditorApp { self.recovery_autosave_path = None; self.show_recovery_dialog = false; self.remove_lock_file(); - self.create_lock_file(); + session_files::write_lock_file( + &self.lock_file_path, + self.current_scene_path + .as_ref() + .and_then(|path| path.to_str()) + .unwrap_or("Untitled"), + ); self.console_logs .push("Recovery declined - starting fresh".to_string()); } @@ -2928,7 +2811,13 @@ impl EditorApp { } // Week 7 Day 5: Create lock file for this session - app.create_lock_file(); + session_files::write_lock_file( + &app.lock_file_path, + app.current_scene_path + .as_ref() + .and_then(|path| path.to_str()) + .unwrap_or("Untitled"), + ); Ok(app) } @@ -10122,7 +10011,35 @@ impl eframe::App for EditorApp { && self.is_dirty && self.last_auto_save.elapsed().as_secs_f32() > self.auto_save_interval_secs { - self.perform_auto_save(); + let saved = { + let world = self.edit_world(); + session_files::write_autosave(session_files::AutosaveRequest { + world, + entities: &self.entity_manager, + content_root: &self.content_root, + scene_path: self.current_scene_path.as_deref(), + separate_dir: self.auto_save_to_separate_dir, + keep_count: self.auto_save_keep_count, + }) + }; + match saved { + Ok(None) => {} + Ok(Some(saved)) => { + self.last_auto_save = std::time::Instant::now(); + self.toast_info(format!("Auto-saved: {}", saved.filename)); + self.log(format!("Auto-saved to {}", saved.filename)); + for note in saved.notes { + self.log(note); + } + } + Err(session_files::AutosaveError::Directory(message)) => { + self.toast_error(message); + } + Err(session_files::AutosaveError::Save(message)) => { + self.toast_error(message.clone()); + self.log(message); + } + } } // Render modal dialogs @@ -10419,3 +10336,74 @@ fn main() -> Result<()> { .map_err(|e| anyhow::anyhow!("Failed to run eframe: {}", e))?; Ok(()) } + +#[cfg(test)] +mod recovery_tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let dir = PathBuf::from("target") + .join("aw-editor-recovery") + .join(name); + fs::create_dir_all(&dir).expect("scratch dir"); + dir + } + + fn app_in(dir: &std::path::Path) -> EditorApp { + let mut app = EditorApp::default(); + app.lock_file_path = dir.join("session.lock"); + app.recent_files.set_storage_path(dir.join("recent.json")); + app.splash = None; + app + } + + #[test] + fn recover_from_autosave_loads_the_scene_and_clears_the_dialog() { + let dir = scratch("recover"); + let scene = dir.join("recovered.scene.ron"); + scene_serialization::save_scene(&World::new(), &scene).expect("save"); + let mut app = app_in(&dir); + app.recovery_autosave_path = Some(scene.clone()); + app.show_recovery_dialog = true; + + app.recover_from_autosave(); + + assert!(!app.show_recovery_dialog); + assert!(app.recovery_autosave_path.is_none()); + assert_eq!(app.current_scene_path.as_deref(), Some(scene.as_path())); + assert!(app.status.starts_with("Loaded:")); + assert!(app.lock_file_path.is_file()); + } + + #[test] + fn decline_recovery_drops_the_offer_and_logs_it() { + let dir = scratch("decline"); + let mut app = app_in(&dir); + app.recovery_autosave_path = Some(dir.join("stale.scene.ron")); + app.show_recovery_dialog = true; + + app.decline_recovery(); + + assert!(app.recovery_autosave_path.is_none()); + assert!(!app.show_recovery_dialog); + assert!(app + .console_logs + .iter() + .any(|line| line.contains("Recovery declined"))); + assert!(app.lock_file_path.is_file()); + } + + #[test] + fn one_update_records_a_frame() { + let dir = scratch("update"); + let mut app = app_in(&dir); + let ctx = egui::Context::default(); + let mut frame = eframe::Frame::_new_kittest(); + let _ = ctx.run(egui::RawInput::default(), |ctx| { + eframe::App::update(&mut app, ctx, &mut frame); + }); + assert!(app.style_applied); + assert_eq!(app.startup_assert_frames, 29); + assert!(app.last_update_end.is_some()); + } +} diff --git a/tools/aw_editor/src/material_inspector.rs b/tools/aw_editor/src/material_inspector.rs index aa48b5b343..1a2394fbed 100644 --- a/tools/aw_editor/src/material_inspector.rs +++ b/tools/aw_editor/src/material_inspector.rs @@ -1465,7 +1465,7 @@ mod tests { #[test] fn test_display_mode_name() { - assert_eq!(DisplayMode::Combined.name(), "Combined"); + assert_eq!(DisplayMode::Split.name(), "Split View"); assert_eq!(DisplayMode::Albedo.name(), "Albedo"); assert_eq!(DisplayMode::Normal.name(), "Normal"); assert_eq!(DisplayMode::Orm.name(), "ORM"); @@ -1480,15 +1480,15 @@ mod tests { #[test] fn test_display_mode_shortcut() { - assert_eq!(DisplayMode::Combined.shortcut(), "C"); - assert_eq!(DisplayMode::Albedo.shortcut(), "A"); - assert_eq!(DisplayMode::Normal.shortcut(), "N"); - assert_eq!(DisplayMode::Orm.shortcut(), "O"); + assert_eq!(DisplayMode::Split.shortcut(), "4"); + assert_eq!(DisplayMode::Albedo.shortcut(), "1"); + assert_eq!(DisplayMode::Normal.shortcut(), "2"); + assert_eq!(DisplayMode::Orm.shortcut(), "3"); } #[test] fn test_display_mode_is_single_texture() { - assert!(!DisplayMode::Combined.is_single_texture()); + assert!(!DisplayMode::Split.is_single_texture()); assert!(DisplayMode::Albedo.is_single_texture()); assert!(DisplayMode::Normal.is_single_texture()); assert!(DisplayMode::Orm.is_single_texture()); @@ -1496,8 +1496,8 @@ mod tests { #[test] fn test_display_mode_display() { - assert_eq!(format!("{}", DisplayMode::Combined), "Combined"); - assert_eq!(format!("{}", DisplayMode::Albedo), "Albedo"); + assert_eq!(format!("{}", DisplayMode::Split), "⊞ Split View"); + assert_eq!(format!("{}", DisplayMode::Albedo), "[Art] Albedo"); } // ==================================================================== @@ -1512,7 +1512,7 @@ mod tests { #[test] fn test_channel_filter_name() { - assert_eq!(ChannelFilter::RGBA.name(), "RGBA"); + assert_eq!(ChannelFilter::All.name(), "RGB"); assert_eq!(ChannelFilter::Red.name(), "Red"); assert_eq!(ChannelFilter::Green.name(), "Green"); assert_eq!(ChannelFilter::Blue.name(), "Blue"); @@ -1528,16 +1528,16 @@ mod tests { #[test] fn test_channel_filter_shortcut() { - assert_eq!(ChannelFilter::RGBA.shortcut(), "0"); - assert_eq!(ChannelFilter::Red.shortcut(), "1"); - assert_eq!(ChannelFilter::Green.shortcut(), "2"); - assert_eq!(ChannelFilter::Blue.shortcut(), "3"); - assert_eq!(ChannelFilter::Alpha.shortcut(), "4"); + assert_eq!(ChannelFilter::All.shortcut(), "0"); + assert_eq!(ChannelFilter::Red.shortcut(), "R"); + assert_eq!(ChannelFilter::Green.shortcut(), "G"); + assert_eq!(ChannelFilter::Blue.shortcut(), "B"); + assert_eq!(ChannelFilter::Alpha.shortcut(), "A"); } #[test] fn test_channel_filter_is_single_channel() { - assert!(!ChannelFilter::RGBA.is_single_channel()); + assert!(!ChannelFilter::All.is_single_channel()); assert!(ChannelFilter::Red.is_single_channel()); assert!(ChannelFilter::Green.is_single_channel()); assert!(ChannelFilter::Blue.is_single_channel()); @@ -1546,8 +1546,8 @@ mod tests { #[test] fn test_channel_filter_display() { - assert_eq!(format!("{}", ChannelFilter::RGBA), "RGBA"); - assert_eq!(format!("{}", ChannelFilter::Red), "Red"); + assert_eq!(format!("{}", ChannelFilter::All), "🔳 RGB"); + assert_eq!(format!("{}", ChannelFilter::Red), "[R] Red"); } // ==================================================================== @@ -1562,7 +1562,7 @@ mod tests { #[test] fn test_color_space_name() { - assert_eq!(ColorSpace::SRGB.name(), "sRGB"); + assert_eq!(ColorSpace::Srgb.name(), "sRGB"); assert_eq!(ColorSpace::Linear.name(), "Linear"); } @@ -1575,20 +1575,20 @@ mod tests { #[test] fn test_color_space_description() { - assert!(ColorSpace::SRGB.description().contains("gamma")); - assert!(ColorSpace::Linear.description().contains("physically")); + assert!(ColorSpace::Srgb.description().contains("Gamma")); + assert!(ColorSpace::Linear.description().contains("linear")); } #[test] fn test_color_space_is_linear() { - assert!(!ColorSpace::SRGB.is_linear()); + assert!(!ColorSpace::Srgb.is_linear()); assert!(ColorSpace::Linear.is_linear()); } #[test] fn test_color_space_display() { - assert_eq!(format!("{}", ColorSpace::SRGB), "sRGB"); - assert_eq!(format!("{}", ColorSpace::Linear), "Linear"); + assert_eq!(format!("{}", ColorSpace::Srgb), "[Mon] sRGB"); + assert_eq!(format!("{}", ColorSpace::Linear), "[Chart] Linear"); } // ==================================================================== @@ -1599,8 +1599,8 @@ mod tests { fn test_material_inspector_creation() { let inspector = MaterialInspector::new(); assert_eq!(inspector.zoom_level, 1.0); - assert!(matches!(inspector.display_mode, DisplayMode::Combined)); - assert!(matches!(inspector.channel_filter, ChannelFilter::RGBA)); + assert!(matches!(inspector.display_mode, DisplayMode::Albedo)); + assert!(matches!(inspector.channel_filter, ChannelFilter::All)); } #[test] diff --git a/tools/aw_editor/src/session_files.rs b/tools/aw_editor/src/session_files.rs new file mode 100644 index 0000000000..8b77f40bd2 --- /dev/null +++ b/tools/aw_editor/src/session_files.rs @@ -0,0 +1,287 @@ +//! Autosave files and the session lock file. +//! +//! The editor UI calls these and turns the result into toasts and console +//! lines. The file work is here so a test can run it without an editor frame. + +use std::path::{Path, PathBuf}; + +use astraweave_core::World; + +use crate::entity_manager::EntityManager; +use crate::local_clock; +use crate::scene_serialization; + +#[derive(Debug)] +pub enum AutosaveError { + Directory(String), + Save(String), +} + +pub struct AutosaveRequest<'a> { + pub world: Option<&'a World>, + pub entities: &'a EntityManager, + pub content_root: &'a Path, + pub scene_path: Option<&'a Path>, + pub separate_dir: bool, + pub keep_count: usize, +} + +#[derive(Debug)] +pub struct SavedAutosave { + pub filename: String, + pub notes: Vec, +} + +pub fn write_lock_file(path: &Path, scene: &str) { + use std::io::Write; + + if let Ok(mut file) = std::fs::File::create(path) { + let session_info = format!( + "pid={}\nstarted={}\nscene={}\n", + std::process::id(), + local_clock::readable(local_clock::now()), + scene + ); + let _ = file.write_all(session_info.as_bytes()); + } +} + +pub fn write_autosave( + request: AutosaveRequest<'_>, +) -> Result, AutosaveError> { + let Some(world) = request.world else { + return Ok(None); + }; + + let auto_save_path = if request.separate_dir { + let autosave_dir = request.content_root.join(".autosave"); + if let Err(error) = std::fs::create_dir_all(&autosave_dir) { + return Err(AutosaveError::Directory(format!( + "Failed to create autosave dir: {error}" + ))); + } + let timestamp = local_clock::compact(local_clock::now()); + let base_name = scene_stem(request.scene_path); + let filename = format!("{base_name}_{timestamp}.autosave.scene.ron"); + autosave_dir.join(filename) + } else { + request + .scene_path + .map(Path::to_path_buf) + .unwrap_or_else(|| request.content_root.join("scenes/autosave.scene.ron")) + }; + + match scene_serialization::save_scene_with_overlay(world, request.entities, &auto_save_path) { + Ok(()) => { + let filename = auto_save_path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + let notes = if request.separate_dir { + cleanup_old_autosaves( + &request.content_root.join(".autosave"), + scene_stem(request.scene_path), + request.keep_count, + ) + } else { + Vec::new() + }; + Ok(Some(SavedAutosave { filename, notes })) + } + Err(error) => Err(AutosaveError::Save(format!("Auto-save failed: {error}"))), + } +} + +pub fn cleanup_old_autosaves( + autosave_dir: &Path, + base_name: &str, + keep_count: usize, +) -> Vec { + if !autosave_dir.exists() { + return Vec::new(); + } + + let mut autosaves: Vec = match std::fs::read_dir(autosave_dir) { + Ok(entries) => entries + .filter_map(|entry| { + entry + .map_err(|err| tracing::debug!("Autosave dir entry error: {err}")) + .ok() + }) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .map(|name| { + name.starts_with(base_name) && name.ends_with(".autosave.scene.ron") + }) + .unwrap_or(false) + }) + .collect(), + Err(_) => return Vec::new(), + }; + + autosaves.sort_by(|left, right| { + let left_time = std::fs::metadata(left) + .and_then(|meta| meta.modified()) + .ok(); + let right_time = std::fs::metadata(right) + .and_then(|meta| meta.modified()) + .ok(); + right_time.cmp(&left_time) + }); + + let mut notes = Vec::new(); + for old_file in autosaves.iter().skip(keep_count) { + if let Err(error) = std::fs::remove_file(old_file) { + notes.push(format!( + "Failed to remove old autosave {:?}: {error}", + old_file.file_name().unwrap_or_default() + )); + } else { + notes.push(format!( + "Removed old autosave: {:?}", + old_file.file_name().unwrap_or_default() + )); + } + } + notes +} + +fn scene_stem(scene_path: Option<&Path>) -> &str { + scene_path + .and_then(|path| path.file_stem()) + .and_then(|stem| stem.to_str()) + .unwrap_or("untitled") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lock_file_records_the_pid_and_scene() { + let path = std::env::temp_dir().join(format!( + "aw-editor-lock-{}-{}.txt", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + write_lock_file(&path, "harbor.scene.ron"); + let text = std::fs::read_to_string(&path).unwrap(); + let _ = std::fs::remove_file(&path); + assert!(text.contains(&format!("pid={}\n", std::process::id()))); + assert!(text.contains("scene=harbor.scene.ron\n")); + assert!(text.contains("started=")); + } + + #[test] + fn autosave_without_a_world_writes_nothing() { + let entities = EntityManager::new(); + let saved = write_autosave(AutosaveRequest { + world: None, + entities: &entities, + content_root: Path::new("missing"), + scene_path: None, + separate_dir: true, + keep_count: 1, + }) + .unwrap(); + assert!(saved.is_none()); + } + + #[test] + fn autosave_directory_failure_is_reported() { + let world = World::new(); + let entities = EntityManager::new(); + let blocker = + std::env::temp_dir().join(format!("aw-editor-not-a-dir-{}", std::process::id())); + std::fs::write(&blocker, b"file").unwrap(); + let error = write_autosave(AutosaveRequest { + world: Some(&world), + entities: &entities, + content_root: &blocker, + scene_path: Some(Path::new("demo.scene.ron")), + separate_dir: true, + keep_count: 1, + }) + .unwrap_err(); + let _ = std::fs::remove_file(&blocker); + match error { + AutosaveError::Directory(message) => { + assert!(message.contains("Failed to create autosave dir:")); + } + AutosaveError::Save(_) => panic!("directory failure must stay a directory error"), + } + } + + #[test] + fn autosave_writes_a_timestamped_scene_under_the_content_root() { + let folder = std::path::PathBuf::from(format!(".autosave-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + let landed = std::path::PathBuf::from("content").join(&folder); + let _ = std::fs::remove_dir_all(&landed); + let world = World::new(); + let entities = EntityManager::new(); + let scene = folder.join("demo.scene.ron"); + let saved = write_autosave(AutosaveRequest { + world: Some(&world), + entities: &entities, + content_root: &folder, + scene_path: Some(&scene), + separate_dir: true, + keep_count: 4, + }); + let outcome = match saved { + Ok(value) => value, + Err(error) => { + let _ = std::fs::remove_dir_all(&folder); + let _ = std::fs::remove_dir_all(&landed); + panic!("autosave failed: {error:?}"); + } + }; + let saved = outcome.expect("a world produces a file"); + let written = landed.join(".autosave").join(&saved.filename); + assert!(written.is_file(), "{}", written.display()); + assert!(saved.filename.contains("demo")); + assert!(saved.filename.ends_with(".autosave.scene.ron")); + let _ = std::fs::remove_dir_all(&folder); + let _ = std::fs::remove_dir_all(&landed); + } + + #[test] + fn cleanup_keeps_only_the_requested_count() { + let dir = std::env::temp_dir().join(format!("aw-editor-autosave-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for name in [ + "demo_a.autosave.scene.ron", + "demo_b.autosave.scene.ron", + "demo_c.autosave.scene.ron", + ] { + std::fs::write(dir.join(name), b"scene").unwrap(); + } + std::fs::write(dir.join("other.autosave.scene.ron"), b"keep").unwrap(); + let notes = cleanup_old_autosaves(&dir, "demo", 1); + let remaining: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + let _ = std::fs::remove_dir_all(&dir); + let demo_left = remaining + .iter() + .filter(|name| name.starts_with("demo")) + .count(); + assert_eq!(demo_left, 1); + assert!(remaining + .iter() + .any(|name| name == "other.autosave.scene.ron")); + assert_eq!(notes.len(), 2); + assert!(notes + .iter() + .all(|note| note.contains("Removed old autosave"))); + } +} diff --git a/tools/aw_editor/src/voxel_tools.rs b/tools/aw_editor/src/voxel_tools.rs index d845ca5ce8..a457f38625 100644 --- a/tools/aw_editor/src/voxel_tools.rs +++ b/tools/aw_editor/src/voxel_tools.rs @@ -666,7 +666,9 @@ mod tests { #[test] fn test_brush_shape_display() { - assert_eq!(format!("{}", BrushShape::Sphere), "Sphere"); + assert_eq!(format!("{}", BrushShape::Sphere), "(O) Sphere"); + assert_eq!(format!("{}", BrushShape::Cube), "[#] Cube"); + assert_eq!(format!("{}", BrushShape::Cylinder), "(|) Cylinder"); } // ==================================================================== @@ -709,7 +711,9 @@ mod tests { #[test] fn test_brush_mode_display() { - assert_eq!(format!("{}", BrushMode::Add), "Add"); + assert_eq!(format!("{}", BrushMode::Add), "+ Add"); + assert_eq!(format!("{}", BrushMode::Remove), "- Remove"); + assert_eq!(format!("{}", BrushMode::Paint), "[P] Paint"); } // ==================================================================== diff --git a/tools/parse_probe/Cargo.lock b/tools/parse_probe/Cargo.lock index 0691e2eda2..c868a00bb0 100644 --- a/tools/parse_probe/Cargo.lock +++ b/tools/parse_probe/Cargo.lock @@ -26,32 +26,34 @@ dependencies = [ "memchr", ] -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - [[package]] name = "anyhow" version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" +[[package]] +name = "astraweave-behavior" +version = "0.4.0" +dependencies = [ + "anyhow", + "astraweave-ecs", + "serde", + "serde_json", +] + [[package]] name = "astraweave-core" version = "0.1.0" dependencies = [ "anyhow", + "astraweave-behavior", "astraweave-ecs", "glam", - "rand 0.9.2", + "rand", "serde", "serde_json", - "thiserror", + "thiserror 2.0.16", ] [[package]] @@ -59,9 +61,11 @@ name = "astraweave-ecs" version = "0.1.0" dependencies = [ "anyhow", + "astraweave-profiling", + "rand", "serde", "serde_json", - "thiserror", + "thiserror 2.0.16", ] [[package]] @@ -72,14 +76,16 @@ dependencies = [ "astraweave-core", "astraweave-observability", "async-trait", - "chrono", "dashmap", "futures-util", - "rand 0.8.5", + "lazy_static", + "rand", "serde", "serde_json", + "time", "tokio", "tracing", + "url", "uuid", ] @@ -90,20 +96,27 @@ dependencies = [ "anyhow", "astraweave-ecs", "async-trait", - "chrono", "dashmap", "hdrhistogram", "histogram", - "rand 0.8.5", + "rand", "serde", "serde_json", - "thiserror", + "thiserror 2.0.16", + "time", "tokio", "tracing", "tracing-subscriber", "uuid", ] +[[package]] +name = "astraweave-profiling" +version = "0.4.0" +dependencies = [ + "anyhow", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -112,7 +125,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -166,42 +179,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" -[[package]] -name = "cc" -version = "1.2.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d05d92f4b1fd76aad469d46cdd858ca761576082cd37df81416691e50199fb" -dependencies = [ - "find-msvc-tools", - "shlex", -] - [[package]] name = "cfg-if" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" -[[package]] -name = "chrono" -version = "0.4.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - [[package]] name = "crc32fast" version = "1.5.0" @@ -241,10 +224,21 @@ dependencies = [ ] [[package]] -name = "find-msvc-tools" -version = "0.1.3" +name = "deranged" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0399f9d26e5191ce32c498bebd31e7a3ceabc2745f0ac54af3f335126c3f24b3" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] [[package]] name = "flate2" @@ -256,6 +250,15 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures-core" version = "0.3.31" @@ -270,7 +273,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -293,17 +296,6 @@ dependencies = [ "slab", ] -[[package]] -name = "getrandom" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.11.1+wasi-snapshot-preview1", -] - [[package]] name = "getrandom" version = "0.3.3" @@ -353,32 +345,118 @@ dependencies = [ [[package]] name = "histogram" -version = "0.6.9" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cb882ccb290b8646e554b157ab0b71e64e8d5bef775cd66b6531e52d302669" +checksum = "95aebe0dec9a429e3207e5e34d97f2a7d1064d5ee6d8ed13ce0a26456de000ae" +dependencies = [ + "thiserror 1.0.69", +] [[package]] -name = "iana-time-zone" -version = "0.1.64" +name = "icu_collections" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" +checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", ] [[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" +name = "icu_locale_core" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" dependencies = [ - "cc", + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" + +[[package]] +name = "icu_properties" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "potential_utf", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" + +[[package]] +name = "icu_provider" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" +dependencies = [ + "displaydoc", + "icu_locale_core", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", ] [[package]] @@ -420,6 +498,12 @@ version = "0.2.176" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174" +[[package]] +name = "litemap" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" + [[package]] name = "lock_api" version = "0.4.13" @@ -497,6 +581,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-traits" version = "0.2.19" @@ -521,16 +611,6 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" -[[package]] -name = "parking_lot" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" -dependencies = [ - "lock_api", - "parking_lot_core", -] - [[package]] name = "parking_lot_core" version = "0.9.11" @@ -553,6 +633,12 @@ dependencies = [ "astraweave-llm", ] +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -565,6 +651,21 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "potential_utf" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84df19adbe5b5a0782edcab45899906947ab039ccf4573713735ee7de1e6b08a" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -585,9 +686,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.40" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" dependencies = [ "proc-macro2", ] @@ -598,35 +699,14 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - [[package]] name = "rand" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", + "rand_chacha", + "rand_core", ] [[package]] @@ -636,16 +716,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.16", + "rand_core", ] [[package]] @@ -654,7 +725,7 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.3", + "getrandom", ] [[package]] @@ -734,7 +805,7 @@ checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -759,21 +830,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signal-hook-registry" -version = "1.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" -dependencies = [ - "libc", -] - [[package]] name = "simd-adler32" version = "0.3.7" @@ -793,14 +849,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] -name = "socket2" -version = "0.6.0" +name = "stable_deref_trait" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "syn" @@ -813,13 +865,66 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3467d614147380f2e4e374161426ff399c91084acd2363eaf549172b3d5e60c0" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.16", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", ] [[package]] @@ -830,7 +935,7 @@ checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -842,6 +947,46 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tokio" version = "1.47.1" @@ -853,13 +998,9 @@ dependencies = [ "io-uring", "libc", "mio", - "parking_lot", "pin-project-lite", - "signal-hook-registry", "slab", - "socket2", "tokio-macros", - "windows-sys 0.59.0", ] [[package]] @@ -870,7 +1011,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -892,7 +1033,7 @@ checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -953,13 +1094,31 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "uuid" version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" dependencies = [ - "getrandom 0.3.3", + "getrandom", "js-sys", "wasm-bindgen", ] @@ -1017,7 +1176,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn", + "syn 2.0.106", "wasm-bindgen-shared", ] @@ -1039,7 +1198,7 @@ checksum = "9f07d2f20d4da7b26400c9f4a0511e6e0345b040694e8a75bd41d578fa4421d7" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -1053,65 +1212,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-sys" version = "0.52.0" @@ -1200,6 +1300,35 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +[[package]] +name = "writeable" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure 0.14.0", +] + [[package]] name = "zerocopy" version = "0.8.27" @@ -1217,5 +1346,59 @@ checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", + "synstructure 0.13.2", +] + +[[package]] +name = "zerotrie" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7aa2bd55086f1ab526693ecbe444205da57e25f4489879da80635a46d90e73b" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", ]