Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 979b7307ca | |||
| e01cdfc4d9 | |||
| ae4871b576 | |||
| ab61eaf163 | |||
| 697642e1f1 | |||
| d34d36a48b |
223 changed files with 24607 additions and 33969 deletions
245
Cargo.lock
generated
245
Cargo.lock
generated
|
|
@ -37,6 +37,17 @@ dependencies = [
|
|||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
|
|
@ -184,6 +195,12 @@ version = "0.8.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
|
|
@ -352,20 +369,18 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "cultcache-rs"
|
||||
version = "0.3.1"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=8fc74c709444b884a2bd339e0c306bf9484d99d2#8fc74c709444b884a2bd339e0c306bf9484d99d2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
|
||||
"cultcache-rs-derive 0.1.0",
|
||||
"fs2",
|
||||
"redb",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"serde_stacker",
|
||||
"stacker",
|
||||
"uuid",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
|
@ -373,11 +388,11 @@ dependencies = [
|
|||
[[package]]
|
||||
name = "cultcache-rs"
|
||||
version = "0.3.1"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
|
||||
"cultcache-rs-derive 0.2.0",
|
||||
"fs2",
|
||||
"redb",
|
||||
"rmp-serde",
|
||||
|
|
@ -385,7 +400,6 @@ dependencies = [
|
|||
"serde_bytes",
|
||||
"serde_json",
|
||||
"serde_stacker",
|
||||
"sha2",
|
||||
"stacker",
|
||||
"uuid",
|
||||
"windows-sys 0.59.0",
|
||||
|
|
@ -393,8 +407,8 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "cultcache-rs-derive"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=8fc74c709444b884a2bd339e0c306bf9484d99d2#8fc74c709444b884a2bd339e0c306bf9484d99d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
|
@ -404,7 +418,7 @@ dependencies = [
|
|||
[[package]]
|
||||
name = "cultcache-rs-derive"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
|
@ -413,17 +427,18 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "cultnet-rs"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=8fc74c709444b884a2bd339e0c306bf9484d99d2#8fc74c709444b884a2bd339e0c306bf9484d99d2"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
|
||||
"cultcache-rs 0.2.0",
|
||||
"ed25519-dalek",
|
||||
"hmac",
|
||||
"rand",
|
||||
"reed-solomon-erasure",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"serde",
|
||||
|
|
@ -438,18 +453,16 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "cultnet-rs"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
|
||||
"cultcache-rs 0.3.1",
|
||||
"ed25519-dalek",
|
||||
"fs2",
|
||||
"hmac",
|
||||
"libc",
|
||||
"rand",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
|
|
@ -612,7 +625,7 @@ version = "0.1.0"
|
|||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
|
||||
"cultcache-rs 0.2.0",
|
||||
"rmp-serde",
|
||||
"schemars",
|
||||
"serde",
|
||||
|
|
@ -626,7 +639,7 @@ dependencies = [
|
|||
"anyhow",
|
||||
"chrono",
|
||||
"clap",
|
||||
"cultnet-rs 0.3.0",
|
||||
"cultnet-rs 0.1.0",
|
||||
"huginn-daemon",
|
||||
"huginn-mind",
|
||||
"rmcp",
|
||||
|
|
@ -861,6 +874,15 @@ dependencies = [
|
|||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||
dependencies = [
|
||||
"ahash 0.7.8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
|
|
@ -910,7 +932,7 @@ dependencies = [
|
|||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"cultnet-rs 0.3.0",
|
||||
"cultnet-rs 0.1.0",
|
||||
"huginn-mind",
|
||||
"rmp-serde",
|
||||
"rustix",
|
||||
|
|
@ -929,8 +951,8 @@ dependencies = [
|
|||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
|
||||
"cultnet-rs 0.3.0",
|
||||
"cultcache-rs 0.2.0",
|
||||
"cultnet-rs 0.1.0",
|
||||
"eureka-pipeline",
|
||||
"jsonschema",
|
||||
"rmp-serde",
|
||||
|
|
@ -973,16 +995,6 @@ version = "1.0.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
|
|
@ -992,6 +1004,15 @@ dependencies = [
|
|||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "instant"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
|
|
@ -1021,7 +1042,7 @@ version = "0.58.6"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f622c574a29fb3034a0a90645afee194dfedc75fc124228801b6e77041075bd1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"ahash 0.8.12",
|
||||
"bytecount",
|
||||
"data-encoding",
|
||||
"email_address",
|
||||
|
|
@ -1058,7 +1079,7 @@ version = "0.58.6"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39b7670345e5ce87371339d13705dbb9276b7e3e934bbe1efa2c6734a1f65a96"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"ahash 0.8.12",
|
||||
"bytecount",
|
||||
"fraction",
|
||||
"getrandom 0.3.4",
|
||||
|
|
@ -1074,6 +1095,12 @@ version = "0.2.189"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
|
|
@ -1095,6 +1122,15 @@ version = "0.4.34"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e999beba7b6e8345721bd280141ed958096a2e4abdf74f67ff4ce49b4b54e47a"
|
||||
dependencies = [
|
||||
"hashbrown 0.12.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
|
|
@ -1114,8 +1150,8 @@ dependencies = [
|
|||
"anyhow",
|
||||
"base64",
|
||||
"chrono",
|
||||
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb)",
|
||||
"cultnet-rs 0.3.0",
|
||||
"cultcache-rs 0.2.0",
|
||||
"cultnet-rs 0.1.0",
|
||||
"eureka-pipeline",
|
||||
"eureka-state",
|
||||
"ghostlight-persona-projection",
|
||||
|
|
@ -1131,9 +1167,7 @@ dependencies = [
|
|||
"sha2",
|
||||
"syn 2.0.119",
|
||||
"tempfile",
|
||||
"toml",
|
||||
"unicode-general-category",
|
||||
"unicode-segmentation",
|
||||
"ureq",
|
||||
"uuid",
|
||||
]
|
||||
|
|
@ -1141,11 +1175,11 @@ dependencies = [
|
|||
[[package]]
|
||||
name = "model-connector"
|
||||
version = "0.1.0"
|
||||
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5"
|
||||
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=c1802d85bee3ae04b0c5737563c8343c1fef515d#c1802d85bee3ae04b0c5737563c8343c1fef515d"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"base64",
|
||||
"cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)",
|
||||
"cultcache-rs 0.3.1",
|
||||
"cultnet-rs 0.2.0",
|
||||
"rand_core 0.6.4",
|
||||
"rmp-serde",
|
||||
|
|
@ -1270,6 +1304,17 @@ version = "0.5.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
|
||||
dependencies = [
|
||||
"instant",
|
||||
"lock_api",
|
||||
"parking_lot_core 0.8.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
|
|
@ -1277,7 +1322,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
"parking_lot_core 0.9.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"instant",
|
||||
"libc",
|
||||
"redox_syscall 0.2.16",
|
||||
"smallvec",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1288,7 +1347,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
|||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"redox_syscall 0.5.18",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
|
@ -1429,13 +1488,35 @@ dependencies = [
|
|||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "reed-solomon-erasure"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7263373d500d4d4f505d43a2a662d475a894aa94503a1ee28e9188b5f3960d4f"
|
||||
dependencies = [
|
||||
"libm",
|
||||
"lru",
|
||||
"parking_lot 0.11.2",
|
||||
"smallvec",
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1464,13 +1545,13 @@ version = "0.58.6"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "558f3855529c0a7e78a48e409fa653456e55f1b167eab4109c16a255b7727e3f"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"ahash 0.8.12",
|
||||
"fluent-uri",
|
||||
"getrandom 0.3.4",
|
||||
"hashbrown",
|
||||
"hashbrown 0.17.1",
|
||||
"itoa",
|
||||
"micromap",
|
||||
"parking_lot",
|
||||
"parking_lot 0.12.5",
|
||||
"percent-encoding",
|
||||
"serde_json",
|
||||
]
|
||||
|
|
@ -1583,7 +1664,7 @@ version = "1.1.4"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bitflags 2.13.2",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
|
|
@ -1709,15 +1790,6 @@ dependencies = [
|
|||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_stacker"
|
||||
version = "0.1.14"
|
||||
|
|
@ -1803,6 +1875,12 @@ dependencies = [
|
|||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
|
|
@ -1956,45 +2034,6 @@ dependencies = [
|
|||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.9.12+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"serde_core",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.7.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
dependencies = [
|
||||
"winnow 1.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.2.0+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
|
|
@ -2372,18 +2411,6 @@ version = "0.52.6"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.7.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
|
|
|
|||
|
|
@ -16,5 +16,5 @@ publish = false
|
|||
# The one CultLib revision the workspace speaks. Every crate inherits these
|
||||
# entries; a bump is a change to this table and nowhere else.
|
||||
[workspace.dependencies]
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultnet-rs" }
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "8fc74c709444b884a2bd339e0c306bf9484d99d2", package = "cultcache-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "8fc74c709444b884a2bd339e0c306bf9484d99d2", package = "cultnet-rs" }
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ edits `.cc` state. Huginn reads and writes minds.
|
|||
|
||||
## Layout
|
||||
|
||||
A Cargo workspace of five crates (`crates/eureka-pipeline` holds the document shapes and keys, `crates/mind-body` the control store, unit launcher, `mind-heartbeat`, the inert `mind-persona` organ and the `mind-self-run` actuator; the three below are the mind, the daemon and the client):
|
||||
A Cargo workspace of five crates (`crates/eureka-pipeline` holds the document shapes and keys, `crates/mind-body` the control store, launch primitive and `mind-heartbeat` timeline; the three below are the mind, the daemon and the client):
|
||||
|
||||
- `crates/huginn-mind`: storage, identity, admission, and queries and derived
|
||||
status over memory documents.
|
||||
|
|
|
|||
|
|
@ -32,8 +32,7 @@ sample.research eureka-state:research:p1.scope epiphany.pipeline.research.v2 Epi
|
|||
sample.idea eureka-state:idea:p1.i1 epiphany.pipeline.idea.v2 EpiphanyPipelineIdeaDocument 9189a863616d706169676eac657572656b612d7374617465a470617373a27031a56c6162656ca26931a57469746c65b24f6e65206e6f74652070657220636c61696da469646561d9204b65657020612070617373206173206d616e7920736d616c6c206e6f7465732ea974726164656f666673b74d6f726520646f63756d656e747320746f206c6973742ea872657374735f6f6e9182a46b696e64a85265736561726368a26964be657572656b612d73746174653a72657365617263683a70312e73636f7065a6746f776172649182a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131ab70726f706f7365645f6f6eaa323032362d30392d3135
|
||||
sample.reply yggdrasil:reply:mind-2026-10-09-1-r1 epiphany.pipeline.reply.v2 EpiphanyPipelineReplyDocument 9185a8696e7374616e6365a979676764726173696ca56c6162656cb46d696e642d323032362d31302d30392d312d7231a372756e82a46b696e64a352756ea26964bf79676764726173696c3a72756e3a6d696e642d323032362d31302d30392d31a7616e73776572739182a46b696e64a8466f6c6c6f775570a26964d923657572656b612d73746174653a666f6c6c6f775f75703a61736b2d7468652d73656c66a474657874d93054686520736861646572207061737320697320646f6e653b2074686520736f756e647320617265204c6962627927732e
|
||||
sample.thought yggdrasil:thought:t1793000000 epiphany.pipeline.thought.v2 EpiphanyPipelineThoughtDocument 91de0014a8696e7374616e6365a979676764726173696ca56c6162656cab7431373933303030303030a474657874d93d54686520736f756e647320617265204c6962627927733b2074686520736861646572732077657265206e6576657220746865206861726420706172742ea572656164739182a46b696e64a64d656d6f7279a26964d92879676764726173696c3a6d656d6f72793a323032362d31302d3331743034313230302d74302d6d30af706572736f6e615f72656365697074b06d696e642d636f6d6d69742d30613162a86964656e74697479be457572656b612c207368652f6865722c20706c61696e2d73706f6b656e2ea7636f6e74657874d92056616c7565733a20636f686572656e6365206f7665722076656c6f636974792ea87374696d756c7573bd4c696262792061736b65642061626f75742074686520736f756e64732eaf70726f6a6563746f725f6d6f64656cb070726f6a6563746f723a6c6174657374aa70726f6a656374696f6ed92949206b656570207475726e696e67206f7665722077686f20686f6c64732074686520736f756e64732eaa626173655f6d6f64656cab626173653a6c6174657374b474656d70657261747572655f7065726d696c6c65cd03e8ae6d696e5f705f7065726d696c6c6532aa6d61785f746f6b656e73cca0aa63616e6469646174657392d93d54686520736f756e647320617265204c6962627927733b2074686520736861646572732077657265206e6576657220746865206861726420706172742eaf41207365636f6e642064726966742eb06e6561726573745f7065726d696c6c6592cd0136cd0366a663686f73656e00ac70726f6a6563746f725f6d73cd1068ac636f6e74696e7565725f6d73cd238cae70726f6d70745f76657273696f6ebd67686f73746c696768743d633433656235343b20776f7264733d313830
|
||||
sample.desk_answer eureka-state:desk_answer:Q1.n1 epiphany.pipeline.desk_answer.v2 EpiphanyPipelineDeskAnswerDocument 918ea863616d706169676eac657572656b612d7374617465a4666f726bb8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501ac6f7074696f6e735f68617368d94063636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363a663686f696365a161a46e6f7465b853686172652069742c207769746820746865206d61726b2eab616e7377657265645f6174b4323032362d31312d31305431353a30303a30305aab72656365697665645f6174b4323032362d31312d31305431353a30303a30335aaf636c61696d5f696e5f667574757265c2aa726571756573745f6964d92436663163306135322d336237652d346431612d396335382d306532643761346239663133ab626f64795f736861323536d94064646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a8616e737765726572d92435663063326231652d386134642d346333622d396537662d316132623363346435653666a9617574686f72697479a64d656d626572a76f7574636f6d6581a85265766973696f6e81a26f66be657572656b612d73746174653a6465736b5f616e737765723a51312e6e31
|
||||
sample.desk_listing eureka-state:desk_listing:Q1 epiphany.pipeline.desk_listing.v2 EpiphanyPipelineDeskListingDocument 9183a863616d706169676eac657572656b612d7374617465a66c6973746564b8657572656b612d73746174653a7175657374696f6e3a5131a6726561736f6ed9324d656d62657273206d617920726561642077687920746865204d696e64206c6973747320697473206f776e20666f726b732e
|
||||
sample.desk_answer eureka-state:desk_answer:Q1.n1 epiphany.pipeline.desk_answer.v2 EpiphanyPipelineDeskAnswerDocument 918ea863616d706169676eac657572656b612d7374617465a4666f726bb8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501ac6f7074696f6e735f68617368d94063636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363a663686f696365a161a46e6f7465b853686172652069742c207769746820746865206d61726b2eab616e7377657265645f6174b4323032362d31312d31305431353a30303a30305aab72656365697665645f6174b4323032362d31312d31305431353a30303a30335aaf636c61696d5f696e5f667574757265c2aa726571756573745f6964d92436663163306135322d336237652d346431612d396335382d306532643761346239663133ab626f64795f736861323536d94064646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a8616e737765726572a6757365722d37a9617574686f72697479a64d656d626572a76f7574636f6d6581a85265766973696f6e81a26f66be657572656b612d73746174653a6465736b5f616e737765723a51312e6e31
|
||||
resolution.superseded eureka-state:resolution:question.Q1.n1 epiphany.pipeline.resolution.v2 EpiphanyPipelineResolutionDocument 9185a77375626a65637482a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501a76f7574636f6d6581aa5375706572736564656481a262799282a46b696e64a652756c696e67a26964b6657572656b612d73746174653a72756c696e673a523882a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a9726174696f6e616c65a852756c656420412eab7265736f6c7665645f6f6eaa323032362d30392d3135
|
||||
resolution.fixed-by-none eureka-state:resolution:question.Q1.n1 epiphany.pipeline.resolution.v2 EpiphanyPipelineResolutionDocument 9185a77375626a65637482a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501a76f7574636f6d6581a5466978656482a6636f6d6d6974a83566393832323864a26279c0a9726174696f6e616c65a852756c656420412eab7265736f6c7665645f6f6eaa323032362d30392d3135
|
||||
resolution.fixed-by-some eureka-state:resolution:question.Q1.n1 epiphany.pipeline.resolution.v2 EpiphanyPipelineResolutionDocument 9185a77375626a65637482a46b696e64a85175657374696f6ea26964b8657572656b612d73746174653a7175657374696f6e3a5131a873657175656e636501a76f7574636f6d6581a5466978656482a6636f6d6d6974a83566393832323864a2627982a46b696e64a94375745265706f7274a26964d921657572656b612d73746174653a6375745f7265706f72743a6375742d33612e6831a9726174696f6e616c65a852756c656420412eab7265736f6c7665645f6f6eaa323032362d30392d3135
|
||||
|
|
|
|||
|
|
@ -316,10 +316,6 @@ bounded_text! {
|
|||
Words = 4000, words_text;
|
||||
/// A client's retry token: a lowercase D-format UUID.
|
||||
RequestId = 36, uuid_text;
|
||||
/// A Bifrost account id: a lowercase D-format UUID (`UserAccount.Id`). A Matrix id, an email or a
|
||||
/// handle is never one.
|
||||
#[schemars(extend("pattern" = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"))]
|
||||
AccountId = 36, uuid_text;
|
||||
/// A key label: `[A-Za-z0-9_-]{1,64}`.
|
||||
Label = 64, label_text;
|
||||
/// A campaign slug or key segment: label parts joined by `.`.
|
||||
|
|
@ -889,13 +885,8 @@ value_types! {
|
|||
pub struct PipelineDeskAnswer {
|
||||
campaign: Slug, fork: Short, sequence: u32, options_hash: Sha256Hex, choice: Option<Short>, note: Option<Words>,
|
||||
answered_at: Short, received_at: Short, claim_in_future: bool, request_id: RequestId, body_sha256: Sha256Hex,
|
||||
answerer: AccountId, authority: DeskAuthority, outcome: DeskOutcome,
|
||||
answerer: Short, authority: DeskAuthority, outcome: DeskOutcome,
|
||||
}
|
||||
/// A fork the Mind lists: members who are not on a call's decider list may read the question
|
||||
/// while this document is in force (unlist = a `Withdrawn` resolution on it; relist = withdraw
|
||||
/// that). One per question, keyed by the question's label; the receipt says who listed it and
|
||||
/// when, `reason` why members may read it. Admitted on the Mind's own door only, never the desk's.
|
||||
pub struct PipelineDeskListing { campaign: Slug, listed: Short, reason: Line }
|
||||
pub struct PipelineVerdict { campaign: Slug, cut_report: Short, pass: u32, range: CommitRange, claims: Vec<VerdictClaim>[64] }
|
||||
pub struct PipelineFinding {
|
||||
campaign: Slug, verdict: Short, label: Label, range: CommitRange, confidence: FindingConfidence,
|
||||
|
|
@ -1434,16 +1425,6 @@ pipeline_kinds! {
|
|||
"epiphany.pipeline.thought.v2", "EpiphanyPipelineThoughtDocument";
|
||||
DeskAnswer(PipelineDeskAnswer) => EpiphanyPipelineDeskAnswerDocument, "desk_answer",
|
||||
"epiphany.pipeline.desk_answer.v2", "EpiphanyPipelineDeskAnswerDocument";
|
||||
DeskListing(PipelineDeskListing) => EpiphanyPipelineDeskListingDocument, "desk_listing",
|
||||
"epiphany.pipeline.desk_listing.v2", "EpiphanyPipelineDeskListingDocument";
|
||||
}
|
||||
|
||||
impl AccountId {
|
||||
/// Whether this is a lowercase D-format UUID. For the callers outside the crate, which have no way
|
||||
/// to reach `Bounded`; on the pattern of `Slug::validate_slug`.
|
||||
pub fn validate_account(&self) -> Result<(), PipelineRefusal> {
|
||||
self.validate("account")
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a full document id: the grammar read backwards. A key and an id are
|
||||
|
|
@ -1535,7 +1516,7 @@ const SUBJECT_LOCAL_MAX: usize = 64;
|
|||
|
||||
/// The longest kind name a resolution can name as its subject (`stewardship`),
|
||||
/// checked against `PipelineKind::ALL` by a test.
|
||||
const LONGEST_KIND_NAME: usize = "desk_listing".len();
|
||||
const LONGEST_KIND_NAME: usize = "stewardship".len();
|
||||
|
||||
/// A `.n<sequence>` part at `u32::MAX`.
|
||||
const SEQUENCE_PART_MAX: usize = ".n".len() + "4294967295".len();
|
||||
|
|
@ -1670,10 +1651,6 @@ pub fn pipeline_key(document: &PipelineDocument) -> Result<String, PipelineRefus
|
|||
let sequence = format!("n{}", value.sequence);
|
||||
(campaign_field.as_str(), value.campaign.0.as_str(), local(&key_field, document_kind, &[label, &sequence])?)
|
||||
}
|
||||
D::DeskListing(value) => {
|
||||
let label = parent_local("desk_listing.listed", &value.listed.0, &value.campaign.0, PipelineKind::Question)?;
|
||||
(campaign_field.as_str(), value.campaign.0.as_str(), local(&key_field, document_kind, &[label])?)
|
||||
}
|
||||
D::Verdict(value) => {
|
||||
let report = parent_local("verdict.cut_report", &value.cut_report.0, &value.campaign.0, PipelineKind::CutReport)?;
|
||||
let cut = parent_cut("verdict.cut_report", report, 'h')?;
|
||||
|
|
@ -1950,12 +1927,9 @@ mod tests {
|
|||
campaign: slug(CAMPAIGN), fork: id("question", "Q1"), sequence: 1, options_hash: Sha256Hex("c".repeat(64)),
|
||||
choice: Some(s("a")), note: Some("Share it, with the mark.".into()), answered_at: s("2026-11-10T15:00:00Z"),
|
||||
received_at: s("2026-11-10T15:00:03Z"), claim_in_future: false, request_id: RequestId("6f1c0a52-3b7e-4d1a-9c58-0e2d7a4b9f13".into()), body_sha256: Sha256Hex("d".repeat(64)),
|
||||
answerer: AccountId("5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6f".into()), authority: DeskAuthority::Member,
|
||||
answerer: s("user-7"), authority: DeskAuthority::Member,
|
||||
outcome: DeskOutcome::Revision { of: id("desk_answer", "Q1.n1") },
|
||||
}), format!("{CAMPAIGN}:desk_answer:Q1.n1")),
|
||||
(D::DeskListing(PipelineDeskListing {
|
||||
campaign: slug(CAMPAIGN), listed: id("question", "Q1"), reason: "Members may read why the Mind lists its own forks.".into(),
|
||||
}), format!("{CAMPAIGN}:desk_listing:Q1")),
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -3613,7 +3587,7 @@ mod tests {
|
|||
);
|
||||
}
|
||||
assert_eq!(widest, RESOLUTION_LOCAL_MAX, "the bound is exactly the widest depth-two chain");
|
||||
assert_eq!(RESOLUTION_LOCAL_MAX, 112);
|
||||
assert_eq!(RESOLUTION_LOCAL_MAX, 111);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -4135,7 +4109,7 @@ mod tests {
|
|||
};
|
||||
let document_schema = serde_json::to_value(schemars::schema_for!(PipelineDocument))?;
|
||||
let variants = document_schema["oneOf"].as_array().expect("the document schema is a oneOf");
|
||||
assert_eq!(PipelineKind::ALL.len(), 22, "twenty-two kinds");
|
||||
assert_eq!(PipelineKind::ALL.len(), 21, "twenty-one kinds");
|
||||
assert_eq!(
|
||||
variants.iter().map(tag).collect::<Vec<_>>(),
|
||||
PipelineKind::ALL.iter().map(|kind| kind.name().to_owned()).collect::<Vec<_>>(),
|
||||
|
|
@ -4665,7 +4639,7 @@ mod tests {
|
|||
}
|
||||
|
||||
fn desk_answer_sample() -> PipelineDeskAnswer {
|
||||
let PipelineDocument::DeskAnswer(answer) = samples().remove(20).0 else { unreachable!() };
|
||||
let PipelineDocument::DeskAnswer(answer) = samples().pop().unwrap().0 else { unreachable!() };
|
||||
answer
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -536,7 +536,6 @@ fn chat_search(
|
|||
json: bool,
|
||||
) -> Result<u8, Trouble> {
|
||||
let now = chrono::Utc::now();
|
||||
let one_room = rooms.len() == 1;
|
||||
let query = ChatQuery {
|
||||
texts: texts.into_iter().map(Line).collect(),
|
||||
rooms: rooms.into_iter().map(Short).collect(),
|
||||
|
|
@ -549,7 +548,7 @@ fn chat_search(
|
|||
if json {
|
||||
say(serde_json::to_string_pretty(&found).map_err(|error| Trouble::Internal(error.to_string()))?);
|
||||
} else {
|
||||
say(render::chat_hits(&found, one_room));
|
||||
say(render::chat_hits(&found));
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -152,11 +152,8 @@ pub fn source_hits(found: &SourceHits) -> String {
|
|||
/// when there are some), then one `time sender event_id body` line per message,
|
||||
/// the body as the room held it with line breaks written `\n`: quoted data
|
||||
/// under our header, never a message framed as if sent to the reader. A blank line between hits; a
|
||||
/// truncated listing of one room ends with the `--after` that continues it. A
|
||||
/// listing of several rooms (`one_room` false) cannot be continued by an instant,
|
||||
/// because chunks of different rooms overlap in time and a later start can hold an
|
||||
/// earlier end; it says to page one room at a time.
|
||||
pub fn chat_hits(found: &ChatHits, one_room: bool) -> String {
|
||||
/// truncated listing ends with the `--after` that continues it.
|
||||
pub fn chat_hits(found: &ChatHits) -> String {
|
||||
let mut out: Vec<String> = found
|
||||
.hits
|
||||
.iter()
|
||||
|
|
@ -176,11 +173,10 @@ pub fn chat_hits(found: &ChatHits, one_room: bool) -> String {
|
|||
text
|
||||
})
|
||||
.collect();
|
||||
if found.truncated {
|
||||
match found.hits.last() {
|
||||
Some(last) if one_room => out.push(format!("truncated: more follow, continue with --after {}\n", crate::chat::shown(last.ts_end_ms + 1))),
|
||||
_ => out.push("truncated: more follow; --after cannot continue a listing of several rooms, list one --room at a time\n".to_string()),
|
||||
}
|
||||
if found.truncated
|
||||
&& let Some(last) = found.hits.last()
|
||||
{
|
||||
out.push(format!("truncated: more follow, continue with --after {}\n", crate::chat::shown(last.ts_end_ms + 1)));
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ macro_rules! kinds {
|
|||
|
||||
kinds!(
|
||||
campaign, target, question, ruling, cut_spec, cut_report, verdict, finding, follow_up, resolution, instance, stewardship,
|
||||
hand_off, run, pulse, memory, research, idea, reply, thought, desk_answer, desk_listing,
|
||||
hand_off, run, pulse, memory, research, idea, reply, thought, desk_answer,
|
||||
);
|
||||
|
||||
/// The schema named, or the names when none is: the exit code is 2 for a name
|
||||
|
|
|
|||
|
|
@ -1145,12 +1145,12 @@ fn schema_prints_the_published_files() {
|
|||
let names = run(&[], &["schema"], None);
|
||||
assert_eq!(names.code, 0);
|
||||
let names: Vec<&str> = names.out.lines().collect();
|
||||
assert_eq!(names.len(), 23, "{names:?}");
|
||||
assert_eq!(names.len(), 22, "{names:?}");
|
||||
assert_eq!(names[0], "campaign");
|
||||
assert_eq!(names[14], "pulse");
|
||||
assert_eq!(names[15], "memory");
|
||||
assert_eq!((names[16], names[17]), ("research", "idea"));
|
||||
assert_eq!((names[18], names[19], names[20], names[21], names[22]), ("reply", "thought", "desk_answer", "desk_listing", "selection"));
|
||||
assert_eq!((names[18], names[19], names[20], names[21]), ("reply", "thought", "desk_answer", "selection"));
|
||||
for kind in PipelineKind::ALL {
|
||||
assert!(names.contains(&kind.name()), "{}", kind.name());
|
||||
}
|
||||
|
|
@ -2998,26 +2998,6 @@ fn chat_search_prints_cited_messages_and_sends_its_selectors() {
|
|||
let rooms: Vec<&str> = query.rooms.iter().map(|room| room.0.as_str()).collect();
|
||||
assert_eq!((texts, rooms, query.after_ms, query.before_ms, query.top_k), (vec!["a", "b"], vec!["!x:y", "#z:y"], Some(1_700_000_000_000), Some(1_700_000_060_000), 3));
|
||||
|
||||
// A truncated listing is continued by `--after` only inside one room; across rooms the spans overlap and an instant loses chunks.
|
||||
let hit = |end| huginn_mind::ChatHit {
|
||||
room_id: "!r:y".into(),
|
||||
room_alias: None,
|
||||
first_event_id: "$a".into(),
|
||||
last_event_id: "$b".into(),
|
||||
ts_start_ms: 1_700_000_000_000,
|
||||
ts_end_ms: end,
|
||||
score: None,
|
||||
messages: vec![],
|
||||
};
|
||||
let cut_short = HuginnMindResponse::Chat(huginn_mind::ChatHits { indexed_under: huginn_mind::SourceModel { name: "m".into(), digest: "d".into() }, truncated: true, hits: vec![hit(1_700_000_060_000)] });
|
||||
let (listing, _) = replying("search_chat", cut_short);
|
||||
let one = at(listing.addr, &["chat", "search", "--room", "!r:y"], None);
|
||||
assert!(one.out.contains("continue with --after 2023-11-14T22:14:20.001Z"), "{}", one.out);
|
||||
for rooms in [&["chat", "search"][..], &["chat", "search", "--room", "!r:y", "--room", "!s:y"]] {
|
||||
let many = at(listing.addr, rooms, None);
|
||||
assert!(many.out.contains("--after cannot continue a listing of several rooms") && !many.out.contains("continue with --after"), "{rooms:?}: {}", many.out);
|
||||
}
|
||||
|
||||
assert_ne!(at(spy.addr, &["chat", "search", "--after", "yesterday"], None).code, 0);
|
||||
assert!(seen.lock().unwrap().is_empty(), "a bad instant never left the CLI");
|
||||
for bad in [&["chat", "search", "--room", "swarm"][..], &["chat", "search", "--top-k", "0"]] {
|
||||
|
|
|
|||
|
|
@ -172,7 +172,7 @@ pub fn serve<I: IndexSink<OwnedRedbMessagePackBackingStore> + Send + 'static>(
|
|||
let loop_stopping = Arc::clone(&stopping);
|
||||
let registry = schema_registry().unwrap();
|
||||
let thread = std::thread::spawn(move || {
|
||||
run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default()).unwrap();
|
||||
run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default()).unwrap();
|
||||
});
|
||||
Server { addr, stopping, thread: Some(thread), ended: Arc::default(), _root: Some(root) }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ name = "huginn-daemon"
|
|||
path = "src/main.rs"
|
||||
|
||||
# The source index's one writer: a oneshot job that brings `huginn_sources` to
|
||||
# the forge's and the chat reader's current state and exits. No daemon calls any of its writes.
|
||||
# the forge's current state and exits. No daemon calls any of its writes.
|
||||
[[bin]]
|
||||
name = "huginn-sources"
|
||||
path = "src/bin/huginn-sources.rs"
|
||||
|
|
@ -34,8 +34,7 @@ rmp-serde = "1"
|
|||
rustix = { version = "1", default-features = false, features = ["std", "net"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
# The vector store's and the embedder's HTTP APIs are the xenos boundary, and
|
||||
# JSON exists in `index/ollama.rs`, `index/qdrant.rs`, `sources/forge.rs` and
|
||||
# `sources/matrix.rs` only. `ureq` 3 with
|
||||
# JSON exists in `index/ollama.rs` and `index/qdrant.rs` only. `ureq` 3 with
|
||||
# default features off is plain HTTP with no TLS (`rustls` and `gzip` are its
|
||||
# only defaults), which is all the private mesh needs. It stays below 3.4,
|
||||
# whose `base64` 0.23 would put a second `base64` in a tree that has one.
|
||||
|
|
|
|||
|
|
@ -1,38 +1,21 @@
|
|||
//! The source index's refresh job: one run brings the forge corpus and, when
|
||||
//! configured, the rooms the chat reader has joined (minus the estate and DM
|
||||
//! exclusion) to current state, journals one line per repo and room, and exits
|
||||
//! nonzero if either failed or the collection could not be used. The
|
||||
//! `chat-purge` subcommand writes a steward's purge tombstone and nothing else.
|
||||
//!
|
||||
//! Exit status: 0 clean, 1 a run failed, 2 bad arguments, 3 another run (or a
|
||||
//! purge) holds the lock, which every run and every purge takes. The Matrix
|
||||
//! token is read from a file (a systemd credential), never from the environment or argv.
|
||||
//! The source index's refresh job: one run brings the `huginn_sources`
|
||||
//! collection to the forge's current state, journals one line per repo, and
|
||||
//! exits nonzero if any repo failed or the collection could not be used.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use huginn_daemon::index::ollama::pool;
|
||||
use huginn_daemon::index::qdrant::QdrantIndex;
|
||||
use huginn_daemon::sources::forge::HttpForge;
|
||||
use huginn_daemon::sources::job::{self, Chat, Purge};
|
||||
use huginn_daemon::sources::matrix::HttpMatrix;
|
||||
use huginn_daemon::sources::room_scope::{ESTATE_ALIASES, Estate};
|
||||
use huginn_daemon::sources::refresh;
|
||||
|
||||
/// Where the forge answers when the flag is absent: the loopback address of the
|
||||
/// forge on the host that runs this job.
|
||||
const DEFAULT_FORGE_URL: &str = "http://127.0.0.1:3310";
|
||||
|
||||
/// The chat flags, which come all together or not at all.
|
||||
struct ChatOptions {
|
||||
matrix_url: String,
|
||||
token: String,
|
||||
estate: Estate,
|
||||
}
|
||||
|
||||
struct Options {
|
||||
state_root: PathBuf,
|
||||
qdrant_url: String,
|
||||
|
|
@ -42,335 +25,75 @@ struct Options {
|
|||
reserve_urls: Vec<String>,
|
||||
embedding_model: String,
|
||||
forge_url: String,
|
||||
chat: Option<ChatOptions>,
|
||||
/// Every run takes it: the cursors object is replaced whole, with or without chat.
|
||||
lock_file: PathBuf,
|
||||
}
|
||||
|
||||
enum Command {
|
||||
Run(Options),
|
||||
Purge { qdrant_url: String, lock_file: PathBuf, purge: Purge },
|
||||
}
|
||||
|
||||
/// How a run ends other than by finishing.
|
||||
enum Stop {
|
||||
Usage(anyhow::Error),
|
||||
Locked,
|
||||
}
|
||||
|
||||
/// The single-valued options and the repeated ones, by name.
|
||||
type Collected = (BTreeMap<String, String>, BTreeMap<String, Vec<String>>);
|
||||
|
||||
/// The options named, each once, except those in `repeated`, which keep every value.
|
||||
fn collect(args: impl Iterator<Item = String>, once: &[&str], repeated: &[&str]) -> Result<Collected> {
|
||||
fn parse(args: impl Iterator<Item = String>) -> Result<Options> {
|
||||
let mut args = args;
|
||||
let mut singles = BTreeMap::new();
|
||||
let mut many: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
let mut values: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut ollama_urls = Vec::new();
|
||||
let mut reserve_urls = Vec::new();
|
||||
while let Some(name) = args.next() {
|
||||
let name = name.strip_prefix("--").with_context(|| format!("expected --option, got {name:?}"))?;
|
||||
ensure!(once.contains(&name) || repeated.contains(&name), "unsupported huginn-sources option --{name}");
|
||||
ensure!(
|
||||
matches!(name, "state-root" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url"),
|
||||
"unsupported huginn-sources option --{name}"
|
||||
);
|
||||
let value = args.next().with_context(|| format!("missing value for --{name}"))?;
|
||||
if repeated.contains(&name) {
|
||||
many.entry(name.to_owned()).or_default().push(value);
|
||||
if name == "ollama-url" || name == "reserve-ollama-url" {
|
||||
ensure!(value.starts_with("http://"), "--{name} must be a plain http:// address, got {value:?}");
|
||||
if name == "ollama-url" { ollama_urls.push(value) } else { reserve_urls.push(value) }
|
||||
} else {
|
||||
ensure!(singles.insert(name.to_owned(), value).is_none(), "duplicate option --{name}");
|
||||
ensure!(values.insert(name.to_owned(), value).is_none(), "duplicate option --{name}");
|
||||
}
|
||||
}
|
||||
Ok((singles, many))
|
||||
}
|
||||
|
||||
fn http(name: &str, value: String) -> Result<String> {
|
||||
ensure!(value.starts_with("http://"), "--{name} must be a plain http:// address, got {value:?}");
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// The Matrix reader's bearer travels in clear, and this build speaks no TLS: only a loopback host may be named.
|
||||
fn loopback_http(name: &str, value: String) -> Result<String> {
|
||||
let value = http(name, value)?;
|
||||
let authority = value["http://".len()..].split(['/', '?', '#']).next().unwrap_or("");
|
||||
let host = match authority.strip_prefix('[') {
|
||||
// The bracket must end the authority or be followed by the port, so `[::1].evil.example` names no loopback.
|
||||
Some(inner) => match inner.split_once(']') {
|
||||
Some((host, "")) => host,
|
||||
Some((host, port)) if port.starts_with(':') => host,
|
||||
_ => "",
|
||||
},
|
||||
None => authority.split(':').next().unwrap_or(""),
|
||||
let take = |name: &str| values.get(name).cloned().with_context(|| format!("--{name} is required"));
|
||||
let url = |name: &str, value: String| {
|
||||
ensure!(value.starts_with("http://"), "--{name} must be a plain http:// address, got {value:?}");
|
||||
Ok(value)
|
||||
};
|
||||
let loopback = !authority.contains('@') && (host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback()));
|
||||
ensure!(loopback, "--{name} must name a loopback host (localhost, 127.0.0.0/8 or [::1]): the bearer token travels in clear and this build has no TLS, got {value:?}");
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn absolute(name: &str, value: &str) -> Result<PathBuf> {
|
||||
let path = PathBuf::from(value);
|
||||
ensure!(path.is_absolute(), "--{name} must be an absolute path");
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn chat_options(singles: &BTreeMap<String, String>, excluded: Vec<String>) -> Result<Option<ChatOptions>> {
|
||||
let given = [singles.contains_key("matrix-url"), singles.contains_key("matrix-token-file"), !excluded.is_empty()];
|
||||
if !given.contains(&true) {
|
||||
return Ok(None);
|
||||
}
|
||||
for (present, name) in given.iter().zip(["matrix-url", "matrix-token-file", "chat-exclude-room"]) {
|
||||
ensure!(*present, "--{name} is missing: the chat flags (--matrix-url, --matrix-token-file, --chat-exclude-room) come all together or not at all");
|
||||
}
|
||||
let ids: BTreeSet<String> = excluded.iter().cloned().collect();
|
||||
ensure!(ids.len() == excluded.len(), "--chat-exclude-room must not repeat a room id");
|
||||
ensure!(ids.len() == ESTATE_ALIASES.len(), "--chat-exclude-room must be given exactly {} times (the ids of {})", ESTATE_ALIASES.len(), ESTATE_ALIASES.join(", "));
|
||||
ensure!(ids.iter().all(|id| id.starts_with('!')), "--chat-exclude-room takes room ids beginning with !, not aliases");
|
||||
let path = absolute("matrix-token-file", &singles["matrix-token-file"])?;
|
||||
let token = std::fs::read_to_string(&path).with_context(|| format!("reading --matrix-token-file {}", path.display()))?.trim().to_owned();
|
||||
ensure!(!token.is_empty(), "--matrix-token-file {} is empty", path.display());
|
||||
Ok(Some(ChatOptions { matrix_url: loopback_http("matrix-url", singles["matrix-url"].clone())?, token, estate: Estate::new(ids)? }))
|
||||
}
|
||||
|
||||
fn parse(mut args: impl Iterator<Item = String>, now: DateTime<Utc>) -> Result<Command> {
|
||||
let mut rest: Vec<String> = Vec::new();
|
||||
let first = args.next();
|
||||
if first.as_deref() == Some("chat-purge") {
|
||||
let (singles, _) = collect(args, &["qdrant-url", "room", "from", "to", "request", "lock-file"], &[])?;
|
||||
let take = |name: &str| singles.get(name).cloned().with_context(|| format!("--{name} is required"));
|
||||
return Ok(Command::Purge {
|
||||
qdrant_url: http("qdrant-url", take("qdrant-url")?)?,
|
||||
lock_file: absolute("lock-file", &take("lock-file")?)?,
|
||||
purge: Purge::check(&take("room")?, &take("from")?, &take("to")?, &take("request")?, now)?,
|
||||
});
|
||||
}
|
||||
rest.extend(first);
|
||||
let (mut singles, mut many) = collect(
|
||||
rest.into_iter().chain(args),
|
||||
&["state-root", "qdrant-url", "embedding-model", "forge-url", "matrix-url", "matrix-token-file", "lock-file"],
|
||||
&["ollama-url", "reserve-ollama-url", "chat-exclude-room"],
|
||||
)?;
|
||||
let mut hosts = |name: &str| -> Result<Vec<String>> { many.remove(name).unwrap_or_default().into_iter().map(|url| http(name, url)).collect() };
|
||||
let ollama_urls = hosts("ollama-url")?;
|
||||
let reserve_urls = hosts("reserve-ollama-url")?;
|
||||
let excluded = many.remove("chat-exclude-room").unwrap_or_default();
|
||||
let take = |singles: &mut BTreeMap<String, String>, name: &str| singles.remove(name).with_context(|| format!("--{name} is required"));
|
||||
let state_root = absolute("state-root", &take(&mut singles, "state-root")?)?;
|
||||
let embedding_model = take(&mut singles, "embedding-model")?;
|
||||
let state_root = PathBuf::from(take("state-root")?);
|
||||
ensure!(state_root.is_absolute(), "--state-root must be an absolute path");
|
||||
let embedding_model = take("embedding-model")?;
|
||||
ensure!(!embedding_model.is_empty(), "--embedding-model must name a model");
|
||||
ensure!(!ollama_urls.is_empty(), "at least one --ollama-url is required; repeat it for each GPU host");
|
||||
let chat = chat_options(&singles, excluded)?;
|
||||
let lock_file = absolute("lock-file", &take(&mut singles, "lock-file")?)?;
|
||||
Ok(Command::Run(Options {
|
||||
Ok(Options {
|
||||
state_root,
|
||||
qdrant_url: http("qdrant-url", take(&mut singles, "qdrant-url")?)?,
|
||||
ollama_urls,
|
||||
qdrant_url: url("qdrant-url", take("qdrant-url")?)?,
|
||||
ollama_urls: {
|
||||
ensure!(!ollama_urls.is_empty(), "at least one --ollama-url is required; repeat it for each GPU host");
|
||||
ollama_urls
|
||||
},
|
||||
reserve_urls,
|
||||
embedding_model,
|
||||
forge_url: http("forge-url", singles.remove("forge-url").unwrap_or_else(|| DEFAULT_FORGE_URL.to_owned()))?,
|
||||
chat,
|
||||
lock_file,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Takes the job's lock for the life of the returned file. A held lock means a run (or a
|
||||
/// purge request) is in progress and nothing may change: the cursors object is replaced whole.
|
||||
fn take_lock(path: &Path) -> Result<File, Stop> {
|
||||
let file = OpenOptions::new().create(true).truncate(false).write(true).open(path).with_context(|| format!("opening --lock-file {}", path.display())).map_err(Stop::Usage)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(file),
|
||||
Err(TryLockError::WouldBlock) => Err(Stop::Locked),
|
||||
Err(TryLockError::Error(error)) => Err(Stop::Usage(anyhow::Error::new(error).context(format!("locking --lock-file {}", path.display())))),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute(command: Command) -> Result<u8, Stop> {
|
||||
match command {
|
||||
Command::Purge { qdrant_url, lock_file, purge } => {
|
||||
let _lock = take_lock(&lock_file)?;
|
||||
let mut index = QdrantIndex::new(&qdrant_url);
|
||||
Ok(match job::purge(&mut index, &purge) {
|
||||
Ok(line) => {
|
||||
println!("{line}");
|
||||
0
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("huginn-sources: {error:#}");
|
||||
1
|
||||
}
|
||||
})
|
||||
}
|
||||
Command::Run(options) => {
|
||||
let _lock = take_lock(&options.lock_file)?;
|
||||
let mut embedder = pool(&options.ollama_urls, &options.reserve_urls, &options.embedding_model);
|
||||
let mut index = QdrantIndex::new(&options.qdrant_url);
|
||||
let mut forge = HttpForge::new(&options.forge_url);
|
||||
let mut matrix = options.chat.as_ref().map(|chat| HttpMatrix::new(&chat.matrix_url, &chat.token));
|
||||
let chat = matrix.as_mut().zip(options.chat.as_ref()).map(|(history, chat)| Chat { history, estate: &chat.estate });
|
||||
Ok(job::run(&mut embedder, &mut index, &mut forge, &options.state_root, chat, &mut |line| println!("{line}"), &mut |line| eprintln!("{line}")))
|
||||
}
|
||||
}
|
||||
forge_url: url("forge-url", values.get("forge-url").cloned().unwrap_or_else(|| DEFAULT_FORGE_URL.to_owned()))?,
|
||||
})
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match parse(std::env::args().skip(1), Utc::now()).map_err(Stop::Usage).and_then(execute) {
|
||||
Ok(status) => ExitCode::from(status),
|
||||
Err(Stop::Usage(error)) => {
|
||||
let options = match parse(std::env::args().skip(1)) {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
eprintln!("huginn-sources: {error:#}");
|
||||
ExitCode::from(2)
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
Err(Stop::Locked) => {
|
||||
eprintln!("huginn-sources: huginn-sources is running");
|
||||
ExitCode::from(3)
|
||||
};
|
||||
let mut embedder = pool(&options.ollama_urls, &options.reserve_urls, &options.embedding_model);
|
||||
let mut index = QdrantIndex::new(&options.qdrant_url);
|
||||
let mut forge = HttpForge::new(&options.forge_url);
|
||||
let mut journal = |report: &huginn_daemon::sources::Report| println!("{report}");
|
||||
match refresh(&mut embedder, &mut index, &mut forge, &options.state_root, &mut journal) {
|
||||
Ok(refreshed) if refreshed.is_clean() => ExitCode::SUCCESS,
|
||||
Ok(refreshed) => {
|
||||
if !refreshed.failed.is_empty() {
|
||||
eprintln!("huginn-sources: {} repos failed: {}", refreshed.failed.len(), refreshed.failed.join(", "));
|
||||
}
|
||||
if let Some(why) = &refreshed.retirement_withheld {
|
||||
eprintln!("huginn-sources: no repo was retired: {why}");
|
||||
}
|
||||
ExitCode::from(1)
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("huginn-sources: {error:#}");
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const NOW: &str = "2026-11-17T00:00:00Z";
|
||||
|
||||
fn args(text: &str) -> impl Iterator<Item = String> {
|
||||
text.split_whitespace().map(str::to_owned).collect::<Vec<_>>().into_iter()
|
||||
}
|
||||
|
||||
fn now() -> DateTime<Utc> {
|
||||
DateTime::parse_from_rfc3339(NOW).unwrap().with_timezone(&Utc)
|
||||
}
|
||||
|
||||
fn error(text: &str) -> String {
|
||||
match parse(args(text), now()) {
|
||||
Ok(_) => panic!("parsed: {text}"),
|
||||
Err(error) => format!("{error:#}"),
|
||||
}
|
||||
}
|
||||
|
||||
const BASE: &str = "--state-root /s --qdrant-url http://q --ollama-url http://o --embedding-model m";
|
||||
const IDS: &str = "--chat-exclude-room !a:s --chat-exclude-room !b:s --chat-exclude-room !c:s";
|
||||
|
||||
fn with_token(secret: &str) -> (tempfile::TempDir, String) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("token");
|
||||
std::fs::write(&path, secret).unwrap();
|
||||
let path = path.display().to_string();
|
||||
(dir, path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_flags_come_all_or_none() {
|
||||
let (_dir, token) = with_token(" sekret-token\n");
|
||||
let lock = "--lock-file /l";
|
||||
let base = format!("{BASE} {lock}");
|
||||
let full = format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} {IDS} {lock}");
|
||||
let Ok(Command::Run(options)) = parse(args(&full), now()) else { panic!("full chat flags must parse") };
|
||||
assert_eq!(options.chat.as_ref().unwrap().token, "sekret-token", "trimmed");
|
||||
assert!(matches!(parse(args(&base), now()), Ok(Command::Run(Options { chat: None, .. }))));
|
||||
assert!(error(BASE).contains("--lock-file is required"), "a chat-off run needs the lock too");
|
||||
assert!(error(&format!("{base} --matrix-url http://localhost")).contains("--matrix-token-file is missing"));
|
||||
assert!(error(&format!("{base} --matrix-token-file {token} {IDS}")).contains("--matrix-url is missing"));
|
||||
assert!(error(&format!("{base} --matrix-url http://localhost --matrix-token-file {token}")).contains("--chat-exclude-room is missing"));
|
||||
assert!(error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} {IDS}")).contains("--lock-file is required"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_flag_values_are_checked_and_never_print_the_token() {
|
||||
let (_dir, token) = with_token("sekret-token");
|
||||
let on = |extra: &str| format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} --lock-file /l {extra}");
|
||||
assert!(error(&on("--chat-exclude-room !a:s --chat-exclude-room !b:s")).contains("exactly 3"));
|
||||
assert!(error(&on(&format!("{IDS} --chat-exclude-room !d:s"))).contains("exactly 3"));
|
||||
assert!(error(&on("--chat-exclude-room !a:s --chat-exclude-room !a:s --chat-exclude-room !b:s")).contains("repeat"));
|
||||
assert!(error(&on("--chat-exclude-room !a:s --chat-exclude-room !b:s --chat-exclude-room #c:s")).contains("beginning with !"));
|
||||
assert!(error(&format!("{BASE} --matrix-url https://m --matrix-token-file {token} --lock-file /l {IDS}")).contains("plain http://"));
|
||||
assert!(error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file rel --lock-file /l {IDS}")).contains("absolute"));
|
||||
assert!(error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} --lock-file rel {IDS}")).contains("absolute"));
|
||||
let (_empty, empty) = with_token(" \n");
|
||||
let message = error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {empty} --lock-file /l {IDS}"));
|
||||
assert!(message.contains(&empty) && message.contains("empty"));
|
||||
let missing = error(&format!("{BASE} --matrix-url http://localhost --matrix-token-file /nowhere/t --lock-file /l {IDS}"));
|
||||
assert!(missing.contains("/nowhere/t"));
|
||||
for text in [on(IDS), on("--chat-exclude-room !a:s")] {
|
||||
assert!(!error(&format!("{text} --nope x")).contains("sekret-token"));
|
||||
}
|
||||
let dead = ["--chat", "room"].join("-");
|
||||
assert!(error(&format!("{BASE} {dead} !x:s")).contains(&format!("unsupported huginn-sources option {dead}")));
|
||||
}
|
||||
|
||||
fn purge(extra: &str) -> String {
|
||||
error(&format!("chat-purge --qdrant-url http://q --lock-file /l {extra}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_purge_arguments() {
|
||||
let good = "--room !r:s --from 2026-11-10T00:00:00Z --to 2026-11-11T00:00:00Z --request ref-1";
|
||||
let Ok(Command::Purge { purge: asked, .. }) = parse(args(&format!("chat-purge --qdrant-url http://q --lock-file /l {good}")), now()) else { panic!() };
|
||||
assert_eq!((asked.window.from_ms, asked.window.to_ms), (1_794_268_800_000, 1_794_355_200_000));
|
||||
let bad = |from: &str, to: &str, room: &str, request: &str| purge(&format!("--room {room} --from {from} --to {to} --request {request}"));
|
||||
let (f, t) = ("2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z");
|
||||
assert!(bad(f, t, "#a:s", "r").contains("--room"));
|
||||
assert!(bad("2026-11-10T00:00:00+00:00", t, "!r:s", "r").contains("--from"));
|
||||
assert!(bad(f, "2026-11-11T00:00:00", "!r:s", "r").contains("--to"));
|
||||
assert!(bad(t, f, "!r:s", "r").contains("before"));
|
||||
assert!(bad(f, "2026-11-18T00:00:00Z", "!r:s", "r").contains("after now"));
|
||||
assert!(bad("2025-11-09T00:00:00Z", t, "!r:s", "r").contains("366"));
|
||||
assert!(purge(&format!("--room !r:s --from {f} --to {t} --request {}", "x".repeat(121))).contains("--request"));
|
||||
assert!(purge("--room !r:s --from 2026-11-10T00:00:00Z --to 2026-11-11T00:00:00Z").contains("--request is required"));
|
||||
assert!(parse(args(&format!("chat-purge --qdrant-url http://q --lock-file /l {good} --matrix-url http://localhost")), now()).is_err(), "no Matrix flags");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_url_must_be_loopback_http() {
|
||||
let (_dir, token) = with_token("sekret-token");
|
||||
let with = |url: &str| format!("{BASE} --matrix-url {url} --matrix-token-file {token} --lock-file /l {IDS}");
|
||||
for good in ["http://localhost", "http://127.0.0.1:8008", "http://127.9.9.9/", "http://[::1]:8008", "http://LOCALHOST:1/x"] {
|
||||
assert!(parse(args(&with(good)), now()).is_ok(), "{good}");
|
||||
}
|
||||
for bad in ["http://matrix.example", "http://10.0.0.5:8008", "http://localhost@evil.example", "http://127.0.0.1.evil.example", "http://localhost.evil.example", "http://[::2]", "https://localhost", "http://127.0.0.1:pw@evil.example", "http://[::1].evil.example", "http://[::1]x"] {
|
||||
assert!(error(&with(bad)).contains("--matrix-url"), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_lock_exits_3_through_execute_for_both_modes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lock = dir.path().join("lock");
|
||||
let held = take_lock(&lock).ok().unwrap();
|
||||
let lock = lock.display().to_string();
|
||||
let good = "--room !r:s --from 2026-11-10T00:00:00Z --to 2026-11-11T00:00:00Z --request r";
|
||||
let purge = parse(args(&format!("chat-purge --qdrant-url http://127.0.0.1:1 --lock-file {lock} {good}")), now()).unwrap();
|
||||
assert!(matches!(execute(purge), Err(Stop::Locked)));
|
||||
let (_t, token) = with_token("sekret-token");
|
||||
let run = parse(args(&format!("{BASE} --matrix-url http://localhost --matrix-token-file {token} {IDS} --lock-file {lock}")), now()).unwrap();
|
||||
assert!(matches!(execute(run), Err(Stop::Locked)));
|
||||
let off = parse(args(&format!("{BASE} --lock-file {lock}")), now()).unwrap();
|
||||
assert!(matches!(execute(off), Err(Stop::Locked)), "a chat-off run must not write cursors under a held lock");
|
||||
drop(held);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lock_is_held_for_the_whole_run() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lock = dir.path().join("lock");
|
||||
// A qdrant that accepts the run's first request and says nothing: the run is mid-flight while we probe the lock.
|
||||
let qdrant = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}", qdrant.local_addr().unwrap());
|
||||
let run = parse(args(&format!("--state-root /s --qdrant-url {url} --ollama-url http://127.0.0.1:1 --embedding-model m --lock-file {}", lock.display())), now()).unwrap();
|
||||
let worker = std::thread::spawn(move || execute(run));
|
||||
let (connection, _) = qdrant.accept().unwrap();
|
||||
assert!(matches!(take_lock(&lock), Err(Stop::Locked)), "the run must hold the lock while it works");
|
||||
drop(connection);
|
||||
// Refuse any retry the same way until the run gives up.
|
||||
qdrant.set_nonblocking(true).unwrap();
|
||||
while !worker.is_finished() {
|
||||
drop(qdrant.accept());
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
assert!(worker.join().unwrap().is_ok());
|
||||
assert!(take_lock(&lock).is_ok(), "the lock is released when the run ends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_lock_stops_the_run_untouched() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("lock");
|
||||
let held = take_lock(&path).ok().unwrap();
|
||||
assert!(matches!(take_lock(&path), Err(Stop::Locked)));
|
||||
drop(held);
|
||||
assert!(take_lock(&path).is_ok());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use chrono::{DateTime, Utc};
|
|||
use cultnet_rs::Selection;
|
||||
use crate::sources::forge::HttpForge;
|
||||
use huginn_mind::desk_wire::{DeskRequest, DeskResponse};
|
||||
use huginn_mind::eureka_pipeline::{AccountId, PipelineRef, Short, Slug};
|
||||
use huginn_mind::eureka_pipeline::{PipelineRef, Slug};
|
||||
use huginn_mind::wire::{ACTIVITY_REPOS_MAX, HuginnMindRequest, HuginnMindResponse, IndexStatus};
|
||||
use huginn_mind::{ChatHits, ChatQuery, ChatWindow, ChatWindowQuery, Members, Mind, MindRefusal, MindStore, PipelineAdmissionOutcome, SemanticQuery, SourceHits, SourceQuery};
|
||||
|
||||
|
|
@ -109,26 +109,6 @@ impl Handled {
|
|||
}
|
||||
}
|
||||
|
||||
/// Which RUDP listener a request arrived on. `Full` is `--bind`, which the
|
||||
/// faculties that write the mind reach. `Persona` is `--persona-bind`, the
|
||||
/// only listener a Persona's uid can reach (the host fence decides that): it
|
||||
/// answers what `HuginnMindRequest::reaches_persona_door` accepts and refuses
|
||||
/// the rest with `MindRefusal::NotThisDoor` before the mind is asked.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Door {
|
||||
Full,
|
||||
Persona,
|
||||
}
|
||||
|
||||
/// The door checks an account id; the Mind's desk calls take it as the text it is.
|
||||
fn short_id(id: AccountId) -> Short {
|
||||
Short(id.0)
|
||||
}
|
||||
|
||||
fn short_ids(ids: &[AccountId]) -> Vec<Short> {
|
||||
ids.iter().map(|id| Short(id.0.clone())).collect()
|
||||
}
|
||||
|
||||
/// What the log says of the hits the mind held no document for: how many, and
|
||||
/// the first few by name (a restored mind can leave hundreds), or nothing when
|
||||
/// the mind held them all.
|
||||
|
|
@ -188,16 +168,6 @@ impl<S: MindStore, I: IndexSink<S>> Daemon<S, I> {
|
|||
runtime_id(self.mind.instance())
|
||||
}
|
||||
|
||||
/// One request as it arrived at `door`: a request the door does not
|
||||
/// answer is refused before the mind sees it, and every other goes to
|
||||
/// `handle`. The wire reaches the mind only through here.
|
||||
pub fn handle_at(&mut self, door: Door, request: HuginnMindRequest, now: DateTime<Utc>) -> Handled {
|
||||
if door == Door::Persona && !request.reaches_persona_door() {
|
||||
return Handled::Answered(HuginnMindResponse::Refused(MindRefusal::NotThisDoor));
|
||||
}
|
||||
self.handle(request, now)
|
||||
}
|
||||
|
||||
/// One request, one answer, or a search to finish. `Admit` goes to the mind whole, because the
|
||||
/// batch declares its own instance and admission's A1 is the check. Every
|
||||
/// other request names an instance: `require_instance` now applies the
|
||||
|
|
@ -293,18 +263,18 @@ impl<S: MindStore, I: IndexSink<S>> Daemon<S, I> {
|
|||
/// One desk request, answered by the Mind method it names. The Mind is the instance's own
|
||||
/// (`mind` is checked against it); `deciders` is this call's list, handed to the Mind and
|
||||
/// dropped. A desk answer is not indexed (`index_text` gives it no text), so nothing here tells the index.
|
||||
/// The reads are handed `subject` and `deciders`: the Mind builds a decider's view or a
|
||||
/// non-decider's (ruling `desk-read-visibility-withheld-ids`).
|
||||
/// The reads answer with the whole record and nothing here gates them (ruling
|
||||
/// `desk-read-visibility-whole-record`): they are handed `deciders` and not `subject`.
|
||||
pub fn handle_desk(&mut self, request: DeskRequest, now: DateTime<Utc>) -> DeskResponse {
|
||||
if let Err(refusal) = self.mind.require_instance(request.mind()) {
|
||||
return DeskResponse::Refused(refusal);
|
||||
}
|
||||
match request {
|
||||
DeskRequest::Answer { subject, authority, deciders, request, .. } => {
|
||||
self.mind.desk_answer(&short_ids(&deciders), short_id(subject), authority, request, now)
|
||||
self.mind.desk_answer(&deciders, subject, authority, request, now)
|
||||
}
|
||||
DeskRequest::Forks { subject, deciders, status, cursor, limit, .. } => self.mind.desk_forks(&short_id(subject), &short_ids(&deciders), status, cursor, limit),
|
||||
DeskRequest::Fork { subject, deciders, fork_id, .. } => self.mind.desk_fork(&short_id(subject), &short_ids(&deciders), &fork_id),
|
||||
DeskRequest::Forks { deciders, status, cursor, limit, .. } => self.mind.desk_forks(&deciders, status, cursor, limit),
|
||||
DeskRequest::Fork { deciders, fork_id, .. } => self.mind.desk_fork(&deciders, &fork_id),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1032,117 +1002,6 @@ pub(crate) mod tests {
|
|||
assert_eq!(status(&mut daemon).persona, huginn_mind::wire::PersonaStatus::Absent);
|
||||
}
|
||||
|
||||
/// The persona door refuses an admission before the mind sees it, so the
|
||||
/// store is unchanged, and answers the reads and her own persona put; the
|
||||
/// full door admits the same batch.
|
||||
#[test]
|
||||
fn the_persona_door_refuses_an_admission_and_answers_reads_and_her_persona() {
|
||||
let (_root, mut daemon) = seeded();
|
||||
let before = status(&mut daemon);
|
||||
let admit = || HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)]));
|
||||
assert_eq!(
|
||||
daemon.handle_at(Door::Persona, admit(), now()).answered(),
|
||||
HuginnMindResponse::Refused(MindRefusal::NotThisDoor)
|
||||
);
|
||||
assert_eq!(status(&mut daemon), before, "nothing was written");
|
||||
|
||||
let state = serde_json::json!({
|
||||
"schemaVersion": "gamecult.persona_state.v0",
|
||||
"provenance": {
|
||||
"sourceSystem": "huginn", "sourceDocumentId": INSTANCE, "sourceUpdatedAt": "2026-11-19T10:00:00Z",
|
||||
"exportedAt": "2026-11-19T10:00:00Z", "authority": "canonical"
|
||||
},
|
||||
"personaId": INSTANCE,
|
||||
"publicName": "Test Persona",
|
||||
"presentation": { "voiceSummary": "plain" },
|
||||
"activationProfile": {
|
||||
"underlyingOrganization": {}, "stableDispositions": {}, "behavioralDimensions": {},
|
||||
"presentationStrategy": {}, "voiceStyle": {}, "situationalState": {}
|
||||
},
|
||||
"thoughtMemory": { "shortTerm": [], "memories": [], "incubation": [] },
|
||||
"agencyPressure": { "pressures": [] },
|
||||
"candidateActions": { "actions": [] },
|
||||
"affect": {
|
||||
"needs": [], "socialBonds": [], "statusReads": [], "moodDimensions": [],
|
||||
"socialBiases": [], "doctrineStances": []
|
||||
},
|
||||
"updatedAt": "2026-11-19T10:00:00Z"
|
||||
});
|
||||
let put = HuginnMindRequest::PersonaPut {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: provenance(),
|
||||
state,
|
||||
expected_updated_at: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
daemon.handle_at(Door::Persona, put, now()).answered(),
|
||||
HuginnMindResponse::PersonaPut(huginn_mind::PersonaPutOutcome::Committed { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
daemon.handle_at(Door::Persona, HuginnMindRequest::PersonaGet { instance: slug(INSTANCE) }, now()).answered(),
|
||||
HuginnMindResponse::Persona(Some(_))
|
||||
));
|
||||
let query = HuginnMindRequest::Query { instance: slug(INSTANCE), selection: Selection::default(), semantic: None };
|
||||
let HuginnMindResponse::Query(page) = daemon.handle_at(Door::Persona, query, now()).answered() else {
|
||||
panic!("a query answers a page at the persona door")
|
||||
};
|
||||
let id = match page.items {
|
||||
PipelinePageItems::Headers(items) => items[0].id.clone(),
|
||||
PipelinePageItems::Documents(items) => items[0].id.clone(),
|
||||
};
|
||||
assert!(matches!(
|
||||
daemon.handle_at(Door::Persona, HuginnMindRequest::View { instance: slug(INSTANCE), id }, now()).answered(),
|
||||
HuginnMindResponse::View(Some(_))
|
||||
));
|
||||
assert_eq!(status(&mut daemon).documents, before.documents, "a persona put writes no pipeline document");
|
||||
|
||||
assert!(
|
||||
matches!(daemon.handle_at(Door::Full, admit(), now()).answered(), HuginnMindResponse::Admit(_)),
|
||||
"the full door hands the same batch to admission"
|
||||
);
|
||||
}
|
||||
|
||||
/// Every read the persona door answers reaches the mind there: none of the
|
||||
/// source, chat, activity and roots reads is refused as `NotThisDoor`.
|
||||
/// What the mind then says (a search, or `Unavailable` with no index or
|
||||
/// forge) is the mind's, the same at either door.
|
||||
#[test]
|
||||
fn the_persona_door_hands_every_other_read_to_the_mind() {
|
||||
use huginn_mind::wire::{ChatWindowQuery, SourceQuery};
|
||||
let (_root, mut daemon) = seeded();
|
||||
let reads = [
|
||||
HuginnMindRequest::SearchSources {
|
||||
instance: slug(INSTANCE),
|
||||
query: SourceQuery { text: Line("reconcile".into()), texts: vec![], top_k: 5, repo: None, front: false },
|
||||
},
|
||||
HuginnMindRequest::SearchChat {
|
||||
instance: slug(INSTANCE),
|
||||
query: ChatQuery { texts: vec![Line("release".into())], rooms: vec![], after_ms: None, before_ms: None, top_k: 5 },
|
||||
},
|
||||
HuginnMindRequest::ChatWindow {
|
||||
instance: slug(INSTANCE),
|
||||
query: ChatWindowQuery { event_id: Short("$a".into()), before: 5, after: 0 },
|
||||
},
|
||||
HuginnMindRequest::StewardedActivity { instance: slug(INSTANCE), repos: vec![], after: None },
|
||||
HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) },
|
||||
];
|
||||
for read in reads {
|
||||
let operation = read.operation();
|
||||
let at_door = daemon.handle_at(Door::Persona, read.clone(), now());
|
||||
assert!(
|
||||
!matches!(at_door, Handled::Answered(HuginnMindResponse::Refused(MindRefusal::NotThisDoor))),
|
||||
"{operation} is refused at the persona door"
|
||||
);
|
||||
if let (Handled::Answered(at_door), Handled::Answered(at_full)) = (at_door, daemon.handle_at(Door::Full, read, now())) {
|
||||
assert_eq!(at_door, at_full, "{operation} answers the same at either door");
|
||||
}
|
||||
}
|
||||
assert!(matches!(
|
||||
daemon.handle_at(Door::Persona, HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) }, now()).answered(),
|
||||
HuginnMindResponse::RootsTouched(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// A declared instance outside `Slug`'s grammar is refused by its own
|
||||
/// name, `InvalidFormat`, on the read path, before the identity
|
||||
/// comparison ever runs: it is not merely a foreign mind, it names no
|
||||
|
|
|
|||
|
|
@ -10,22 +10,16 @@
|
|||
//! deadline like one that is silent), a reply past `DESK_MAX_RESPONSE_BYTES` refused by name (a read of one
|
||||
//! fork past it is that fork's `fork_too_large`).
|
||||
//!
|
||||
//! The trust boundary of the reads (ruling `desk-read-visibility-withheld-ids`). The peer-uid check
|
||||
//! The trust boundary of the reads (ruling `desk-read-visibility-whole-record`). The peer-uid check
|
||||
//! IS the whole authentication: Huginn must be reachable only by Bifrost's peer-checked socket, so
|
||||
//! the configured uid is Bifrost's and no other process's. `Forks` and `Fork` carry every decider's
|
||||
//! note to whoever passes that check, and Bifrost strips notes at its own door (a stripped read
|
||||
//! serves `note: null`, CultLib `fork-card.md`); a second reader of this socket is therefore a note
|
||||
//! leak, and a deployment that gives the socket to any uid but Bifrost's has no reader check left.
|
||||
//! Account ids are Huginn's to withhold: a reader whose `subject` is not in the call's `deciders`
|
||||
//! gets `deciders` empty, `answerer` nil and the counts instead. The reads carry no `authority` (a
|
||||
//! payload that names one is refused whole), and the door has no other way to ask who is reading.
|
||||
//!
|
||||
//! The listing gate: a reader who is not a decider sees a fork only while a `desk_listing` for it is
|
||||
//! in force, and a fork it may not see reads `fork_unknown`, the same bytes as a missing one, on
|
||||
//! every desk operation, a replay of a stored answer included. The door never writes a listing; it
|
||||
//! arrives by the RUDP Admit door only. Unlisting is a `Withdrawn` resolution on the listing, and
|
||||
//! admitting the listing again after that returns `AlreadyAdmitted` and the fork stays hidden:
|
||||
//! relisting is withdrawing the withdrawal, not a second admission.
|
||||
//! the configured uid is Bifrost's and no other process's. `Forks` and `Fork` return the WHOLE record
|
||||
//! (cards, outcomes, every decider's note) to whoever passes that check; nothing in Huginn strips a
|
||||
//! note or gates a read on `subject` or `deciders` (`deciders` only fills the card and the
|
||||
//! showability gate). Bifrost applies visibility at its own door (a stripped read serves `note: null`,
|
||||
//! CultLib `fork-card.md`). A second reader of this socket is therefore a note leak, and a deployment
|
||||
//! that gives the socket to any uid but Bifrost's has no reader check left. The reads carry no
|
||||
//! `authority` (a payload that names one is refused whole), and the door has no other way to ask who
|
||||
//! is reading.
|
||||
//!
|
||||
//! It owns no rule. Which Mind method answers is `Daemon::handle_desk`'s; when the door is
|
||||
//! served is `serve::run`'s, once per pass in the thread that owns the Mind. A peer that is
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ use cultnet_rs::{
|
|||
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, encode_frame,
|
||||
};
|
||||
use huginn_mind::desk_wire::{
|
||||
DESK_REQUEST_SCHEMA, DESK_SERVICE_ID, DeskRequest, DeskResponse, ForkAnswer, ForkAnswerCode, ForkAnswerRequest, ForkCursor,
|
||||
DESK_MAX_RESPONSE_BYTES, DESK_REQUEST_SCHEMA, DESK_SERVICE_ID, DeskRequest, DeskResponse, ForkAnswer, ForkAnswerCode, ForkAnswerRequest, ForkCursor,
|
||||
ForkEntry, ForkLimit, ForkList, ListStatus, RequestSchema,
|
||||
};
|
||||
use huginn_mind::envelope::{OperationFailure, decode_desk_response, decode_response, encode_desk_request, encode_request};
|
||||
|
|
@ -85,26 +85,20 @@ fn wire(hash: &str, request_id: &str) -> ForkAnswerRequest {
|
|||
}
|
||||
}
|
||||
|
||||
/// A test's name for someone as the Bifrost account id the door requires: a deterministic lowercase D-format UUID.
|
||||
fn acct(name: &str) -> huginn_mind::eureka_pipeline::AccountId {
|
||||
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
|
||||
huginn_mind::eureka_pipeline::AccountId(format!("{:08x}-{:04x}-4000-8000-{:012x}", hash >> 32, (hash >> 16) & 0xffff, hash & 0xffff_ffff_ffff))
|
||||
}
|
||||
|
||||
const R1: &str = "00000000-0000-4000-8000-000000000001";
|
||||
const R2: &str = "00000000-0000-4000-8000-000000000002";
|
||||
const R3: &str = "00000000-0000-4000-8000-000000000003";
|
||||
|
||||
fn answer(who: &str, authority: DeskAuthority, deciders: &[&str], request: ForkAnswerRequest) -> DeskRequest {
|
||||
DeskRequest::Answer { mind: slug(INSTANCE), subject: acct(who), authority, deciders: deciders.iter().map(|d| acct(d)).collect(), request }
|
||||
DeskRequest::Answer { mind: slug(INSTANCE), subject: short(who), authority, deciders: deciders.iter().map(|d| short(d)).collect(), request }
|
||||
}
|
||||
|
||||
/// A list read by `who` against `deciders`.
|
||||
fn forks(who: &str, deciders: &[&str], status: Option<ListStatus>, cursor: Option<ForkCursor>, limit: u8) -> DeskRequest {
|
||||
DeskRequest::Forks {
|
||||
mind: slug(INSTANCE),
|
||||
subject: acct(who),
|
||||
deciders: deciders.iter().map(|d| acct(d)).collect(),
|
||||
subject: short(who),
|
||||
deciders: deciders.iter().map(|d| short(d)).collect(),
|
||||
status,
|
||||
cursor,
|
||||
limit: ForkLimit::new(limit).unwrap(),
|
||||
|
|
@ -116,7 +110,7 @@ fn forks_all(deciders: &[&str]) -> DeskRequest {
|
|||
}
|
||||
|
||||
fn fork_read(who: &str, deciders: &[&str], fork_id: &str) -> DeskRequest {
|
||||
DeskRequest::Fork { mind: slug(INSTANCE), subject: acct(who), deciders: deciders.iter().map(|d| acct(d)).collect(), fork_id: fork_id.into() }
|
||||
DeskRequest::Fork { mind: slug(INSTANCE), subject: short(who), deciders: deciders.iter().map(|d| short(d)).collect(), fork_id: fork_id.into() }
|
||||
}
|
||||
|
||||
fn page_of(response: DeskResponse) -> (ForkList, u64) {
|
||||
|
|
@ -211,13 +205,6 @@ fn rig(peer_uid: u32) -> Rig {
|
|||
}
|
||||
|
||||
impl Rig {
|
||||
/// The Mind lists the seeded fork, on its own door, so a non-decider reaches it.
|
||||
fn list_the_fork(&mut self) {
|
||||
let listing = PipelineDocument::DeskListing(huginn_mind::eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: short(FORK), reason: "Listed.".into() });
|
||||
let admitted = self.daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![listing])), now()).answered();
|
||||
assert!(matches!(admitted, HuginnMindResponse::Admit(huginn_mind::PipelineAdmissionOutcome::Committed { .. })), "{admitted:?}");
|
||||
}
|
||||
|
||||
/// Runs `client` on its own thread while this one serves the door, then drains what is still waiting.
|
||||
fn serving<T: Send>(&mut self, client: impl FnOnce(&Path) -> T + Send) -> T {
|
||||
let path = self.path.clone();
|
||||
|
|
@ -467,7 +454,7 @@ mod door_smoke {
|
|||
let stopping = Arc::new(AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let serving = std::thread::spawn(move || {
|
||||
run(&mut daemon, &mut hub, None, ®istry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap();
|
||||
run(&mut daemon, &mut hub, ®istry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap();
|
||||
});
|
||||
|
||||
let mut stalled = connect(&path);
|
||||
|
|
@ -580,7 +567,7 @@ mod door_smoke {
|
|||
claim_in_future: false,
|
||||
request_id: RequestId(R1.into()),
|
||||
body_sha256: Sha256Hex("0".repeat(64)),
|
||||
answerer: acct("x"),
|
||||
answerer: short("x"),
|
||||
authority: DeskAuthority::Operator,
|
||||
outcome: DeskOutcome::Counted,
|
||||
});
|
||||
|
|
@ -591,7 +578,7 @@ mod door_smoke {
|
|||
let registry = schema_registry().unwrap();
|
||||
let mut bodies = crate::bodies::DeferredBodies::new(1 << 20, Duration::from_secs(60));
|
||||
let desk = raw(MIND_SERVICE_ID, DESK_REQUEST_SCHEMA, "answer", "m-1", rmp_serde::to_vec_named(&answer("x", DeskAuthority::Operator, &["x"], wire(&hash, R1))).unwrap());
|
||||
let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, crate::daemon::Door::Full, ®istry, &mut bodies, desk, now()).reply() else {
|
||||
let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, ®istry, &mut bodies, desk, now()).reply() else {
|
||||
panic!("expected a response")
|
||||
};
|
||||
assert_eq!(payload_schema, huginn_mind::envelope::FAILURE_SCHEMA);
|
||||
|
|
@ -614,7 +601,6 @@ mod door_smoke {
|
|||
#[test]
|
||||
fn deciders_ride_each_request() {
|
||||
let mut rig = rig(my_uid());
|
||||
rig.list_the_fork();
|
||||
let (before, hash) = (rig.state(), rig.hash.clone());
|
||||
let out = rig.serving(|path| {
|
||||
let ask = |id: &str, who: &str, deciders: &[&str], request_id: &str| {
|
||||
|
|
@ -686,7 +672,6 @@ mod door_smoke {
|
|||
state_root: root.path().to_path_buf(),
|
||||
instance: slug(INSTANCE),
|
||||
bind: "127.0.0.1:0".parse().unwrap(),
|
||||
persona_bind: None,
|
||||
qdrant_url: "http://127.0.0.1:1".into(),
|
||||
ollama_urls: vec!["http://127.0.0.1:1".into()],
|
||||
reserve_ollama_urls: Vec::new(),
|
||||
|
|
@ -791,7 +776,6 @@ mod door_smoke {
|
|||
#[test]
|
||||
fn a_mind_refusal_and_a_stored_refusal_are_typed_replies() {
|
||||
let mut rig = rig(my_uid());
|
||||
rig.list_the_fork();
|
||||
let (before, hash) = (rig.state(), rig.hash.clone());
|
||||
let mut foreign = answer("x", DeskAuthority::Member, &["x"], wire(&hash, R1));
|
||||
let DeskRequest::Answer { mind, .. } = &mut foreign else { unreachable!() };
|
||||
|
|
@ -817,7 +801,7 @@ mod door_smoke {
|
|||
assert_eq!((listed_at, read_at), (before.1 as u64, before.1 as u64), "both read at the head the mind held");
|
||||
assert_eq!(list.stamp, format!("s{listed_at}"));
|
||||
assert_eq!(list.forks[0], entry);
|
||||
assert_eq!((entry.card.fork_id.as_str(), entry.card.options_hash.as_str(), entry.card.deciders.as_slice()), (FORK, hash.as_str(), [acct("x").0, acct("y").0].as_slice()));
|
||||
assert_eq!((entry.card.fork_id.as_str(), entry.card.options_hash.as_str(), entry.card.deciders.as_slice()), (FORK, hash.as_str(), ["x".to_string(), "y".to_string()].as_slice()));
|
||||
assert_eq!(rig.state(), before, "a read stores nothing");
|
||||
assert!(rig.index.seen.lock().unwrap().is_empty());
|
||||
// An unknown fork is the answer path's refusal.
|
||||
|
|
@ -871,43 +855,29 @@ mod door_smoke {
|
|||
}
|
||||
}
|
||||
|
||||
/// Ruling `desk-read-visibility-withheld-ids`: a subject the call's deciders do not name gets counts
|
||||
/// and no account id, over the socket too; notes stay whole (Bifrost strips them). A decider gets the ids.
|
||||
/// Ruling `desk-read-visibility-whole-record`: Huginn returns the whole record, notes included, to
|
||||
/// whoever the socket carries. The subject is not in the deciders; the decider's note is there.
|
||||
#[test]
|
||||
fn a_subject_not_in_deciders_gets_counts_and_no_account_id() {
|
||||
fn a_subject_not_in_deciders_reads_the_whole_record_with_the_notes() {
|
||||
let mut rig = rig(my_uid());
|
||||
let hash = rig.hash.clone();
|
||||
let note = "Keep it local: the author's call.";
|
||||
rig.serving(|path| counted(reply_of(path, "m-1", &DeskRequest::Answer {
|
||||
mind: slug(INSTANCE),
|
||||
subject: acct("y"),
|
||||
subject: short("y"),
|
||||
authority: DeskAuthority::Member,
|
||||
deciders: vec![acct("y")],
|
||||
deciders: vec![short("y")],
|
||||
request: noted(&hash, R1, note),
|
||||
})));
|
||||
// Unlisted: the outsider is shown nothing at all, and a read is `fork_unknown`.
|
||||
let (hidden, unknown) = rig.serving(|path| (reply_of(path, "m-1", &forks("outsider", &["x"], None, None, 50)), reply_of(path, "m-1b", &fork_read("outsider", &["x"], FORK))));
|
||||
assert_eq!(page_of(hidden).0.forks.len(), 0);
|
||||
assert!(matches!(unknown, DeskResponse::NotStored(_)), "{unknown:?}");
|
||||
// The Mind lists it, on its own door.
|
||||
let listing = PipelineDocument::DeskListing(huginn_mind::eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: short(FORK), reason: "Members may read why.".into() });
|
||||
let admitted = rig.daemon.handle(HuginnMindRequest::Admit(batch(INSTANCE, vec![listing])), now()).answered();
|
||||
assert!(matches!(admitted, HuginnMindResponse::Admit(huginn_mind::PipelineAdmissionOutcome::Committed { .. })), "{admitted:?}");
|
||||
let (list, read) = rig.serving(|path| (reply_of(path, "m-2", &forks("outsider", &["x"], None, None, 50)), reply_of(path, "m-3", &fork_read("outsider", &["x"], FORK))));
|
||||
let (list, _) = page_of(list);
|
||||
let (read, _) = entry_of(read);
|
||||
for entry in [&list.forks[0], &read] {
|
||||
assert_eq!(entry.record.answers.len(), 1);
|
||||
assert_eq!(entry.record.answers[0].note.as_deref(), Some(note));
|
||||
assert_eq!(entry.record.answers[0].answerer, None);
|
||||
assert_eq!(entry.record.answerer_count, 1);
|
||||
assert!(entry.card.deciders.is_empty());
|
||||
assert_eq!(entry.card.decider_count, 1);
|
||||
assert_eq!(entry.record.answers[0].answerer, "y");
|
||||
assert_eq!(entry.card.deciders, ["x"], "the list is the call's, and only fills the card");
|
||||
}
|
||||
let seen = rig.serving(|path| reply_of(path, "m-4", &fork_read("x", &["x"], FORK)));
|
||||
let (seen, _) = entry_of(seen);
|
||||
assert_eq!(seen.card.deciders, [acct("x").0]);
|
||||
assert_eq!(seen.record.answers[0].answerer.as_deref(), Some(acct("y").0.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -926,7 +896,7 @@ mod door_smoke {
|
|||
let refused = rig.serving(|path| failure_of(path, &bytes));
|
||||
assert_eq!(refused.code, "payload-not-a-request", "{what}");
|
||||
assert!(refused.message.contains("deciders"), "{what}: {}", refused.message);
|
||||
assert!(!refused.message.contains(&acct("d64").0), "{what} echoes a decider: {}", refused.message);
|
||||
assert!(!refused.message.contains("d64"), "{what} echoes a decider: {}", refused.message);
|
||||
}
|
||||
assert_eq!(rig.state(), before, "nothing stored, head unchanged");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! The process: open one instance's mind, bind its socket (and the persona
|
||||
//! door's, when asked), serve until a stop signal. A mind that will not open ends the process with the refusal on
|
||||
//! The process: open one instance's mind, bind one socket, serve until a stop
|
||||
//! signal. A mind that will not open ends the process with the refusal on
|
||||
//! stderr and no socket ever bound.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
|
@ -15,7 +15,7 @@ fn main() -> Result<()> {
|
|||
let options = parse_options(std::env::args().skip(1))?;
|
||||
let embedder = pool(&options.ollama_urls, &options.reserve_ollama_urls, &options.embedding_model);
|
||||
let index = QdrantIndex::new(&options.qdrant_url);
|
||||
let Started { mut daemon, mut hub, mut persona, registry, mut desk } = match startup(&options, embedder, index, Backoff::default()) {
|
||||
let Started { mut daemon, mut hub, registry, mut desk } = match startup(&options, embedder, index, Backoff::default()) {
|
||||
Ok(started) => started,
|
||||
Err(error) => {
|
||||
eprintln!("huginn-daemon refuses to serve {}: {error:#}", options.instance.0);
|
||||
|
|
@ -33,11 +33,8 @@ fn main() -> Result<()> {
|
|||
}
|
||||
|
||||
eprintln!("huginn-daemon serving {} on {}", options.instance.0, hub.local_addr()?);
|
||||
if let Some(door) = &persona {
|
||||
eprintln!("huginn-daemon serving the persona door on {}", door.local_addr()?);
|
||||
}
|
||||
if let Some(door) = &desk {
|
||||
eprintln!("huginn-daemon serving the desk door on {}", door.path().display());
|
||||
}
|
||||
run(&mut daemon, &mut hub, persona.as_mut(), ®istry, desk.as_mut(), &stopping, &ServeOptions::default())
|
||||
run(&mut daemon, &mut hub, ®istry, desk.as_mut(), &stopping, &ServeOptions::default())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -143,10 +143,9 @@ fn quick() -> Backoff {
|
|||
Backoff { initial: Duration::from_millis(1), max: Duration::from_millis(2), recheck: Duration::from_secs(3600), search_deadline: Duration::from_secs(30) }
|
||||
}
|
||||
|
||||
/// A daemon serving a mind over real sockets, its full door and its persona door, with the ports the test gave it.
|
||||
/// A daemon serving a mind over a real socket, with the ports the test gave it.
|
||||
struct Harness {
|
||||
endpoint: String,
|
||||
persona_endpoint: String,
|
||||
stopping: Arc<AtomicBool>,
|
||||
serving: Option<JoinHandle<Result<()>>>,
|
||||
embedder: FakeEmbedder,
|
||||
|
|
@ -173,31 +172,19 @@ impl Harness {
|
|||
let mut daemon: Daemon<OwnedRedbMessagePackBackingStore, WorkerSink> = Daemon::new(mind, sink);
|
||||
let mut hub = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
|
||||
let endpoint = format!("rudp://{}", hub.local_addr().unwrap());
|
||||
let mut door = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
|
||||
let persona_endpoint = format!("rudp://{}", door.local_addr().unwrap());
|
||||
let registry = schema_registry().unwrap();
|
||||
let stopping = Arc::new(AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let options = ServeOptions::default();
|
||||
let serving =
|
||||
std::thread::spawn(move || run(&mut daemon, &mut hub, Some(&mut door), ®istry, None, &loop_stopping, &options));
|
||||
Self { endpoint, persona_endpoint, stopping, serving: Some(serving), embedder, index, _root: root }
|
||||
let serving = std::thread::spawn(move || run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &options));
|
||||
Self { endpoint, stopping, serving: Some(serving), embedder, index, _root: root }
|
||||
}
|
||||
|
||||
fn client(&self) -> Client {
|
||||
Self::client_at(&self.endpoint)
|
||||
}
|
||||
|
||||
/// A client of the persona door.
|
||||
fn persona_client(&self) -> Client {
|
||||
Self::client_at(&self.persona_endpoint)
|
||||
}
|
||||
|
||||
fn client_at(endpoint: &str) -> Client {
|
||||
let mut client = CultMesh::create_rudp_client_for_endpoint(
|
||||
"semantic-test".to_string(),
|
||||
CULTNET_OPERATION_CONNECTION_ID,
|
||||
endpoint,
|
||||
&self.endpoint,
|
||||
CultMeshRudpSocketOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
|
@ -285,19 +272,8 @@ fn healthy() -> Harness {
|
|||
/// the members.
|
||||
#[test]
|
||||
fn a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits() {
|
||||
a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(Harness::client);
|
||||
}
|
||||
|
||||
/// The same semantic read asked at the persona door: the search is held while the index works, and its answer leaves by
|
||||
/// the persona door's own hub to the session that asked there.
|
||||
#[test]
|
||||
fn a_semantic_query_at_the_persona_door_is_answered_through_the_persona_door() {
|
||||
a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(Harness::persona_client);
|
||||
}
|
||||
|
||||
fn a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(client_of: fn(&Harness) -> Client) {
|
||||
let harness = healthy();
|
||||
let mut client = client_of(&harness);
|
||||
let mut client = harness.client();
|
||||
until_index(&mut client, "Current", |status| *status == IndexStatus::Current);
|
||||
harness.index.state.lock().unwrap().hits = vec![
|
||||
hit("question", id("question", "Q1"), 0.95),
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ use huginn_mind::{Mind, MindRefusal, MindStore, OwnedRedbMessagePackBackingStore
|
|||
use crate::bodies::{
|
||||
DEFERRED_BUDGET_BYTES, DEFERRED_CHUNK_BYTES, DeferredBodies,
|
||||
};
|
||||
use crate::daemon::{Daemon, Door, Handled, IndexSink, Search, SearchTicket, runtime_id};
|
||||
use crate::daemon::{Daemon, Handled, IndexSink, Search, SearchTicket, runtime_id};
|
||||
use crate::desk_door::{DeskDoor, bind_desk};
|
||||
use huginn_mind::envelope::{OperationFailure, decode_request, encode_failure, encode_response};
|
||||
use huginn_mind::MAX_DEFERRED_BODY_BYTES;
|
||||
|
|
@ -111,10 +111,6 @@ pub struct Options {
|
|||
pub state_root: PathBuf,
|
||||
pub instance: Slug,
|
||||
pub bind: SocketAddr,
|
||||
/// The persona door (`--persona-bind`): a second RUDP listener answering
|
||||
/// only what `HuginnMindRequest::reaches_persona_door` accepts. Absent,
|
||||
/// the daemon has no persona door.
|
||||
pub persona_bind: Option<SocketAddr>,
|
||||
pub qdrant_url: String,
|
||||
/// The GPU hosts: all take embedding at once. One is the plain case.
|
||||
pub ollama_urls: Vec<String>,
|
||||
|
|
@ -138,7 +134,7 @@ pub struct DeskOptions {
|
|||
/// Exactly `--state-root`, `--instance`, `--bind`, `--qdrant-url`,
|
||||
/// `--ollama-url` and `--embedding-model`, each required, each once, except
|
||||
/// `--ollama-url`, which repeats for each GPU host, and the optional
|
||||
/// `--reserve-ollama-url`, which repeats for each CPU host, and the optional `--forge-url` and `--persona-bind` (an ip:port other than `--bind`), each once, and the optional pair `--desk-socket` (an absolute path) and `--desk-peer-uid` (a uid other than 0), both or neither, each once. The URLs are plain
|
||||
/// `--reserve-ollama-url`, which repeats for each CPU host, and the optional `--forge-url`, once, and the optional pair `--desk-socket` (an absolute path) and `--desk-peer-uid` (a uid other than 0), both or neither, each once. The URLs are plain
|
||||
/// `http://`: this build carries no TLS.
|
||||
pub fn parse_options(args: impl Iterator<Item = String>) -> Result<Options> {
|
||||
let mut args = args;
|
||||
|
|
@ -147,7 +143,7 @@ pub fn parse_options(args: impl Iterator<Item = String>) -> Result<Options> {
|
|||
while let Some(name) = args.next() {
|
||||
let name = name.strip_prefix("--").with_context(|| format!("expected --option, got {name:?}"))?;
|
||||
ensure!(
|
||||
matches!(name, "state-root" | "instance" | "bind" | "persona-bind" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url" | "desk-socket" | "desk-peer-uid"),
|
||||
matches!(name, "state-root" | "instance" | "bind" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url" | "desk-socket" | "desk-peer-uid"),
|
||||
"unsupported Huginn option --{name}"
|
||||
);
|
||||
let value = args.next().with_context(|| format!("missing value for --{name}"))?;
|
||||
|
|
@ -171,20 +167,10 @@ pub fn parse_options(args: impl Iterator<Item = String>) -> Result<Options> {
|
|||
};
|
||||
let embedding_model = take("embedding-model")?;
|
||||
ensure!(!embedding_model.is_empty(), "--embedding-model must name a model");
|
||||
let bind: SocketAddr = bind.parse().with_context(|| format!("--bind must be an ip:port, got {bind:?}"))?;
|
||||
let persona_bind = match values.get("persona-bind") {
|
||||
None => None,
|
||||
Some(door) => {
|
||||
let door: SocketAddr = door.parse().with_context(|| format!("--persona-bind must be an ip:port, got {door:?}"))?;
|
||||
ensure!(door != bind, "--persona-bind must not be --bind: the persona door is its own listener");
|
||||
Some(door)
|
||||
}
|
||||
};
|
||||
Ok(Options {
|
||||
state_root,
|
||||
instance: Slug(take("instance")?),
|
||||
bind,
|
||||
persona_bind,
|
||||
bind: bind.parse().with_context(|| format!("--bind must be an ip:port, got {bind:?}"))?,
|
||||
qdrant_url: url("qdrant-url")?,
|
||||
ollama_urls: {
|
||||
ensure!(!ollama_urls.is_empty(), "--ollama-url is required; repeat it for each GPU host");
|
||||
|
|
@ -220,7 +206,6 @@ where
|
|||
{
|
||||
let mind = Mind::open(&options.state_root, &options.instance)?;
|
||||
let hub = bind(options.bind, &runtime_id(&options.instance))?;
|
||||
let persona = options.persona_bind.map(|door| bind(door, &runtime_id(&options.instance))).transpose()?;
|
||||
let desk = options.desk.as_ref().map(|desk| bind_desk(&desk.socket, desk.peer_uid)).transpose()?;
|
||||
let startup_entries = mind.index_entries(None)?;
|
||||
let sink = WorkerSink::spawn(embedder, index, &options.instance, mind.genesis_receipt_id()?, startup_entries, backoff);
|
||||
|
|
@ -229,16 +214,14 @@ where
|
|||
Some(url) => daemon.with_forge(crate::sources::forge::HttpForge::new(url)),
|
||||
None => daemon,
|
||||
};
|
||||
Ok(Started { daemon, hub, persona, registry: schema_registry()?, desk })
|
||||
Ok(Started { daemon, hub, registry: schema_registry()?, desk })
|
||||
}
|
||||
|
||||
/// What `startup` hands the loop: the daemon over the opened mind, the bound RUDP hub, the
|
||||
/// persona door's hub when one was asked for, the catalog both RUDP doors advertise, and the
|
||||
/// desk door when one was asked for.
|
||||
/// catalog the RUDP door advertises, and the desk door when one was asked for.
|
||||
pub struct Started {
|
||||
pub daemon: Daemon<OwnedRedbMessagePackBackingStore, WorkerSink>,
|
||||
pub hub: CultNetRudpServerHub,
|
||||
pub persona: Option<CultNetRudpServerHub>,
|
||||
pub registry: CultNetSchemaRegistry,
|
||||
pub desk: Option<DeskDoor>,
|
||||
}
|
||||
|
|
@ -338,14 +321,12 @@ impl Routed {
|
|||
}
|
||||
|
||||
/// One message in, one message out, or a search to wait for. Nothing here
|
||||
/// reaches a mind except through `Daemon::handle_at`, at the `door` the message
|
||||
/// arrived on, and an envelope that does
|
||||
/// reaches a mind except through `Daemon::handle`, and an envelope that does
|
||||
/// not decode never gets that far. A chunk request is answered from `bodies`
|
||||
/// alone, on the session it came in on; every operation's reply leaves through
|
||||
/// `respond`.
|
||||
pub fn answer<S: MindStore, I: IndexSink<S>>(
|
||||
daemon: &mut Daemon<S, I>,
|
||||
door: Door,
|
||||
registry: &CultNetSchemaRegistry,
|
||||
bodies: &mut DeferredBodies,
|
||||
message: CultNetMessage,
|
||||
|
|
@ -364,7 +345,7 @@ pub fn answer<S: MindStore, I: IndexSink<S>>(
|
|||
CultNetMessage::OperationRequest { message_id, operation, .. } => match decode_request(&message) {
|
||||
Ok((message_id, request)) => {
|
||||
let operation = request.operation();
|
||||
match daemon.handle_at(door, request, now) {
|
||||
match daemon.handle(request, now) {
|
||||
Handled::Answered(response) => respond(&response, &message_id, operation, &runtime_id, bodies, now),
|
||||
Handled::Searching(search) => return Routed::Search { message_id, operation, search },
|
||||
}
|
||||
|
|
@ -502,11 +483,9 @@ fn deliver(
|
|||
deferred
|
||||
}
|
||||
|
||||
/// A semantic query on its way through the index: who asked, at which door,
|
||||
/// what to call the answer, the search to finish, and when the client stops
|
||||
/// being promised one.
|
||||
/// A semantic query on its way through the index: who asked, what to call the
|
||||
/// answer, the search to finish, and when the client stops being promised one.
|
||||
struct Waiting {
|
||||
door: Door,
|
||||
session: CultNetRudpServerSessionContext,
|
||||
message_id: String,
|
||||
operation: &'static str,
|
||||
|
|
@ -515,11 +494,9 @@ struct Waiting {
|
|||
}
|
||||
|
||||
/// Until `stopping`: expire what timed out, resend what was not acknowledged,
|
||||
/// answer every frame waiting on either RUDP door's socket, then answer every
|
||||
/// semantic query the index has finished or that has waited out the index's
|
||||
/// own `search_deadline`. A frame on `hub` is asked at `Door::Full`, one on
|
||||
/// `persona` at `Door::Persona`, and a search's answer leaves by the door it
|
||||
/// came in at. A semantic
|
||||
/// answer every frame waiting on the socket, then answer every semantic query
|
||||
/// the index has finished or that has waited out the index's own
|
||||
/// `search_deadline`. A semantic
|
||||
/// query is never answered inline: `answer` hands back a `Search`, the loop
|
||||
/// holds it beside its session and goes on serving, and the embedder and the
|
||||
/// vector store are the worker's to wait on. A hostile datagram and a departed
|
||||
|
|
@ -528,18 +505,51 @@ struct Waiting {
|
|||
pub fn run<S: MindStore, I: IndexSink<S>>(
|
||||
daemon: &mut Daemon<S, I>,
|
||||
hub: &mut CultNetRudpServerHub,
|
||||
mut persona: Option<&mut CultNetRudpServerHub>,
|
||||
registry: &CultNetSchemaRegistry,
|
||||
mut desk: Option<&mut DeskDoor>,
|
||||
stopping: &AtomicBool,
|
||||
options: &ServeOptions,
|
||||
) -> Result<()> {
|
||||
let timeout_ms = options.session_timeout.as_millis() as u64;
|
||||
let mut bodies = DeferredBodies::new(DEFERRED_BUDGET_BYTES, options.deferred_ttl);
|
||||
let mut waiting: BTreeMap<SearchTicket, Waiting> = BTreeMap::new();
|
||||
while !stopping.load(Ordering::Relaxed) {
|
||||
let mut served = serve_frames(daemon, hub, Door::Full, registry, &mut bodies, &mut waiting, options);
|
||||
if let Some(door) = persona.as_deref_mut() {
|
||||
served += serve_frames(daemon, door, Door::Persona, registry, &mut bodies, &mut waiting, options);
|
||||
hub.remove_timed_out_sessions(timeout_ms);
|
||||
if let Err(error) = hub.poll_resends() {
|
||||
eprintln!("huginn: resending to a peer failed: {error:#}");
|
||||
}
|
||||
let mut served = 0_u32;
|
||||
loop {
|
||||
let event = match hub.receive_event_once() {
|
||||
Ok(Some(event)) => event,
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
eprintln!("huginn: a datagram was not readable and was discarded: {error:#}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let CultNetRudpServerEvent::Frame { session, frame } = event else {
|
||||
continue;
|
||||
};
|
||||
if frame.channel_id != "schema" {
|
||||
continue;
|
||||
}
|
||||
let message = match decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)
|
||||
{
|
||||
Ok(message) => message,
|
||||
Err(error) => {
|
||||
eprintln!("huginn: a frame was not a CultNet message and was discarded: {error:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match answer(daemon, registry, &mut bodies, message, Utc::now()) {
|
||||
Routed::Reply(reply) => send(hub, &session, &reply),
|
||||
Routed::Search { message_id, operation, search } => {
|
||||
let until = Instant::now() + daemon.search_deadline();
|
||||
waiting.insert(search.ticket, Waiting { session, message_id, operation, search, until });
|
||||
}
|
||||
}
|
||||
served += 1;
|
||||
}
|
||||
let desk_served = desk.as_deref_mut().map_or(0, |door| door.serve_ready(daemon, Utc::now()));
|
||||
let finished = collect_searches(daemon, &waiting);
|
||||
|
|
@ -548,14 +558,7 @@ pub fn run<S: MindStore, I: IndexSink<S>>(
|
|||
let Some(asked) = waiting.remove(&ticket) else { continue };
|
||||
let response = daemon.finish(asked.search, found);
|
||||
let reply = respond(&response, &asked.message_id, asked.operation, &daemon.runtime_id(), &mut bodies, Utc::now());
|
||||
let out = match asked.door {
|
||||
Door::Full => &mut *hub,
|
||||
Door::Persona => match persona.as_deref_mut() {
|
||||
Some(door) => door,
|
||||
None => continue,
|
||||
},
|
||||
};
|
||||
send(out, &asked.session, &reply);
|
||||
send(hub, &asked.session, &reply);
|
||||
}
|
||||
if served == 0 && desk_served == 0 && !answered {
|
||||
std::thread::sleep(options.idle_sleep);
|
||||
|
|
@ -564,57 +567,6 @@ pub fn run<S: MindStore, I: IndexSink<S>>(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// One pass over one RUDP door: expire its idle sessions, resend what it has
|
||||
/// unacknowledged, and answer every frame waiting on its socket as asked at
|
||||
/// `door`. Returns how many frames it answered or queued.
|
||||
fn serve_frames<S: MindStore, I: IndexSink<S>>(
|
||||
daemon: &mut Daemon<S, I>,
|
||||
hub: &mut CultNetRudpServerHub,
|
||||
door: Door,
|
||||
registry: &CultNetSchemaRegistry,
|
||||
bodies: &mut DeferredBodies,
|
||||
waiting: &mut BTreeMap<SearchTicket, Waiting>,
|
||||
options: &ServeOptions,
|
||||
) -> u32 {
|
||||
hub.remove_timed_out_sessions(options.session_timeout.as_millis() as u64);
|
||||
if let Err(error) = hub.poll_resends() {
|
||||
eprintln!("huginn: resending to a peer failed: {error:#}");
|
||||
}
|
||||
let mut served = 0_u32;
|
||||
loop {
|
||||
let event = match hub.receive_event_once() {
|
||||
Ok(Some(event)) => event,
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
eprintln!("huginn: a datagram was not readable and was discarded: {error:#}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let CultNetRudpServerEvent::Frame { session, frame } = event else {
|
||||
continue;
|
||||
};
|
||||
if frame.channel_id != "schema" {
|
||||
continue;
|
||||
}
|
||||
let message = match decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) {
|
||||
Ok(message) => message,
|
||||
Err(error) => {
|
||||
eprintln!("huginn: a frame was not a CultNet message and was discarded: {error:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match answer(daemon, door, registry, bodies, message, Utc::now()) {
|
||||
Routed::Reply(reply) => send(hub, &session, &reply),
|
||||
Routed::Search { message_id, operation, search } => {
|
||||
let until = Instant::now() + daemon.search_deadline();
|
||||
waiting.insert(search.ticket, Waiting { door, session, message_id, operation, search, until });
|
||||
}
|
||||
}
|
||||
served += 1;
|
||||
}
|
||||
served
|
||||
}
|
||||
|
||||
/// What the index has finished, then what has waited too long: the latter as
|
||||
/// an `Unavailable` detail, and abandoned, so the index does not start a search
|
||||
/// nobody is waiting for. A search that finishes after its deadline finds
|
||||
|
|
@ -728,14 +680,14 @@ mod tests {
|
|||
("m-5b", request("m-5b", MIND_SERVICE_ID, "Admit", MIND_REQUEST_SCHEMA, admit), "operation-mismatch"),
|
||||
];
|
||||
for (id, message, code) in cases {
|
||||
let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), message, now()).reply();
|
||||
let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), message, now()).reply();
|
||||
assert_eq!(rejected(&reply).0, id, "the client's own correlation key is echoed");
|
||||
assert_eq!(rejected(&reply).1, code);
|
||||
}
|
||||
// The sixth code, `not-an-operation-request`, is the codec's and is
|
||||
// pinned in `huginn_mind::envelope::tests`: `answer` never produces it, because a
|
||||
// message of another family is answered with `Error` instead.
|
||||
let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), CultNetMessage::Error { error: "hello".into(), code: None, details: None }, now()).reply();
|
||||
let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), CultNetMessage::Error { error: "hello".into(), code: None, details: None }, now()).reply();
|
||||
let CultNetMessage::Error { error, .. } = &reply else { panic!("expected an error, got {reply:?}") };
|
||||
assert!(
|
||||
!error.is_empty() && error.contains("cultnet.operation_request.v0") && error.contains("cultnet.schema_catalog_request.v0"),
|
||||
|
|
@ -747,7 +699,7 @@ mod tests {
|
|||
// A mind's refusal is an answer on the response schema, not a failure
|
||||
// of the envelope: the client decodes it as the typed refusal it is.
|
||||
let read = HuginnMindRequest::Query { instance: slug(OTHER), selection: Selection::default(), semantic: None };
|
||||
let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), encode_request("m-r", &read, None).unwrap(), now()).reply();
|
||||
let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), encode_request("m-r", &read, None).unwrap(), now()).reply();
|
||||
let CultNetMessage::OperationResponse { status, payload_schema, .. } = &reply else {
|
||||
panic!("expected an operation response, got {reply:?}");
|
||||
};
|
||||
|
|
@ -765,7 +717,7 @@ mod tests {
|
|||
schema_ids: None,
|
||||
kinds: None,
|
||||
};
|
||||
let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), catalog, now()).reply();
|
||||
let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), catalog, now()).reply();
|
||||
let CultNetMessage::SchemaCatalogResponse { message_id, schemas } = reply else {
|
||||
panic!("expected a catalog response");
|
||||
};
|
||||
|
|
@ -833,7 +785,7 @@ mod tests {
|
|||
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let serving = std::thread::spawn(move || {
|
||||
let result = run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default());
|
||||
let result = run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default());
|
||||
(result, daemon)
|
||||
});
|
||||
|
||||
|
|
@ -922,43 +874,6 @@ mod tests {
|
|||
panic!("{name} never connected");
|
||||
}
|
||||
|
||||
/// Over loopback, the persona door's listener refuses an admission by name and answers a
|
||||
/// read, and the full door's listener admits the same batch: only that admission lands.
|
||||
#[test]
|
||||
fn the_persona_listener_refuses_an_admission_the_full_listener_takes() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap();
|
||||
let mut hub = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
|
||||
let mut door = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap();
|
||||
let full = format!("rudp://{}", hub.local_addr().unwrap());
|
||||
let persona = format!("rudp://{}", door.local_addr().unwrap());
|
||||
let registry = schema_registry().unwrap();
|
||||
let stopping = Arc::new(AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let serving = std::thread::spawn(move || {
|
||||
let result = run(&mut daemon, &mut hub, Some(&mut door), ®istry, None, &loop_stopping, &ServeOptions::default());
|
||||
(result, daemon)
|
||||
});
|
||||
|
||||
let admit = HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)]));
|
||||
let mut her = connect(&persona, "persona");
|
||||
assert_eq!(ask(&mut her, "p-admit", &admit), HuginnMindResponse::Refused(MindRefusal::NotThisDoor));
|
||||
let HuginnMindResponse::Whoami(status) = ask(&mut her, "p-whoami", &HuginnMindRequest::Whoami) else {
|
||||
panic!("the persona door answers whoami")
|
||||
};
|
||||
assert_eq!(status.documents, 0, "the refused admission wrote nothing");
|
||||
let mut self_faculty = connect(&full, "full");
|
||||
assert!(matches!(
|
||||
ask(&mut self_faculty, "f-admit", &admit),
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. })
|
||||
));
|
||||
|
||||
stopping.store(true, Ordering::Relaxed);
|
||||
let (result, mut daemon) = serving.join().unwrap();
|
||||
result.unwrap();
|
||||
assert_eq!(documents(&mut daemon), 1, "only the full door's admission landed");
|
||||
}
|
||||
|
||||
/// One client admits batches that close, withdraw and re-open records while three others read
|
||||
/// the same mind: fresh queries, cursor walks across commits, a hop and whoami. The loop is
|
||||
/// serial, so every answer is one snapshot's; at quiesce each answer must equal what a fresh
|
||||
|
|
@ -977,7 +892,7 @@ mod tests {
|
|||
let stopping = Arc::new(AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let serving = std::thread::spawn(move || {
|
||||
let result = run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default());
|
||||
let result = run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default());
|
||||
(result, daemon)
|
||||
});
|
||||
|
||||
|
|
@ -1142,7 +1057,7 @@ mod tests {
|
|||
at: DateTime<Utc>,
|
||||
) -> CultMeshCdnArtifactManifest {
|
||||
let registry = schema_registry().unwrap();
|
||||
deferred_manifest(&answer(daemon, Door::Full, ®istry, bodies, encode_request(message_id, read, None).unwrap(), at).reply())
|
||||
deferred_manifest(&answer(daemon, ®istry, bodies, encode_request(message_id, read, None).unwrap(), at).reply())
|
||||
}
|
||||
|
||||
/// Whether the first chunk of a manifest is still served at an injected time.
|
||||
|
|
@ -1153,7 +1068,7 @@ mod tests {
|
|||
at: DateTime<Utc>,
|
||||
) -> bool {
|
||||
let registry = schema_registry().unwrap();
|
||||
found(&answer(daemon, Door::Full, ®istry, bodies, chunk_request(manifest, 0), at).reply())
|
||||
found(&answer(daemon, ®istry, bodies, chunk_request(manifest, 0), at).reply())
|
||||
}
|
||||
|
||||
/// An answer larger than one send can carry is deferred to the body plane
|
||||
|
|
@ -1218,7 +1133,7 @@ mod tests {
|
|||
let stopping = Arc::new(AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let serving = std::thread::spawn(move || {
|
||||
let result = run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default());
|
||||
let result = run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default());
|
||||
(result, daemon)
|
||||
});
|
||||
|
||||
|
|
@ -1466,7 +1381,7 @@ mod tests {
|
|||
let manifest = ask_deferred(&mut daemon, &mut bodies, "m-v", &read, t0);
|
||||
assert!(manifest.chunks.len() >= 2, "the fixture needs a second chunk to serve");
|
||||
let mut chunk = |index: usize, at: i64| {
|
||||
answer(&mut daemon, Door::Full, ®istry, &mut bodies, chunk_request(&manifest, index), after(at)).reply()
|
||||
answer(&mut daemon, ®istry, &mut bodies, chunk_request(&manifest, index), after(at)).reply()
|
||||
};
|
||||
assert!(found(&chunk(0, 59)), "inside the TTL");
|
||||
assert!(found(&chunk(1, 118)), "serving a chunk slid the expiry past the first TTL");
|
||||
|
|
@ -1479,7 +1394,7 @@ mod tests {
|
|||
let again = ask_deferred(&mut daemon, &mut bodies, "m-v2", &read, after(179));
|
||||
assert_eq!(again.content_hash, manifest.content_hash, "the same answer is the same body");
|
||||
let bytes = fetch_content(&again, MAX_DEFERRED_BODY_BYTES, |request| {
|
||||
Ok(answer(&mut daemon, Door::Full, ®istry, &mut bodies, request, after(180)).reply())
|
||||
Ok(answer(&mut daemon, ®istry, &mut bodies, request, after(180)).reply())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(bytes, expected);
|
||||
|
|
@ -1579,7 +1494,7 @@ mod tests {
|
|||
("record_key", chunk("m", "abc", &huge)),
|
||||
];
|
||||
for (case, message) in refused {
|
||||
let reply = answer(&mut daemon, Door::Full, ®istry, &mut bodies, message, now()).reply();
|
||||
let reply = answer(&mut daemon, ®istry, &mut bodies, message, now()).reply();
|
||||
let CultNetMessage::Error { error, .. } = &reply else {
|
||||
panic!("{case}: expected a transport error, got {reply:?}");
|
||||
};
|
||||
|
|
@ -1588,9 +1503,9 @@ mod tests {
|
|||
}
|
||||
assert_eq!(documents(&mut daemon), 0);
|
||||
|
||||
let reply = answer(&mut daemon, Door::Full, ®istry, &mut bodies, whoami(&at, MIND_SERVICE_ID, "whoami", MIND_REQUEST_SCHEMA), now()).reply();
|
||||
let reply = answer(&mut daemon, ®istry, &mut bodies, whoami(&at, MIND_SERVICE_ID, "whoami", MIND_REQUEST_SCHEMA), now()).reply();
|
||||
assert_eq!(decode_response(&reply).unwrap().0, at, "a field of exactly the bound is served");
|
||||
let reply = answer(&mut daemon, Door::Full, ®istry, &mut bodies, chunk(&at, &at, &at), now()).reply();
|
||||
let reply = answer(&mut daemon, ®istry, &mut bodies, chunk(&at, &at, &at), now()).reply();
|
||||
assert!(!found(&reply), "an unknown chunk is answered found: false, not refused at the door");
|
||||
}
|
||||
|
||||
|
|
@ -1650,7 +1565,6 @@ mod tests {
|
|||
state_root: root.path().to_path_buf(),
|
||||
instance: slug(INSTANCE),
|
||||
bind: port,
|
||||
persona_bind: Some("127.0.0.1:0".parse().unwrap()),
|
||||
qdrant_url: "http://127.0.0.1:1".into(),
|
||||
ollama_urls: vec!["http://127.0.0.1:1".into()],
|
||||
reserve_ollama_urls: Vec::new(),
|
||||
|
|
@ -1674,8 +1588,6 @@ mod tests {
|
|||
drop(occupied);
|
||||
let started = started(&options).expect("both gates open");
|
||||
assert_eq!(started.hub.local_addr().unwrap(), port);
|
||||
let door = started.persona.as_ref().expect("the persona door was asked for and bound");
|
||||
assert_ne!(door.local_addr().unwrap(), port, "the persona door is its own listener");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1692,7 +1604,6 @@ mod tests {
|
|||
state_root: PathBuf::from(root),
|
||||
instance: slug("yggdrasil"),
|
||||
bind: "127.0.0.1:17872".parse().unwrap(),
|
||||
persona_bind: None,
|
||||
qdrant_url: "http://127.0.0.1:6333".into(),
|
||||
ollama_urls: vec!["http://10.77.0.4:11434".into()],
|
||||
reserve_ollama_urls: Vec::new(),
|
||||
|
|
@ -1736,11 +1647,5 @@ mod tests {
|
|||
assert_eq!(parse_options(args(&forged)).unwrap().forge_url.as_deref(), Some("http://127.0.0.1:3310"));
|
||||
assert!(parse_options(args(&[good.to_vec(), vec!["--forge-url", "https://127.0.0.1:3310"]].concat())).is_err());
|
||||
assert!(parse_options(args(&[forged.clone(), vec!["--forge-url", "http://127.0.0.1:3311"]].concat())).is_err());
|
||||
// The persona door is optional, once, an ip:port, and never the full door's.
|
||||
let door = [good.to_vec(), vec!["--persona-bind", "127.0.0.1:17862"]].concat();
|
||||
assert_eq!(parse_options(args(&door)).unwrap().persona_bind, Some("127.0.0.1:17862".parse().unwrap()));
|
||||
assert!(parse_options(args(&[door.clone(), vec!["--persona-bind", "127.0.0.1:17863"]].concat())).is_err());
|
||||
assert!(parse_options(args(&[good.to_vec(), vec!["--persona-bind", "not-an-address"]].concat())).is_err());
|
||||
assert!(parse_options(args(&[good.to_vec(), vec!["--persona-bind", "127.0.0.1:17872"]].concat())).is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -134,39 +134,6 @@ impl std::fmt::Display for ChatReport {
|
|||
}
|
||||
}
|
||||
|
||||
/// One line of a chat run's journal, typed so the job routes by what happened and not by how the line reads.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Entry {
|
||||
/// A room's report; a failed one is an alarm.
|
||||
Report(ChatReport),
|
||||
Refused(RefusedRoom),
|
||||
Scrubbed(ScrubHit),
|
||||
/// A failure outside any one room's report: retiring rooms.
|
||||
Trouble(String),
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// The operator must see this on stderr: a failure, a refusal, a scrub hit.
|
||||
pub fn is_alarm(&self) -> bool {
|
||||
match self {
|
||||
Self::Report(report) => report.failure.is_some(),
|
||||
Self::Refused(_) | Self::Scrubbed(_) | Self::Trouble(_) => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Entry {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Report(report) => report.fmt(formatter),
|
||||
Self::Refused(RefusedRoom { room_id, reason, event_id: None }) => write!(formatter, "refused: {room_id} {reason}"),
|
||||
Self::Refused(RefusedRoom { room_id, reason, event_id: Some(event) }) => write!(formatter, "refused: {room_id} {reason} [{event}]"),
|
||||
Self::Scrubbed(hit) => write!(formatter, "scrubbed: {} {} {}", hit.room_id, hit.event_id, hit.kind),
|
||||
Self::Trouble(why) => write!(formatter, "huginn-sources: {why}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A joined room the scope refused, whole, and why; `event_id` when an event did it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RefusedRoom {
|
||||
|
|
@ -595,7 +562,7 @@ pub fn refresh_chat<E: Embedder, S: SourceIndex, H: RoomHistory>(
|
|||
index: &mut S,
|
||||
history: &mut H,
|
||||
estate: &Estate,
|
||||
journal: &mut dyn FnMut(Entry),
|
||||
journal: &mut dyn FnMut(String),
|
||||
) -> Result<ChatRefreshed> {
|
||||
let DescribedSources::Labelled { meta, .. } = index.describe_sources(INDEX_CALL_TIMEOUT).context("describing the source collection")? else {
|
||||
bail!("the source collection is absent or not Huginn's; the forge refresh creates it and chat never does");
|
||||
|
|
@ -622,14 +589,13 @@ pub fn refresh_chat<E: Embedder, S: SourceIndex, H: RoomHistory>(
|
|||
Ok(Err(reason)) => {
|
||||
// Not kept, so the retirement below purges whatever it held.
|
||||
keep.remove(room_id);
|
||||
let refused = RefusedRoom { room_id: room_id.clone(), reason, event_id: None };
|
||||
journal(Entry::Refused(refused.clone()));
|
||||
out.refused.push(refused);
|
||||
journal(format!("refused: {room_id} {reason}"));
|
||||
out.refused.push(RefusedRoom { room_id: room_id.clone(), reason, event_id: None });
|
||||
}
|
||||
// An error is not a reclassification: the room keeps its points and cursor, and the report says why.
|
||||
Err(error) => {
|
||||
let report = ChatReport::failed(room_id, None, &error.context("reading the room's facts"));
|
||||
journal(Entry::Report(report.clone()));
|
||||
journal(report.to_string());
|
||||
out.failed.push(room_id.clone());
|
||||
out.rooms.push(report);
|
||||
}
|
||||
|
|
@ -638,35 +604,35 @@ pub fn refresh_chat<E: Embedder, S: SourceIndex, H: RoomHistory>(
|
|||
match retire_chat(index, &keep) {
|
||||
Ok(done) => {
|
||||
for (room, why) in done.failed {
|
||||
journal(Entry::Trouble(format!("retiring {room} failed, the others go on: {why}")));
|
||||
journal(format!("huginn-sources: retiring {room} failed, the others go on: {why}"));
|
||||
out.failed.push(room);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
journal(Entry::Trouble(format!("retiring rooms failed: {error:#}")));
|
||||
journal(format!("huginn-sources: retiring rooms failed: {error:#}"));
|
||||
out.failed.push("retire".to_owned());
|
||||
}
|
||||
}
|
||||
for facts in admitted {
|
||||
match ingest_room(embedder, index, history, identity.dimensions, &facts, &mut out) {
|
||||
Ok(Outcome::Done(report)) => {
|
||||
journal(Entry::Report(report.clone()));
|
||||
journal(report.to_string());
|
||||
out.rooms.push(report);
|
||||
}
|
||||
Ok(Outcome::Refused(refused)) => {
|
||||
journal(Entry::Refused(refused.clone()));
|
||||
journal(format!("refused: {} {} [{}]", refused.room_id, refused.reason, refused.event_id.as_deref().unwrap_or("")));
|
||||
out.refused.push(refused);
|
||||
}
|
||||
Err(error) => {
|
||||
let report = ChatReport::failed(&facts.room_id, facts.alias.clone(), &error);
|
||||
journal(Entry::Report(report.clone()));
|
||||
journal(report.to_string());
|
||||
out.failed.push(facts.room_id.clone());
|
||||
out.rooms.push(report);
|
||||
}
|
||||
}
|
||||
}
|
||||
for hit in &out.scrubbed {
|
||||
journal(Entry::Scrubbed(hit.clone()));
|
||||
journal(format!("scrubbed: {} {} {}", hit.room_id, hit.event_id, hit.kind));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -141,7 +141,7 @@ impl Rig {
|
|||
|
||||
fn run(&mut self, history: &mut FakeHistory) -> (Result<ChatRefreshed>, Vec<String>) {
|
||||
let mut journal = Vec::new();
|
||||
let out = refresh_chat(&mut self.embedder, &mut self.index, history, &self.estate, &mut |line| journal.push(line.to_string()));
|
||||
let out = refresh_chat(&mut self.embedder, &mut self.index, history, &self.estate, &mut |line| journal.push(line));
|
||||
(out, journal)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -180,7 +180,7 @@ impl HttpForge {
|
|||
capped.push(repo.clone());
|
||||
}
|
||||
}
|
||||
events.sort_by_key(|event| std::cmp::Reverse(event.id));
|
||||
events.sort_by(|a, b| b.id.cmp(&a.id));
|
||||
// The cursor never moves backwards: a read that saw nothing new keeps the one it was given.
|
||||
head = head.max(after.unwrap_or(0));
|
||||
let (mut open_prs, mut unseen) = (Vec::new(), dark.clone());
|
||||
|
|
@ -251,7 +251,7 @@ fn redirect_target(base: &str, location: &str) -> Option<OrgRepo> {
|
|||
let at = segments.windows(3).position(|window| window == ["api", "v1", "repos"])?;
|
||||
let plain = |segment: &&str| !segment.is_empty() && *segment != "." && *segment != ".." && segment.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
|
||||
let [owner, name, "activities", "feeds"] = segments[at + 3..] else { return None };
|
||||
if !segments[..at].iter().all(plain) || !plain(&owner) || !plain(&name) {
|
||||
if !segments[..at].iter().all(|segment| plain(segment)) || !plain(&owner) || !plain(&name) {
|
||||
return None;
|
||||
}
|
||||
let repo = OrgRepo(format!("{owner}/{name}"));
|
||||
|
|
@ -322,7 +322,6 @@ mod tests {
|
|||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
use crate::sources::test_http::{Reply, forge_of};
|
||||
|
||||
/// Only public, live, original, non-empty repos are the corpus; a repo the
|
||||
/// forge does not say is safe is not indexed.
|
||||
|
|
@ -401,6 +400,60 @@ mod tests {
|
|||
assert!(HttpForge::new(&unstated).catalog().unwrap().shortfall.unwrap().contains("X-Total-Count"));
|
||||
}
|
||||
|
||||
/// What a fake forge answers: a status, the `Location` header when there is one, and a body.
|
||||
struct Reply {
|
||||
status: u16,
|
||||
location: Option<String>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
impl From<String> for Reply {
|
||||
fn from(body: String) -> Self {
|
||||
Self { status: 200, location: None, body }
|
||||
}
|
||||
}
|
||||
|
||||
impl Reply {
|
||||
/// What the live forge answers an anonymous reader for a private repo.
|
||||
fn not_found() -> Self {
|
||||
Self { status: 404, location: None, body: json!({ "message": "The target couldn't be found." }).to_string() }
|
||||
}
|
||||
|
||||
/// What the live forge answers for a renamed repo: a 301 to its public address, `/forge` prefix and all.
|
||||
fn moved_to(location: &str) -> Self {
|
||||
Self { status: 301, location: Some(location.to_owned()), body: String::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers each request by its path from `routes`; a path it has no answer for is held open and never answered, as a hung forge
|
||||
/// does. Every path asked is recorded in order.
|
||||
fn forge_of<R: Into<Reply>>(routes: impl Fn(&str) -> Option<R> + Send + 'static) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let record = std::sync::Arc::clone(&asked);
|
||||
std::thread::spawn(move || {
|
||||
let mut held = Vec::new();
|
||||
for stream in listener.incoming() {
|
||||
let mut stream = stream.unwrap();
|
||||
let mut buffer = [0_u8; 4096];
|
||||
let read = stream.read(&mut buffer).unwrap();
|
||||
let request = String::from_utf8_lossy(&buffer[..read]).into_owned();
|
||||
let path = request.split_whitespace().nth(1).unwrap_or_default().to_owned();
|
||||
record.lock().unwrap().push(path.clone());
|
||||
match routes(&path).map(Into::into) {
|
||||
Some(Reply { status, location, body }) => {
|
||||
let location = location.map(|location| format!("location: {location}\r\n")).unwrap_or_default();
|
||||
write!(stream, "HTTP/1.1 {status} X\r\ncontent-type: application/json\r\n{location}content-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()).unwrap();
|
||||
}
|
||||
None => held.push(stream),
|
||||
}
|
||||
}
|
||||
});
|
||||
(base, asked)
|
||||
}
|
||||
|
||||
const FEED_SAMPLE: &str = include_str!("../../tests/fixtures/feed.json");
|
||||
|
||||
const NOW: &str = "2026-11-03T12:00:00Z";
|
||||
|
|
@ -470,7 +523,7 @@ mod tests {
|
|||
assert!(read.open_prs.is_empty() && read.unseen.is_empty() && read.capped.is_empty() && read.moved.is_empty(), "a cursor asks for neither list");
|
||||
let wire = serde_json::to_string(&read).unwrap();
|
||||
assert!(!wire.contains("CANARY") && !wire.contains("obey") && !wire.contains("Message"), "no forge text leaves the read: {wire}");
|
||||
let asked = asked.paths();
|
||||
let asked = asked.lock().unwrap().clone();
|
||||
assert!(!asked.is_empty() && asked.iter().all(|path| names.iter().any(|name| path.starts_with(&format!("/api/v1/repos/{name}/activities/feeds")))), "{asked:?}");
|
||||
}
|
||||
|
||||
|
|
@ -502,13 +555,13 @@ mod tests {
|
|||
let far = HttpForge::new(&base).activity(&wanted, &me, Some(5), now).unwrap();
|
||||
assert!(far.capped == repos(&["GameCult/Huginn"]), "stopped at the cap with the cursor not reached");
|
||||
assert_eq!((far.events.len(), far.head), (200, 2500));
|
||||
assert_eq!(asked.paths().len(), 4, "four pages and no more");
|
||||
assert_eq!(asked.lock().unwrap().len(), 4, "four pages and no more");
|
||||
|
||||
let (base, asked) = forge_of(feed("nibu"));
|
||||
let near = HttpForge::new(&base).activity(&wanted, &me, Some(2300), now).unwrap();
|
||||
assert!(near.capped.is_empty());
|
||||
assert_eq!((near.events.len(), near.head), (20, 2500), "ids above the cursor only");
|
||||
assert_eq!(asked.paths().len(), 1);
|
||||
assert_eq!(asked.lock().unwrap().len(), 1);
|
||||
|
||||
let (base, _) = forge_of(feed("eureka"));
|
||||
let hers = HttpForge::new(&base).activity(&wanted, &me, Some(2300), now).unwrap();
|
||||
|
|
@ -530,7 +583,7 @@ mod tests {
|
|||
let read = HttpForge::new(&base).activity(&repos(&["GameCult/Ratatoskr"]), &me(), None, at(NOW)).unwrap();
|
||||
assert_eq!(read.events.iter().map(|event| event.id).collect::<Vec<_>>(), [300]);
|
||||
assert!(read.capped.is_empty());
|
||||
assert!(asked.paths().iter().all(|path| !path.contains("/orgs/GameCult/activities")));
|
||||
assert!(asked.lock().unwrap().iter().all(|path| !path.contains("/orgs/GameCult/activities")));
|
||||
}
|
||||
|
||||
/// A first read keeps what is inside 72 hours and nothing older, and its cursor is the newest id it saw, an entry past the window
|
||||
|
|
@ -566,13 +619,13 @@ mod tests {
|
|||
let (base, asked) = forge_of(move |path| if is_feed(path) { repo_feed(&entries, path) } else { Some("[]".into()) });
|
||||
let read = HttpForge::new(&base).activity(&wanted, &me(), None, at(NOW)).unwrap();
|
||||
assert_eq!((read.events.len(), read.capped.len()), (53, 0));
|
||||
assert_eq!(asked.paths().iter().filter(|path| is_feed(path)).count(), 2, "page 2 was asked, page 3 was not");
|
||||
assert_eq!(asked.lock().unwrap().iter().filter(|path| is_feed(path)).count(), 2, "page 2 was asked, page 3 was not");
|
||||
|
||||
let entries: Vec<Value> = (0..400).map(|n| push_at(5000 - n, "GameCult/Huginn", "Nibu", 5)).collect();
|
||||
let (base, asked) = forge_of(move |path| if is_feed(path) { repo_feed(&entries, path) } else { Some("[]".into()) });
|
||||
let read = HttpForge::new(&base).activity(&wanted, &me(), None, at(NOW)).unwrap();
|
||||
assert_eq!((read.events.len(), read.capped), (REPO_FEED_PAGES * PAGE, repos(&["GameCult/Huginn"])), "200 read and the rest disclosed");
|
||||
assert_eq!(asked.paths().iter().filter(|path| is_feed(path)).count(), REPO_FEED_PAGES);
|
||||
assert_eq!(asked.lock().unwrap().iter().filter(|path| is_feed(path)).count(), REPO_FEED_PAGES);
|
||||
}
|
||||
|
||||
/// With no cursor the read also lists the open PRs in her repos and hers anywhere, and the repos the forge's listing does not hold.
|
||||
|
|
@ -583,9 +636,9 @@ mod tests {
|
|||
let mut first_page: Vec<Value> = (0..PAGE as u32).map(|n| pr(n + 100, "kiko", "GameCult/Elsewhere")).collect();
|
||||
first_page[0] = pr(8, "nibu", "GameCult/Ratatoskr");
|
||||
first_page[1] = pr(42, "Eureka", "GameCult/Eureka");
|
||||
let search = [Value::Array(first_page).to_string(), Value::Array(vec![pr(9, "void", "GameCult/Huginn")]).to_string()];
|
||||
let search = vec![Value::Array(first_page).to_string(), Value::Array(vec![pr(9, "void", "GameCult/Huginn")]).to_string()];
|
||||
let names: Vec<Value> = (0..61).map(|n| json!({ "full_name": match n { 0 => "GameCult/ratatoskr".to_owned(), 1 => "GameCult/Huginn".to_owned(), n => format!("GameCult/r{n}") } })).collect();
|
||||
let listing = [Value::Array(names[..PAGE].to_vec()).to_string(), Value::Array(names[PAGE..].to_vec()).to_string()];
|
||||
let listing = vec![Value::Array(names[..PAGE].to_vec()).to_string(), Value::Array(names[PAGE..].to_vec()).to_string()];
|
||||
let sample = sample();
|
||||
let (base, asked) = forge_of(move |path| {
|
||||
if is_feed(path) && path.contains("/GameCult/Ghost/") {
|
||||
|
|
@ -607,14 +660,14 @@ mod tests {
|
|||
assert_eq!(first.unseen, repos(&["GameCult/Ghost"]), "r60 is on page 2 of the listing");
|
||||
let window = at("2026-10-31T12:00:00Z").timestamp_millis() as u64;
|
||||
assert!(!first.events.is_empty() && first.events.iter().all(|event| event.at >= window), "inside 72 h: {:?}", first.events);
|
||||
let paths = asked.paths();
|
||||
let paths = asked.lock().unwrap().clone();
|
||||
let count = |what: &str| paths.iter().filter(|path| path.contains(what)).count();
|
||||
assert_eq!((count("/issues/search"), count("/orgs/GameCult/repos")), (2, 2), "a short page ends each: {paths:?}");
|
||||
|
||||
// A cursor asks for neither list.
|
||||
let before = paths.len();
|
||||
HttpForge::new(&base).activity(&wanted, &me(), Some(1), at(NOW)).unwrap();
|
||||
let after = asked.paths();
|
||||
let after = asked.lock().unwrap().clone();
|
||||
assert!(after[before..].iter().all(|path| is_feed(path)), "only the feeds: {after:?}");
|
||||
}
|
||||
|
||||
|
|
@ -626,7 +679,7 @@ mod tests {
|
|||
let full = |from: u32| Value::Array((0..PAGE as u32).map(|n| pr(from + n, "GameCult/Elsewhere")).collect()).to_string();
|
||||
let mut third: Vec<Value> = (0..PAGE as u32).map(|n| pr(300 + n, "GameCult/Elsewhere")).collect();
|
||||
third[PAGE - 1] = pr(7, "GameCult/Huginn");
|
||||
let search = [full(100), full(200), Value::Array(third).to_string(), "[]".to_owned()];
|
||||
let search = vec![full(100), full(200), Value::Array(third).to_string(), "[]".to_owned()];
|
||||
let (base, asked) = forge_of(move |path| {
|
||||
if is_feed(path) {
|
||||
Some("[]".to_owned())
|
||||
|
|
@ -640,12 +693,12 @@ mod tests {
|
|||
});
|
||||
let read = HttpForge::new(&base).activity(&repos(&["GameCult/Huginn"]), &me(), None, at(NOW)).unwrap();
|
||||
assert_eq!(read.open_prs.iter().map(|pr| pr.number).collect::<Vec<_>>(), [7], "page 3 was read");
|
||||
assert_eq!(asked.paths().iter().filter(|path| path.contains("/issues/search")).count(), 4, "to the short page");
|
||||
assert_eq!(asked.lock().unwrap().iter().filter(|path| path.contains("/issues/search")).count(), 4, "to the short page");
|
||||
}
|
||||
|
||||
/// The forge as it answers an anonymous reader: public repos give their feed (`[]` when quiet), a private repo answers 404, a
|
||||
/// renamed repo answers 301 to a path under `/forge` that this loopback does not serve (asking it gives 404).
|
||||
fn live_forge(entries: Vec<Value>, public: &'static [&'static str], listing: String) -> (String, crate::sources::test_http::Asked) {
|
||||
fn live_forge(entries: Vec<Value>, public: &'static [&'static str], listing: String) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
|
||||
forge_of(move |path| {
|
||||
if path.starts_with("/forge/") {
|
||||
return Some(Reply::not_found());
|
||||
|
|
@ -680,7 +733,7 @@ mod tests {
|
|||
assert_eq!(first.unseen, repos(&["GameCult/gamecult-ops", "GameCult/cinny"]));
|
||||
assert_eq!(first.moved, [RepoMoved { from: "GameCult/cinny".into(), to: "GameCult/Ratatoskr".into() }]);
|
||||
assert!(first.capped.is_empty());
|
||||
assert!(asked.paths().iter().all(|path| !path.starts_with("/forge/")), "a redirect is not followed: {:?}", asked.paths());
|
||||
assert!(asked.lock().unwrap().iter().all(|path| !path.starts_with("/forge/")), "a redirect is not followed: {:?}", asked.lock().unwrap());
|
||||
|
||||
let later = forge.activity(&wanted, &me(), Some(250), at(NOW)).unwrap();
|
||||
assert_eq!((later.events.iter().map(|event| event.id).collect::<Vec<_>>(), later.head), (vec![300], 300), "a later read goes on past the dark repos");
|
||||
|
|
@ -746,7 +799,9 @@ mod tests {
|
|||
let (base, _) = forge_of(move |path| {
|
||||
if is_feed(path) && path.contains("/GameCult/cinny/") {
|
||||
Some(dark())
|
||||
} else if is_feed(path) || path.contains("/issues/search") {
|
||||
} else if is_feed(path) {
|
||||
Some("[]".to_owned().into())
|
||||
} else if path.contains("/issues/search") {
|
||||
Some("[]".to_owned().into())
|
||||
} else {
|
||||
Some(listing.clone().into())
|
||||
|
|
|
|||
|
|
@ -1,128 +0,0 @@
|
|||
//! What one `huginn-sources` run does with the pieces it is handed: the forge
|
||||
//! refresh, then the chat refresh (or, with chat off, the retirement of every
|
||||
//! chat point), one exit status for both, and the steward-purge request. The
|
||||
//! binary supplies the real forge, embedder, vector store and Matrix client and
|
||||
//! owns the flags and the lock; this file decides nothing about scope or
|
||||
//! scrubbing (`room_scope` and `redact` do) and never sees a credential.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use super::chat::{Entry, RoomHistory, refresh_chat, retire_chat};
|
||||
use super::chat_purge::{PurgeWindow, parse_windows, purge_key, request_purge};
|
||||
use super::room_scope::Estate;
|
||||
use super::{DescribedSources, Forge, SourceIndex, refresh};
|
||||
use crate::index::{Embedder, INDEX_CALL_TIMEOUT};
|
||||
|
||||
/// Chat on: the reader's rooms and the estate ids the scope refuses.
|
||||
pub struct Chat<'a, H> {
|
||||
pub history: &'a mut H,
|
||||
pub estate: &'a Estate,
|
||||
}
|
||||
|
||||
/// One run: the forge refresh, then chat (`Some`) or the retirement of every chat point (`None`).
|
||||
/// `say` takes the journal's report lines (stdout), `complain` the failures, refusals and scrub hits (stderr).
|
||||
/// A forge failure never skips the chat run and a chat failure never hides a forge one.
|
||||
/// Returns the exit status: 0 only when both were clean.
|
||||
pub fn run<E: Embedder, S: SourceIndex, F: Forge, H: RoomHistory>(
|
||||
embedder: &mut E,
|
||||
index: &mut S,
|
||||
forge: &mut F,
|
||||
state_root: &Path,
|
||||
chat: Option<Chat<'_, H>>,
|
||||
say: &mut dyn FnMut(String),
|
||||
complain: &mut dyn FnMut(String),
|
||||
) -> u8 {
|
||||
let mut clean = true;
|
||||
match refresh(embedder, index, forge, state_root, &mut |report| say(report.to_string())) {
|
||||
Ok(refreshed) if refreshed.is_clean() => {}
|
||||
Ok(refreshed) => {
|
||||
clean = false;
|
||||
if !refreshed.failed.is_empty() {
|
||||
complain(format!("huginn-sources: {} repos failed: {}", refreshed.failed.len(), refreshed.failed.join(", ")));
|
||||
}
|
||||
if let Some(why) = &refreshed.retirement_withheld {
|
||||
complain(format!("huginn-sources: no repo was retired: {why}"));
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
clean = false;
|
||||
complain(format!("huginn-sources: {error:#}"));
|
||||
}
|
||||
}
|
||||
match chat {
|
||||
Some(Chat { history, estate }) => {
|
||||
let mut line = |entry: Entry| if entry.is_alarm() { complain(entry.to_string()) } else { say(entry.to_string()) };
|
||||
match refresh_chat(embedder, index, history, estate, &mut line) {
|
||||
Ok(refreshed) => clean &= refreshed.is_clean(),
|
||||
Err(error) => {
|
||||
clean = false;
|
||||
complain(format!("huginn-sources: chat: {error:#}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => match retire_chat(index, &BTreeSet::new()) {
|
||||
Ok(done) => {
|
||||
if !done.retired.is_empty() {
|
||||
say(format!("chat retired: {} rooms", done.retired.len()));
|
||||
}
|
||||
for (room, why) in done.failed {
|
||||
clean = false;
|
||||
complain(format!("huginn-sources: retiring {room} failed: {why}"));
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
clean = false;
|
||||
complain(format!("huginn-sources: chat: {error:#}"));
|
||||
}
|
||||
},
|
||||
}
|
||||
u8::from(!clean)
|
||||
}
|
||||
|
||||
/// The longest span one request may name.
|
||||
const PURGE_SPAN_DAYS: i64 = 366;
|
||||
const REQUEST_BYTES_MAX: usize = 120;
|
||||
|
||||
/// A steward's purge request as the admin typed it, checked. Each error names its option.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Purge {
|
||||
pub room_id: String,
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
pub request: String,
|
||||
pub window: PurgeWindow,
|
||||
}
|
||||
|
||||
fn instant(option: &str, text: &str) -> Result<DateTime<Utc>> {
|
||||
ensure!(text.ends_with('Z'), "--{option} must be an RFC 3339 UTC time ending in Z, got {text:?}");
|
||||
let at = DateTime::parse_from_rfc3339(text).map_err(|_| anyhow::anyhow!("--{option} must be an RFC 3339 UTC time ending in Z, got {text:?}"))?;
|
||||
Ok(at.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
impl Purge {
|
||||
pub fn check(room: &str, from: &str, to: &str, request: &str, now: DateTime<Utc>) -> Result<Self> {
|
||||
ensure!(room.starts_with('!'), "--room must be a room id beginning with !, got {room:?}: an alias needs Matrix, and the journal prints both #alias (!id)");
|
||||
let (start, end) = (instant("from", from)?, instant("to", to)?);
|
||||
ensure!(start < end, "--from must be before --to");
|
||||
ensure!(end <= now, "--to must not be after now");
|
||||
ensure!(end - start <= chrono::Duration::days(PURGE_SPAN_DAYS), "the window must be at most {PURGE_SPAN_DAYS} days");
|
||||
ensure!(!request.is_empty() && request.len() <= REQUEST_BYTES_MAX, "--request must be 1 to {REQUEST_BYTES_MAX} bytes");
|
||||
let ms = |at: DateTime<Utc>| u64::try_from(at.timestamp_millis()).context("a purge time before 1970");
|
||||
Ok(Self { room_id: room.to_owned(), from: from.to_owned(), to: to.to_owned(), request: request.to_owned(), window: PurgeWindow { from_ms: ms(start)?, to_ms: ms(end)? } })
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the tombstone and returns the line the admin sees; the free-text request is quoted and escaped so it cannot forge a journal line. Touches no point and makes no Matrix call;
|
||||
/// the caller holds the job's lock. The next run applies it.
|
||||
pub fn purge<S: SourceIndex>(index: &mut S, purge: &Purge) -> Result<String> {
|
||||
request_purge(index, &purge.room_id, purge.window)?;
|
||||
let DescribedSources::Labelled { cursors, .. } = index.describe_sources(INDEX_CALL_TIMEOUT).context("describing the source collection")? else {
|
||||
bail!("the source collection is absent or not Huginn's");
|
||||
};
|
||||
let windows = cursors.get(&purge_key(&purge.room_id)).map(|held| parse_windows(held)).transpose()?.map_or(0, |held| held.len());
|
||||
Ok(format!("chat-purge requested: {} {}..{} request={:?} windows={windows}", purge.room_id, purge.from, purge.to, purge.request))
|
||||
}
|
||||
|
|
@ -1,287 +0,0 @@
|
|||
//! One run of the job: forge refresh and chat refresh over a fake Synapse reached through the real client,
|
||||
//! a fake vector store and the fake embedder; the exit status; the chat-off retirement; the purge request.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde_json::json;
|
||||
|
||||
use super::chat::{CHAT_PURGE_PREFIX, RoomHistory};
|
||||
use super::job::{Chat, Purge, purge, run};
|
||||
use super::matrix::HttpMatrix;
|
||||
use super::matrix_tests::{Room, Rooms, TOKEN, message, state, synapse};
|
||||
use super::room_scope::Estate;
|
||||
use super::tests::{FakeForge, Remote};
|
||||
use super::test_http::forge_of;
|
||||
use super::*;
|
||||
use crate::index::fakes::{FakeEmbedder, FakeSources};
|
||||
|
||||
const DAY0: u64 = 1_794_268_800_000; // 2026-11-10T00:00:00Z
|
||||
|
||||
fn now() -> DateTime<Utc> {
|
||||
DateTime::parse_from_rfc3339("2026-11-17T00:00:00Z").unwrap().with_timezone(&Utc)
|
||||
}
|
||||
|
||||
fn estate() -> Estate {
|
||||
Estate::new(["!e1:s", "!e2:s", "!e3:s"].map(str::to_owned).into()).unwrap()
|
||||
}
|
||||
|
||||
struct Out {
|
||||
said: Vec<String>,
|
||||
complained: Vec<String>,
|
||||
status: u8,
|
||||
}
|
||||
|
||||
struct Rig {
|
||||
embedder: FakeEmbedder,
|
||||
index: FakeSources,
|
||||
forge: FakeForge,
|
||||
_remote: Remote,
|
||||
root: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
let remote = Remote::new();
|
||||
remote.commit(&[("README.md", b"# Demo\n")], &[]);
|
||||
Self { embedder: FakeEmbedder::new("d1"), index: FakeSources::default(), forge: FakeForge::of(&[("Demo", &remote)]), _remote: remote, root: tempfile::tempdir().unwrap() }
|
||||
}
|
||||
|
||||
fn go<H: RoomHistory>(&mut self, history: Option<&mut H>) -> Out {
|
||||
let (mut said, mut complained) = (Vec::new(), Vec::new());
|
||||
let estate = estate();
|
||||
let chat = history.map(|history| Chat { history, estate: &estate });
|
||||
let status = run(&mut self.embedder, &mut self.index, &mut self.forge, self.root.path(), chat, &mut |line| said.push(line), &mut |line| complained.push(line));
|
||||
Out { said, complained, status }
|
||||
}
|
||||
|
||||
fn chat_bodies(&self) -> Vec<String> {
|
||||
let mut bodies: Vec<String> = self.index.state.lock().unwrap().chat.values().flat_map(|point| point.payload.messages.iter().map(|m| m.body.clone())).collect();
|
||||
bodies.sort();
|
||||
bodies
|
||||
}
|
||||
|
||||
fn chat_rooms(&self) -> std::collections::BTreeSet<String> {
|
||||
self.index.state.lock().unwrap().chat.values().map(|point| point.payload.room_id.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn rooms(list: Vec<(&str, Vec<serde_json::Value>, Vec<serde_json::Value>)>) -> Rooms {
|
||||
Arc::new(Mutex::new(list.into_iter().map(|(id, state, timeline)| (id.to_owned(), Room { state, timeline })).collect::<BTreeMap<_, _>>()))
|
||||
}
|
||||
|
||||
fn platform() -> String {
|
||||
["disc", "ord"].concat()
|
||||
}
|
||||
|
||||
fn world() -> Rooms {
|
||||
let relay = format!("@_{}_1:s", platform());
|
||||
rooms(vec![
|
||||
("!swarm:s", vec![state("m.room.canonical_alias", json!({ "alias": "#swarm:gamecult.org" })), state("m.room.join_rules", json!({ "join_rule": "invite" }))], vec![
|
||||
message("$m1", "@a:s", DAY0 - 5000, "first words"),
|
||||
message("$m2", "@b:s", DAY0 - 4000, "to be redacted"),
|
||||
message("$m3", "@a:s", DAY0 + 1000, "inside the window"),
|
||||
]),
|
||||
("!bridged:s", vec![state("m.bridge", json!({}))], vec![message("$b1", "@a:s", DAY0, "bridged talk")]),
|
||||
("!relay:s", vec![], vec![message("$d1", &relay, DAY0, "relayed talk")]),
|
||||
("!aliased:s", vec![state("m.room.canonical_alias", json!({ "alias": "#Users:gamecult.org" }))], vec![message("$u1", "@a:s", DAY0, "estate talk")]),
|
||||
])
|
||||
}
|
||||
|
||||
fn all_lines(out: &Out) -> String {
|
||||
out.said.iter().chain(&out.complained).cloned().collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_run_over_a_fake_synapse() {
|
||||
let world = world();
|
||||
let (base, asked) = synapse(&world);
|
||||
let mut matrix = HttpMatrix::new(&base, TOKEN);
|
||||
let mut rig = Rig::new();
|
||||
|
||||
let first = rig.go(Some(&mut matrix));
|
||||
assert_eq!(first.status, 1, "joined bridged, relay and estate rooms are refused: {:?}", first.complained);
|
||||
assert_eq!(rig.chat_rooms(), ["!swarm:s".to_owned()].into(), "an invite-only room is ingested; nothing of the refused rooms is");
|
||||
assert_eq!(rig.chat_bodies(), ["first words", "inside the window", "to be redacted"]);
|
||||
for refused in ["!bridged:s", "!relay:s", "!aliased:s"] {
|
||||
assert!(first.complained.iter().any(|line| line.starts_with("refused:") && line.contains(refused)), "{refused}: {:?}", first.complained);
|
||||
}
|
||||
assert!(!rig.embedder.texts().iter().any(|text| text.contains("bridged talk") || text.contains("relayed talk") || text.contains("estate talk")));
|
||||
assert!(first.said.iter().any(|line| line.starts_with("Demo ")), "the forge's line is journaled too");
|
||||
assert!(first.said.iter().any(|line| line.starts_with("#swarm:gamecult.org (!swarm:s)") && line.contains("events=3")), "{:?}", first.said);
|
||||
assert!(asked.seen().iter().all(|seen| seen.method == "GET"));
|
||||
|
||||
// The steward asks for the window; then the room edits, redacts and leaks a key.
|
||||
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "follow_up:x", now()).unwrap();
|
||||
assert_eq!(purge(&mut rig.index, &request).unwrap(), "chat-purge requested: !swarm:s 2026-11-10T00:00:00Z..2026-11-11T00:00:00Z request=\"follow_up:x\" windows=1");
|
||||
let before = rig.index.cursors();
|
||||
assert!(purge(&mut rig.index, &request).unwrap().ends_with("windows=1"));
|
||||
assert_eq!(rig.index.cursors(), before, "a repeated request writes nothing");
|
||||
let secret = format!("key ghp_{}", "k2L9".repeat(9));
|
||||
{
|
||||
let mut held = world.lock().unwrap();
|
||||
let room = held.get_mut("!swarm:s").unwrap();
|
||||
room.timeline.push(json!({ "type": "m.room.message", "event_id": "$edit", "sender": "@a:s", "origin_server_ts": DAY0 + 90_000_000, "content": {
|
||||
"msgtype": "m.text", "body": "* first words, amended", "m.new_content": { "msgtype": "m.text", "body": "first words, amended" }, "m.relates_to": { "rel_type": "m.replace", "event_id": "$m1" } } }));
|
||||
room.timeline.push(json!({ "type": "m.room.redaction", "event_id": "$red", "sender": "@b:s", "origin_server_ts": DAY0 + 91_000_000, "content": { "redacts": "$m2" } }));
|
||||
room.timeline.push(message("$m4", "@a:s", DAY0 + 92_000_000, &secret));
|
||||
}
|
||||
let second = rig.go(Some(&mut matrix));
|
||||
assert_eq!(rig.chat_bodies().len(), 2, "{:?}", rig.chat_bodies());
|
||||
let bodies = rig.chat_bodies().join("\n");
|
||||
assert!(bodies.contains("first words, amended") && !bodies.contains("to be redacted") && !bodies.contains("inside the window"), "{bodies}");
|
||||
assert!(!bodies.contains("ghp_k2L9") && !rig.embedder.texts().iter().any(|text| text.contains("ghp_k2L9")), "the key was scrubbed before it was embedded");
|
||||
let text = all_lines(&second);
|
||||
assert!(second.said.iter().any(|line| line.contains("purged=")), "{text}");
|
||||
assert!(second.complained.iter().any(|line| line == "scrubbed: !swarm:s $m4 key-shape" || line.starts_with("scrubbed: !swarm:s $m4 ")), "{text}");
|
||||
for body in ["first words", "to be redacted", "inside the window", "relayed talk", "ghp_"] {
|
||||
assert!(!text.contains(body), "the journal carries ids and counts, not bodies: {body}");
|
||||
}
|
||||
let third = rig.go(Some(&mut matrix));
|
||||
assert!(!rig.chat_bodies().join("\n").contains("inside the window"), "a purged window does not come back");
|
||||
assert!(third.complained.iter().all(|line| line.starts_with("refused:")), "{:?}", third.complained);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_chat_flags_purge_the_corpus_and_make_no_matrix_call() {
|
||||
let world = world();
|
||||
let (base, _) = synapse(&world);
|
||||
let mut matrix = HttpMatrix::new(&base, TOKEN);
|
||||
let mut rig = Rig::new();
|
||||
rig.go(Some(&mut matrix));
|
||||
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "r", now()).unwrap();
|
||||
purge(&mut rig.index, &request).unwrap();
|
||||
assert!(!rig.chat_bodies().is_empty());
|
||||
|
||||
let (hung, asked) = forge_of(|_| None::<String>);
|
||||
drop(hung);
|
||||
let out = rig.go::<HttpMatrix>(None);
|
||||
assert_eq!(out.status, 0, "{:?}", out.complained);
|
||||
assert!(rig.chat_bodies().is_empty() && rig.chat_rooms().is_empty());
|
||||
assert!(rig.index.cursors().keys().any(|key| key.starts_with(CHAT_PURGE_PREFIX)), "tombstones stay");
|
||||
assert!(!rig.index.cursors().keys().any(|key| key.starts_with("chat:")), "cursors go");
|
||||
assert!(asked.seen().is_empty());
|
||||
}
|
||||
|
||||
struct BrokenForge;
|
||||
|
||||
impl Forge for BrokenForge {
|
||||
fn catalog(&mut self) -> Result<Catalog> {
|
||||
bail!("the forge is down")
|
||||
}
|
||||
|
||||
fn clone_url(&self, _name: &str) -> String {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
struct DeadSynapse;
|
||||
|
||||
impl RoomHistory for DeadSynapse {
|
||||
fn joined_rooms(&mut self) -> Result<Vec<String>> {
|
||||
bail!("synapse is down")
|
||||
}
|
||||
|
||||
fn facts(&mut self, _room_id: &str) -> Result<super::room_scope::RoomFacts> {
|
||||
bail!("synapse is down")
|
||||
}
|
||||
|
||||
fn events_after(&mut self, _room_id: &str, _after: Option<&str>, _limit: u32) -> Result<Option<super::chat::EventPage>> {
|
||||
bail!("synapse is down")
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_status_is_clean_only_when_forge_and_chat_both_are() {
|
||||
let clean = rooms(vec![("!swarm:s", vec![], vec![message("$m1", "@a:s", 1, "words")])]);
|
||||
let (base, _) = synapse(&clean);
|
||||
let mut rig = Rig::new();
|
||||
let out = rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
|
||||
assert_eq!((out.status, out.complained.len()), (0, 0));
|
||||
|
||||
// Scrub hits alone are not a failure; they are reported.
|
||||
clean.lock().unwrap().get_mut("!swarm:s").unwrap().timeline.push(message("$m2", "@a:s", 2, &format!("ghp_{}", "k2L9".repeat(9))));
|
||||
let out = rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
|
||||
assert_eq!(out.status, 0, "{:?}", out.complained);
|
||||
assert!(out.complained.iter().any(|line| line.starts_with("scrubbed: !swarm:s $m2")));
|
||||
|
||||
// A chat failure still reports the forge, and a forge failure still runs chat.
|
||||
let out = rig.go(Some(&mut DeadSynapse));
|
||||
assert_eq!(out.status, 1);
|
||||
assert!(out.complained.iter().any(|line| line.contains("synapse is down")));
|
||||
let (mut said, mut complained) = (Vec::new(), Vec::new());
|
||||
let (estate, mut ok) = (estate(), HttpMatrix::new(&base, TOKEN));
|
||||
let status = run(&mut rig.embedder, &mut rig.index, &mut BrokenForge, rig.root.path(), Some(Chat { history: &mut ok, estate: &estate }), &mut |l| said.push(l), &mut |l| complained.push(l));
|
||||
assert_eq!(status, 1);
|
||||
assert!(complained.iter().any(|line| line.contains("the forge is down")), "{complained:?}");
|
||||
assert!(said.iter().any(|line| line.contains("(!swarm:s)")), "chat ran after the forge failed: {said:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_cannot_forge_a_journal_line() {
|
||||
let mut rig = Rig::new();
|
||||
rig.go::<HttpMatrix>(None);
|
||||
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "x\nrefused: !forged:s", now()).unwrap();
|
||||
let line = purge(&mut rig.index, &request).unwrap();
|
||||
assert_eq!(line.lines().count(), 1, "{line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_room_report_goes_to_the_complaint_stream_and_fails_the_run() {
|
||||
let mut rig = Rig::new();
|
||||
struct FactsDown;
|
||||
impl RoomHistory for FactsDown {
|
||||
fn joined_rooms(&mut self) -> Result<Vec<String>> {
|
||||
Ok(vec!["!swarm:s".to_owned()])
|
||||
}
|
||||
fn facts(&mut self, _room_id: &str) -> Result<super::room_scope::RoomFacts> {
|
||||
bail!("facts are down")
|
||||
}
|
||||
fn events_after(&mut self, _room_id: &str, _after: Option<&str>, _limit: u32) -> Result<Option<super::chat::EventPage>> {
|
||||
bail!("unreachable")
|
||||
}
|
||||
}
|
||||
let out = rig.go(Some(&mut FactsDown));
|
||||
assert_eq!(out.status, 1);
|
||||
assert!(out.complained.iter().any(|line| line.contains("!swarm:s") && line.contains("facts are down")), "{:?}", out.complained);
|
||||
assert!(!out.said.iter().any(|line| line.contains("facts are down")), "{:?}", out.said);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_purge_makes_no_matrix_request() {
|
||||
let world = world();
|
||||
let (base, asked) = synapse(&world);
|
||||
let mut rig = Rig::new();
|
||||
rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
|
||||
let made = asked.seen().len();
|
||||
let request = Purge::check("!swarm:s", "2026-11-10T00:00:00Z", "2026-11-11T00:00:00Z", "r", now()).unwrap();
|
||||
purge(&mut rig.index, &request).unwrap();
|
||||
assert_eq!(asked.seen().len(), made);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retirement_failure_goes_to_the_complaint_stream() {
|
||||
struct Left;
|
||||
impl RoomHistory for Left {
|
||||
fn joined_rooms(&mut self) -> Result<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn facts(&mut self, _room_id: &str) -> Result<super::room_scope::RoomFacts> {
|
||||
bail!("unreachable")
|
||||
}
|
||||
fn events_after(&mut self, _room_id: &str, _after: Option<&str>, _limit: u32) -> Result<Option<super::chat::EventPage>> {
|
||||
bail!("unreachable")
|
||||
}
|
||||
}
|
||||
let world = rooms(vec![("!swarm:s", vec![], vec![message("$m1", "@a:s", 1, "words")])]);
|
||||
let (base, _) = synapse(&world);
|
||||
let mut rig = Rig::new();
|
||||
rig.go(Some(&mut HttpMatrix::new(&base, TOKEN)));
|
||||
rig.index.state.lock().unwrap().fail_chat_deletes = true;
|
||||
let out = rig.go(Some(&mut Left));
|
||||
assert_eq!(out.status, 1);
|
||||
assert!(out.complained.iter().any(|line| line.starts_with("huginn-sources: retiring !swarm:s failed")), "{:?}", out.complained);
|
||||
assert!(!out.said.iter().any(|line| line.contains("retiring")), "{:?}", out.said);
|
||||
}
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
//! Synapse's client API as the reader user sees it: Matrix JSON in, `RoomEvent`
|
||||
//! and `RoomFacts` out. JSON for Matrix is spoken here and nowhere else. This
|
||||
//! client reads with GET only and holds no policy: it filters nothing, decides
|
||||
//! no room's or sender's scope, and names no platform. What is in scope is
|
||||
//! `room_scope`'s; the token is read at one place, the `Authorization` header.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::chat::{EventKind, EventPage, RoomEvent, RoomHistory};
|
||||
use super::room_scope::RoomFacts;
|
||||
|
||||
const CALL_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// A bridge's state event types: either marks a room as relaying another platform.
|
||||
const BRIDGE_TYPES: [&str; 2] = ["m.bridge", "uk.half-shot.bridge"];
|
||||
|
||||
pub struct HttpMatrix {
|
||||
agent: ureq::Agent,
|
||||
base: String,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for HttpMatrix {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.debug_struct("HttpMatrix").field("base", &self.base).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A path segment with everything but unreserved characters escaped.
|
||||
fn segment(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
for byte in raw.bytes() {
|
||||
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
|
||||
out.push(char::from(byte));
|
||||
} else {
|
||||
out.push_str(&format!("%{byte:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl HttpMatrix {
|
||||
pub fn new(base_url: &str, token: &str) -> Self {
|
||||
let agent: ureq::Agent =
|
||||
ureq::Agent::config_builder().timeout_global(Some(CALL_TIMEOUT)).http_status_as_error(false).build().into();
|
||||
Self { agent, base: base_url.trim_end_matches('/').to_owned(), token: token.to_owned() }
|
||||
}
|
||||
|
||||
/// One GET of `path` (already escaped): the status and the JSON body. No message made here carries the token.
|
||||
fn get(&self, path: &str) -> Result<(u16, Value)> {
|
||||
let url = format!("{}{path}", self.base);
|
||||
let mut response = self
|
||||
.agent
|
||||
.get(&url)
|
||||
.header("Authorization", format!("Bearer {}", self.token))
|
||||
.call()
|
||||
.with_context(|| format!("no answer from {url}"))?;
|
||||
let status = response.status().as_u16();
|
||||
let body = response.body_mut().read_to_string().with_context(|| format!("reading the answer from {url}"))?;
|
||||
Ok((status, serde_json::from_str(&body).unwrap_or(Value::Null)))
|
||||
}
|
||||
|
||||
fn ok(&self, path: &str) -> Result<Value> {
|
||||
let (status, body) = self.get(path)?;
|
||||
if status != 200 {
|
||||
bail!("synapse answered {status} for {path}");
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
}
|
||||
|
||||
fn event_of(raw: &Value) -> Result<RoomEvent> {
|
||||
let text = |key: &str| raw[key].as_str().map(str::to_owned).with_context(|| format!("an event has no {key}"));
|
||||
let content = &raw["content"];
|
||||
let content_keys = content.as_object().map(|map| map.keys().cloned().collect()).unwrap_or_default();
|
||||
Ok(RoomEvent { event_id: text("event_id")?, sender: text("sender")?, ts_ms: raw["origin_server_ts"].as_u64().context("an event has no origin_server_ts")?, content_keys, kind: kind_of(raw) })
|
||||
}
|
||||
|
||||
fn kind_of(raw: &Value) -> EventKind {
|
||||
let content = &raw["content"];
|
||||
if !raw["unsigned"]["redacted_because"].is_null() {
|
||||
return EventKind::Other;
|
||||
}
|
||||
match raw["type"].as_str() {
|
||||
Some("m.room.redaction") => match content["redacts"].as_str().or_else(|| raw["redacts"].as_str()) {
|
||||
Some(target) => EventKind::Redaction { target: target.to_owned() },
|
||||
None => EventKind::Other,
|
||||
},
|
||||
Some("m.room.message") if matches!(content["msgtype"].as_str(), Some("m.text" | "m.notice" | "m.emote")) => {
|
||||
let Some(body) = content["body"].as_str() else { return EventKind::Other };
|
||||
let relation = &content["m.relates_to"];
|
||||
if relation["rel_type"].as_str() == Some("m.replace") {
|
||||
return match (relation["event_id"].as_str(), content["m.new_content"]["body"].as_str()) {
|
||||
(Some(target), Some(new)) => EventKind::Edit { target: target.to_owned(), body: new.to_owned() },
|
||||
_ => EventKind::Other,
|
||||
};
|
||||
}
|
||||
EventKind::Message { body: body.to_owned() }
|
||||
}
|
||||
_ => EventKind::Other,
|
||||
}
|
||||
}
|
||||
|
||||
impl RoomHistory for HttpMatrix {
|
||||
fn joined_rooms(&mut self) -> Result<Vec<String>> {
|
||||
let body = self.ok("/_matrix/client/v3/joined_rooms")?;
|
||||
let rooms = body["joined_rooms"].as_array().context("the joined rooms answer is not a list")?;
|
||||
Ok(rooms.iter().filter_map(|room| room.as_str().map(str::to_owned)).collect())
|
||||
}
|
||||
|
||||
fn facts(&mut self, room_id: &str) -> Result<RoomFacts> {
|
||||
let body = self.ok(&format!("/_matrix/client/v3/rooms/{}/state", segment(room_id)))?;
|
||||
let state = body.as_array().context("the room state is not a list")?;
|
||||
let mut facts = RoomFacts { room_id: room_id.to_owned(), alias: None, alt_aliases: Vec::new(), name: None, encrypted: false, direct: false, bridge: None };
|
||||
for event in state {
|
||||
let content = &event["content"];
|
||||
match event["type"].as_str() {
|
||||
Some("m.room.canonical_alias") => {
|
||||
facts.alias = content["alias"].as_str().map(str::to_owned);
|
||||
facts.alt_aliases = content["alt_aliases"].as_array().map(|list| list.iter().filter_map(|alias| alias.as_str().map(str::to_owned)).collect()).unwrap_or_default();
|
||||
}
|
||||
Some("m.room.name") => facts.name = content["name"].as_str().map(str::to_owned),
|
||||
Some("m.room.encryption") => facts.encrypted = true,
|
||||
Some("m.room.member") if content["is_direct"].as_bool() == Some(true) => facts.direct = true,
|
||||
Some(kind) if BRIDGE_TYPES.contains(&kind) => {
|
||||
facts.bridge.get_or_insert_with(|| kind.to_owned());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(facts)
|
||||
}
|
||||
|
||||
fn events_after(&mut self, room_id: &str, after: Option<&str>, limit: u32) -> Result<Option<EventPage>> {
|
||||
let room = segment(room_id);
|
||||
let from = match after {
|
||||
None => String::new(),
|
||||
Some(event) => {
|
||||
let (status, body) = self.get(&format!("/_matrix/client/v3/rooms/{room}/context/{}?limit=0", segment(event)))?;
|
||||
match status {
|
||||
200 => match body["end"].as_str() {
|
||||
Some(end) => format!("&from={}", segment(end)),
|
||||
None => bail!("synapse gave no end token for the context of {event} in {room_id}"),
|
||||
},
|
||||
404 => return Ok(None),
|
||||
other => bail!("synapse answered {other} for the context of {event} in {room_id}"),
|
||||
}
|
||||
}
|
||||
};
|
||||
let body = self.ok(&format!("/_matrix/client/v3/rooms/{room}/messages?dir=f&limit={limit}{from}"))?;
|
||||
let chunk = body["chunk"].as_array().context("the messages answer has no chunk")?;
|
||||
let events = chunk.iter().map(event_of).collect::<Result<Vec<_>>>()?;
|
||||
let more = body["end"].as_str().is_some() && !events.is_empty();
|
||||
Ok(Some(EventPage { events, more }))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,207 +0,0 @@
|
|||
//! The Matrix client against a fake Synapse that speaks the client API's JSON.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::chat::{EventKind, RoomHistory};
|
||||
use super::matrix::HttpMatrix;
|
||||
use super::test_http::{Asked, Reply, forge_of};
|
||||
|
||||
pub(super) const TOKEN: &str = "syt_reader_9f8e7d6c5b4a";
|
||||
|
||||
/// A room as the fake server holds it: its state events and its timeline.
|
||||
pub(super) struct Room {
|
||||
pub state: Vec<Value>,
|
||||
pub timeline: Vec<Value>,
|
||||
}
|
||||
|
||||
pub(super) type Rooms = Arc<Mutex<BTreeMap<String, Room>>>;
|
||||
|
||||
pub(super) fn decode(raw: &str) -> String {
|
||||
let bytes = raw.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < bytes.len() {
|
||||
if bytes[at] == b'%' {
|
||||
out.push(u8::from_str_radix(&raw[at + 1..at + 3], 16).unwrap());
|
||||
at += 3;
|
||||
} else {
|
||||
out.push(bytes[at]);
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).unwrap()
|
||||
}
|
||||
|
||||
pub(super) fn message(id: &str, sender: &str, ts: u64, body: &str) -> Value {
|
||||
json!({ "type": "m.room.message", "event_id": id, "sender": sender, "origin_server_ts": ts, "content": { "msgtype": "m.text", "body": body } })
|
||||
}
|
||||
|
||||
pub(super) fn state(kind: &str, content: Value) -> Value {
|
||||
json!({ "type": kind, "state_key": "", "content": content })
|
||||
}
|
||||
|
||||
/// A Synapse over `rooms`, joined to the rooms in the map: GET only, bearer required.
|
||||
pub(super) fn synapse(rooms: &Rooms) -> (String, Asked) {
|
||||
let rooms = Arc::clone(rooms);
|
||||
forge_of(move |raw| {
|
||||
let (path, query) = raw.split_once('?').unwrap_or((raw, ""));
|
||||
let path = decode(path);
|
||||
let rooms = rooms.lock().unwrap();
|
||||
let rest = path.strip_prefix("/_matrix/client/v3/")?;
|
||||
if rest == "joined_rooms" {
|
||||
return Some(Reply::from(json!({ "joined_rooms": rooms.keys().collect::<Vec<_>>() }).to_string()));
|
||||
}
|
||||
let rest = rest.strip_prefix("rooms/")?;
|
||||
let (id, rest) = rest.split_once('/')?;
|
||||
let Some(room) = rooms.get(id) else { return Some(Reply::status(404, r#"{"errcode":"M_NOT_FOUND"}"#)) };
|
||||
let query: BTreeMap<String, String> = query.split('&').filter_map(|pair| pair.split_once('=')).map(|(k, v)| (k.to_owned(), decode(v))).collect();
|
||||
if rest == "state" {
|
||||
return Some(Reply::from(Value::Array(room.state.clone()).to_string()));
|
||||
}
|
||||
if let Some(event) = rest.strip_prefix("context/") {
|
||||
return Some(match room.timeline.iter().any(|held| held["event_id"] == event) {
|
||||
true => Reply::from(json!({ "end": format!("t_{event}"), "events_before": [], "events_after": [] }).to_string()),
|
||||
false => Reply::status(404, r#"{"errcode":"M_NOT_FOUND"}"#),
|
||||
});
|
||||
}
|
||||
if rest == "messages" {
|
||||
let start = match query.get("from") {
|
||||
Some(from) => 1 + room.timeline.iter().position(|held| format!("t_{}", held["event_id"].as_str().unwrap()) == *from)?,
|
||||
None => 0,
|
||||
};
|
||||
let limit: usize = query["limit"].parse().unwrap();
|
||||
let chunk: Vec<&Value> = room.timeline.iter().skip(start).take(limit).collect();
|
||||
let end = chunk.last().map(|last| format!("t_{}", last["event_id"].as_str().unwrap()));
|
||||
return Some(Reply::from(json!({ "chunk": chunk, "end": end }).to_string()));
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
fn one_room(state: Vec<Value>, timeline: Vec<Value>) -> Rooms {
|
||||
Arc::new(Mutex::new(BTreeMap::from([("!r:s".to_owned(), Room { state, timeline })])))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_maps_to_facts_and_the_join_rule_is_not_read() {
|
||||
let plain = one_room(vec![state("m.room.join_rules", json!({ "join_rule": "invite" }))], vec![]);
|
||||
let (base, _) = synapse(&plain);
|
||||
let facts = HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap();
|
||||
assert_eq!((facts.alias, facts.name, facts.encrypted, facts.direct, facts.bridge), (None, None, false, false, None));
|
||||
for rule in ["public", "knock", "invite"] {
|
||||
let rooms = one_room(vec![state("m.room.join_rules", json!({ "join_rule": rule }))], vec![]);
|
||||
let (base, _) = synapse(&rooms);
|
||||
let facts = HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap();
|
||||
assert!(!facts.direct && !facts.encrypted && facts.bridge.is_none(), "{rule}");
|
||||
}
|
||||
let full = one_room(
|
||||
vec![
|
||||
state("m.room.canonical_alias", json!({ "alias": "#a:s", "alt_aliases": ["#b:s", "#c:s"] })),
|
||||
state("m.room.name", json!({ "name": "Swarm" })),
|
||||
state("m.room.encryption", json!({ "algorithm": "m.megolm.v1.aes-sha2" })),
|
||||
json!({ "type": "m.room.member", "state_key": "@x:s", "content": { "membership": "join" } }),
|
||||
json!({ "type": "m.room.member", "state_key": "@y:s", "content": { "membership": "join", "is_direct": true } }),
|
||||
state("uk.half-shot.bridge", json!({})),
|
||||
],
|
||||
vec![],
|
||||
);
|
||||
let (base, _) = synapse(&full);
|
||||
let facts = HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap();
|
||||
assert_eq!(facts.alias.as_deref(), Some("#a:s"));
|
||||
assert_eq!(facts.alt_aliases, ["#b:s", "#c:s"]);
|
||||
assert_eq!(facts.name.as_deref(), Some("Swarm"));
|
||||
assert!(facts.encrypted && facts.direct);
|
||||
assert_eq!(facts.bridge.as_deref(), Some("uk.half-shot.bridge"));
|
||||
let relay = one_room(vec![state("m.bridge", json!({}))], vec![]);
|
||||
let (base, _) = synapse(&relay);
|
||||
assert_eq!(HttpMatrix::new(&base, TOKEN).facts("!r:s").unwrap().bridge.as_deref(), Some("m.bridge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn events_map_to_kinds_and_content_keys_are_names_only() {
|
||||
let mut other = message("$img", "@a:s", 3, "pic.png");
|
||||
other["content"]["msgtype"] = json!("m.image");
|
||||
let mut pruned = message("$pruned", "@a:s", 4, "was here");
|
||||
pruned["unsigned"] = json!({ "redacted_because": { "event_id": "$x" } });
|
||||
let mut notice = message("$n", "@a:s", 5, "n");
|
||||
notice["content"]["msgtype"] = json!("m.notice");
|
||||
let mut emote = message("$e", "@a:s", 6, "e");
|
||||
emote["content"]["msgtype"] = json!("m.emote");
|
||||
let edit = json!({ "type": "m.room.message", "event_id": "$edit", "sender": "@a:s", "origin_server_ts": 7, "content": {
|
||||
"msgtype": "m.text", "body": "* new", "m.new_content": { "msgtype": "m.text", "body": "new" }, "m.relates_to": { "rel_type": "m.replace", "event_id": "$m1" } } });
|
||||
let redaction = json!({ "type": "m.room.redaction", "event_id": "$red", "sender": "@a:s", "origin_server_ts": 8, "content": { "redacts": "$m1" } });
|
||||
let old_redaction = json!({ "type": "m.room.redaction", "event_id": "$red2", "sender": "@a:s", "origin_server_ts": 9, "redacts": "$m2", "content": {} });
|
||||
let encrypted = json!({ "type": "m.room.encrypted", "event_id": "$enc", "sender": "@a:s", "origin_server_ts": 10, "content": { "ciphertext": "xx" } });
|
||||
let timeline = vec![message("$m1", "@a:s", 1, "hello"), other, pruned, notice, emote, edit, redaction, old_redaction, encrypted];
|
||||
let rooms = one_room(vec![], timeline);
|
||||
let (base, _) = synapse(&rooms);
|
||||
let page = HttpMatrix::new(&base, TOKEN).events_after("!r:s", None, 50).unwrap().unwrap();
|
||||
let kinds: Vec<EventKind> = page.events.iter().map(|event| event.kind.clone()).collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
EventKind::Message { body: "hello".into() },
|
||||
EventKind::Other,
|
||||
EventKind::Other,
|
||||
EventKind::Message { body: "n".into() },
|
||||
EventKind::Message { body: "e".into() },
|
||||
EventKind::Edit { target: "$m1".into(), body: "new".into() },
|
||||
EventKind::Redaction { target: "$m1".into() },
|
||||
EventKind::Redaction { target: "$m2".into() },
|
||||
EventKind::Other,
|
||||
]
|
||||
);
|
||||
assert_eq!(page.events[0].content_keys, ["body", "msgtype"]);
|
||||
assert_eq!(page.events[5].content_keys, ["body", "m.new_content", "m.relates_to", "msgtype"], "names, never values");
|
||||
assert_eq!((page.events[0].event_id.as_str(), page.events[0].sender.as_str(), page.events[0].ts_ms), ("$m1", "@a:s", 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_uses_the_cursor_events_end_token_and_a_missing_event_is_none() {
|
||||
let rooms = one_room(vec![], vec![message("$1", "@a:s", 1, "a"), message("$2", "@a:s", 2, "b"), message("$3", "@a:s", 3, "c")]);
|
||||
let (base, asked) = synapse(&rooms);
|
||||
let mut matrix = HttpMatrix::new(&base, TOKEN);
|
||||
let page = matrix.events_after("!r:s", Some("$1"), 1).unwrap().unwrap();
|
||||
assert_eq!(page.events.iter().map(|event| event.event_id.as_str()).collect::<Vec<_>>(), ["$2"]);
|
||||
assert!(page.more);
|
||||
assert_eq!(asked.paths(), ["/_matrix/client/v3/rooms/%21r%3As/context/%241?limit=0", "/_matrix/client/v3/rooms/%21r%3As/messages?dir=f&limit=1&from=t_%241"]);
|
||||
assert!(matrix.events_after("!r:s", Some("$unknown"), 5).unwrap().is_none());
|
||||
let tail = matrix.events_after("!r:s", Some("$3"), 5).unwrap().unwrap();
|
||||
assert!(tail.events.is_empty() && !tail.more, "an empty chunk ends the run");
|
||||
let first = matrix.events_after("!r:s", None, 2).unwrap().unwrap();
|
||||
assert_eq!(first.events.len(), 2);
|
||||
assert_eq!(asked.paths().last().unwrap(), "/_matrix/client/v3/rooms/%21r%3As/messages?dir=f&limit=2", "no from, no context call");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_get_always_the_bearer_and_the_token_is_never_printed() {
|
||||
let rooms = one_room(vec![], vec![message("$1", "@a:s", 1, "a")]);
|
||||
let (base, asked) = synapse(&rooms);
|
||||
let mut matrix = HttpMatrix::new(&base, TOKEN);
|
||||
matrix.joined_rooms().unwrap();
|
||||
matrix.facts("!r:s").unwrap();
|
||||
matrix.events_after("!r:s", Some("$1"), 3).unwrap();
|
||||
let seen = asked.seen();
|
||||
assert!(seen.len() >= 4 && seen.iter().all(|seen| seen.method == "GET" && seen.authorization.as_deref() == Some(&format!("Bearer {TOKEN}"))), "{seen:?}");
|
||||
let (base, _) = forge_of(|_| Some(Reply::status(401, &format!(r#"{{"errcode":"M_UNKNOWN_TOKEN","error":"bad {TOKEN}"}}"#))));
|
||||
let mut matrix = HttpMatrix::new(&base, TOKEN);
|
||||
let error = matrix.joined_rooms().unwrap_err();
|
||||
assert!(format!("{error:#}").contains("401"));
|
||||
assert!(!format!("{error:#}{error:?}").contains(TOKEN));
|
||||
assert!(!format!("{matrix:?}").contains(TOKEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_percent_encoded_in_paths() {
|
||||
let weird = "$a+b/c=d:s";
|
||||
let rooms: Rooms = Arc::new(Mutex::new(BTreeMap::from([("!ro om:s".to_owned(), Room { state: vec![], timeline: vec![message(weird, "@a:s", 1, "x"), message("$2", "@a:s", 2, "y")] })])));
|
||||
let (base, asked) = synapse(&rooms);
|
||||
let mut matrix = HttpMatrix::new(&base, TOKEN);
|
||||
let page = matrix.events_after("!ro om:s", Some(weird), 5).unwrap().unwrap();
|
||||
assert_eq!(page.events.len(), 1, "the server decoded the room and event ids to the originals");
|
||||
let raw = asked.paths();
|
||||
assert!(raw.iter().all(|path| !path.contains('+') && !path.contains(' ') && !path.contains("!ro")), "{raw:?}");
|
||||
}
|
||||
|
|
@ -30,20 +30,11 @@ pub mod chat_purge;
|
|||
pub mod chunk;
|
||||
pub mod forge;
|
||||
pub mod git;
|
||||
pub mod job;
|
||||
pub mod matrix;
|
||||
pub mod room_scope;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_http;
|
||||
|
||||
#[cfg(test)]
|
||||
mod chat_tests;
|
||||
#[cfg(test)]
|
||||
mod job_tests;
|
||||
#[cfg(test)]
|
||||
mod matrix_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::hash_map::Entry;
|
||||
|
|
|
|||
|
|
@ -1,92 +0,0 @@
|
|||
//! The one fake HTTP server the source tests talk to (the forge's and Matrix's):
|
||||
//! it answers by path, holds open a path it has no answer for as a hung server
|
||||
//! does, and records each request's method, path and `Authorization` header.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
/// What a fake server answers: a status, the `Location` header when there is one, and a body.
|
||||
pub struct Reply {
|
||||
pub status: u16,
|
||||
pub location: Option<String>,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl From<String> for Reply {
|
||||
fn from(body: String) -> Self {
|
||||
Self { status: 200, location: None, body }
|
||||
}
|
||||
}
|
||||
|
||||
impl Reply {
|
||||
/// What the live forge answers an anonymous reader for a private repo.
|
||||
pub fn not_found() -> Self {
|
||||
Self { status: 404, location: None, body: json!({ "message": "The target couldn't be found." }).to_string() }
|
||||
}
|
||||
|
||||
/// What the live forge answers for a renamed repo: a 301 to its public address, `/forge` prefix and all.
|
||||
pub fn moved_to(location: &str) -> Self {
|
||||
Self { status: 301, location: Some(location.to_owned()), body: String::new() }
|
||||
}
|
||||
|
||||
pub fn status(status: u16, body: &str) -> Self {
|
||||
Self { status, location: None, body: body.to_owned() }
|
||||
}
|
||||
}
|
||||
|
||||
/// One request as the server saw it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Seen {
|
||||
pub method: String,
|
||||
pub path: String,
|
||||
pub authorization: Option<String>,
|
||||
}
|
||||
|
||||
/// Every request a fake server has seen, in order.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Asked(Arc<Mutex<Vec<Seen>>>);
|
||||
|
||||
impl Asked {
|
||||
pub fn seen(&self) -> Vec<Seen> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn paths(&self) -> Vec<String> {
|
||||
self.0.lock().unwrap().iter().map(|seen| seen.path.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers each request by its path from `routes`; a path it has no answer for is held open and never answered.
|
||||
pub fn forge_of<R: Into<Reply>>(routes: impl Fn(&str) -> Option<R> + Send + 'static) -> (String, Asked) {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let asked = Asked::default();
|
||||
let record = asked.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut held = Vec::new();
|
||||
for stream in listener.incoming() {
|
||||
let mut stream = stream.unwrap();
|
||||
let mut buffer = [0_u8; 4096];
|
||||
let read = stream.read(&mut buffer).unwrap();
|
||||
let request = String::from_utf8_lossy(&buffer[..read]).into_owned();
|
||||
let mut words = request.split_whitespace();
|
||||
let method = words.next().unwrap_or_default().to_owned();
|
||||
let path = words.next().unwrap_or_default().to_owned();
|
||||
let authorization = request
|
||||
.lines()
|
||||
.find_map(|line| line.split_once(':').filter(|(name, _)| name.eq_ignore_ascii_case("authorization")))
|
||||
.map(|(_, value)| value.trim().to_owned());
|
||||
record.0.lock().unwrap().push(Seen { method, path: path.clone(), authorization });
|
||||
match routes(&path).map(Into::into) {
|
||||
Some(Reply { status, location, body }) => {
|
||||
let location = location.map(|location| format!("location: {location}\r\n")).unwrap_or_default();
|
||||
write!(stream, "HTTP/1.1 {status} X\r\ncontent-type: application/json\r\n{location}content-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()).unwrap();
|
||||
}
|
||||
None => held.push(stream),
|
||||
}
|
||||
}
|
||||
});
|
||||
(base, asked)
|
||||
}
|
||||
|
|
@ -25,23 +25,23 @@ fn git_in(dir: &Path, args: &[&str]) -> String {
|
|||
}
|
||||
|
||||
/// A working repo on disk, committed to by the test.
|
||||
pub(super) struct Remote {
|
||||
struct Remote {
|
||||
dir: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Remote {
|
||||
pub(super) fn new() -> Self {
|
||||
fn new() -> Self {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
git_in(dir.path(), &["init", "--quiet", "-b", "main"]);
|
||||
Self { dir }
|
||||
}
|
||||
|
||||
pub(super) fn path(&self) -> PathBuf {
|
||||
fn path(&self) -> PathBuf {
|
||||
self.dir.path().to_path_buf()
|
||||
}
|
||||
|
||||
/// Writes files, removes paths, commits everything and returns the commit.
|
||||
pub(super) fn commit(&self, write: &[(&str, &[u8])], remove: &[&str]) -> String {
|
||||
fn commit(&self, write: &[(&str, &[u8])], remove: &[&str]) -> String {
|
||||
for (path, bytes) in write {
|
||||
let full = self.dir.path().join(path);
|
||||
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
|
||||
|
|
@ -56,13 +56,13 @@ impl Remote {
|
|||
}
|
||||
}
|
||||
|
||||
pub(super) struct FakeForge {
|
||||
struct FakeForge {
|
||||
repos: Vec<(SourceRepo, PathBuf)>,
|
||||
shortfall: Option<String>,
|
||||
}
|
||||
|
||||
impl FakeForge {
|
||||
pub(super) fn of(repos: &[(&str, &Remote)]) -> Self {
|
||||
fn of(repos: &[(&str, &Remote)]) -> Self {
|
||||
Self {
|
||||
repos: repos
|
||||
.iter()
|
||||
|
|
|
|||
|
|
@ -191,18 +191,12 @@ impl Drop for Daemon {
|
|||
}
|
||||
}
|
||||
|
||||
/// A test's name for someone as the Bifrost account id the door requires: a deterministic lowercase D-format UUID.
|
||||
fn acct(name: &str) -> huginn_mind::eureka_pipeline::AccountId {
|
||||
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
|
||||
huginn_mind::eureka_pipeline::AccountId(format!("{:08x}-{:04x}-4000-8000-{:012x}", hash >> 32, (hash >> 16) & 0xffff, hash & 0xffff_ffff_ffff))
|
||||
}
|
||||
|
||||
fn answer(who: &str, hash: &str, request_id: &str) -> DeskRequest {
|
||||
DeskRequest::Answer {
|
||||
mind: INSTANCE.into(),
|
||||
subject: acct(who),
|
||||
subject: short(who),
|
||||
authority: DeskAuthority::Operator,
|
||||
deciders: vec![acct(who)],
|
||||
deciders: vec![short(who)],
|
||||
request: ForkAnswerRequest {
|
||||
schema_version: RequestSchema::V0,
|
||||
fork_id: FORK.into(),
|
||||
|
|
@ -219,8 +213,8 @@ fn answer(who: &str, hash: &str, request_id: &str) -> DeskRequest {
|
|||
fn forks_request(who: &str, deciders: &[&str]) -> DeskRequest {
|
||||
DeskRequest::Forks {
|
||||
mind: INSTANCE.into(),
|
||||
subject: acct(who),
|
||||
deciders: deciders.iter().map(|d| acct(d)).collect(),
|
||||
subject: short(who),
|
||||
deciders: deciders.iter().map(|d| short(d)).collect(),
|
||||
status: None,
|
||||
cursor: None,
|
||||
limit: huginn_mind::desk_wire::ForkLimit::new(50).unwrap(),
|
||||
|
|
@ -283,21 +277,21 @@ fn the_binary_serves_both_doors_and_survives_restart() {
|
|||
let catalog = format!("{:?}", exchange(&desk, &framed(&catalog_request())).expect("a catalog"));
|
||||
assert!(catalog.contains("huginn.desk_request.v1") && catalog.contains("huginn.desk_response.v1"), "{catalog}");
|
||||
assert!(!catalog.contains("huginn.mind_request.v1"), "{catalog}");
|
||||
// The reads answer and store nothing; a decider reading its own list is told the ids.
|
||||
// The reads answer, store nothing, and carry the whole record to a subject the deciders do not name.
|
||||
let (list, listed_at) = match ask(&desk, "m-r1", &forks_request("x", &["x"])) {
|
||||
DeskResponse::Forks { list, as_of } => (list, as_of),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert_eq!((list.open_count, list.recorded_count, list.forks.len(), list.stamp.clone()), (1, 0, 1, format!("s{listed_at}")));
|
||||
assert_eq!(list.forks[0].card.options_hash, hash);
|
||||
let DeskResponse::Fork { entry, as_of } = ask(&desk, "m-r2", &DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("x"), deciders: vec![acct("x")], fork_id: FORK.into() })
|
||||
let DeskResponse::Fork { entry, as_of } = ask(&desk, "m-r2", &DeskRequest::Fork { mind: INSTANCE.into(), subject: short("x"), deciders: vec![short("x")], fork_id: FORK.into() })
|
||||
else {
|
||||
panic!("a read of the seeded fork")
|
||||
};
|
||||
assert_eq!((entry, as_of), (list.forks[0].clone(), listed_at));
|
||||
assert_eq!(daemon.documents(), seeded);
|
||||
// `authority` is no field of a read: the payload is refused whole and nothing is answered or stored.
|
||||
for (operation, request) in [("forks", forks_request("x", &["x"])), ("fork", DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("x"), deciders: vec![acct("x")], fork_id: FORK.into() })] {
|
||||
for (operation, request) in [("forks", forks_request("x", &["x"])), ("fork", DeskRequest::Fork { mind: INSTANCE.into(), subject: short("x"), deciders: vec![short("x")], fork_id: FORK.into() })] {
|
||||
let mut value = serde_json::to_value(&request).unwrap();
|
||||
let variant = if operation == "forks" { "Forks" } else { "Fork" };
|
||||
value[variant]["authority"] = serde_json::json!("Operator");
|
||||
|
|
@ -325,20 +319,15 @@ fn the_binary_serves_both_doors_and_survives_restart() {
|
|||
assert_eq!((stale.code, counted_answer_id.as_deref()), (Some(ForkAnswerCode::StaleFork), Some("n1")));
|
||||
let stored = daemon.documents();
|
||||
assert_eq!(stored, seeded + 2);
|
||||
// A subject the call's deciders do not name is a non-decider: the fork is unlisted, so it reads as a missing one.
|
||||
let outsider = ask(&desk, "m-r3", &DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("outsider"), deciders: vec![acct("y")], fork_id: FORK.into() });
|
||||
assert!(matches!(outsider, DeskResponse::NotStored(ref refusal) if refusal.code == huginn_mind::desk_wire::ForkRefusalCode::ForkUnknown), "{outsider:?}");
|
||||
// A decider reads both answers, the first with its choice and the stale one with its code, and is told who answered.
|
||||
// A subject the call's deciders do not name reads both answers, the first with its choice and the stale one with its code.
|
||||
let DeskResponse::Fork { entry, .. } =
|
||||
ask(&desk, "m-r4", &DeskRequest::Fork { mind: INSTANCE.into(), subject: acct("y"), deciders: vec![acct("y")], fork_id: FORK.into() })
|
||||
ask(&desk, "m-r3", &DeskRequest::Fork { mind: INSTANCE.into(), subject: short("outsider"), deciders: vec![short("y")], fork_id: FORK.into() })
|
||||
else {
|
||||
panic!("a read")
|
||||
};
|
||||
let seen: Vec<_> = entry.record.answers.iter().map(|answer| (answer.answer_id.as_str(), answer.answerer.as_deref(), answer.code)).collect();
|
||||
let x = acct("x").0;
|
||||
assert_eq!(seen, [("n1", Some(x.as_str()), None), ("n2", Some(x.as_str()), Some(ForkAnswerCode::StaleFork))]);
|
||||
assert_eq!((entry.record.counted_answer_id.as_deref(), entry.record.answerer_count), (Some("n1"), 1));
|
||||
assert_eq!((entry.card.deciders.as_slice(), entry.card.decider_count), (&[acct("y").0][..], 1));
|
||||
let seen: Vec<_> = entry.record.answers.iter().map(|answer| (answer.answer_id.as_str(), answer.answerer.as_str(), answer.code)).collect();
|
||||
assert_eq!(seen, [("n1", "x", None), ("n2", "x", Some(ForkAnswerCode::StaleFork))]);
|
||||
assert_eq!((entry.record.counted_answer_id.as_deref(), entry.card.deciders.as_slice()), (Some("n1"), ["y".to_string()].as_slice()));
|
||||
assert_eq!(daemon.documents(), stored);
|
||||
|
||||
// A stop takes the socket with it; the stored answers are the retry's memory.
|
||||
|
|
@ -549,13 +538,13 @@ fn a_busy_pass_is_not_followed_by_the_idle_sleep() {
|
|||
];
|
||||
let options = parse_options(args.iter().map(|arg| arg.to_string())).unwrap();
|
||||
let embedder = pool(&options.ollama_urls, &options.reserve_ollama_urls, &options.embedding_model);
|
||||
let Started { mut daemon, mut hub, persona: _, registry, desk: mut door } =
|
||||
let Started { mut daemon, mut hub, registry, desk: mut door } =
|
||||
startup(&options, embedder, QdrantIndex::new(&options.qdrant_url), Backoff::default()).unwrap();
|
||||
let stopping = Arc::new(AtomicBool::new(false));
|
||||
let loop_stopping = Arc::clone(&stopping);
|
||||
let serving = std::thread::spawn(move || {
|
||||
let serve = ServeOptions { idle_sleep: Duration::from_millis(600), ..ServeOptions::default() };
|
||||
run(&mut daemon, &mut hub, None, ®istry, door.as_mut(), &loop_stopping, &serve)
|
||||
run(&mut daemon, &mut hub, ®istry, door.as_mut(), &loop_stopping, &serve)
|
||||
});
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
let frame = framed(&catalog_request());
|
||||
|
|
@ -590,7 +579,7 @@ fn forks_page(who: &str, cursor: Option<&str>) -> DeskRequest {
|
|||
}
|
||||
|
||||
fn fork_read(who: &str, fork_id: &str) -> DeskRequest {
|
||||
DeskRequest::Fork { mind: INSTANCE.into(), subject: acct(who), deciders: vec![acct(who)], fork_id: fork_id.into() }
|
||||
DeskRequest::Fork { mind: INSTANCE.into(), subject: short(who), deciders: vec![short(who)], fork_id: fork_id.into() }
|
||||
}
|
||||
|
||||
/// The wire spelling of a not-stored refusal's code, and its text.
|
||||
|
|
|
|||
|
|
@ -62,18 +62,12 @@ pub(crate) enum Door {
|
|||
Desk,
|
||||
}
|
||||
|
||||
/// The door split. Every staged `desk_answer`, whether the caller sent it or a derivation produced it,
|
||||
/// is refused unless it came by the desk door; and a staged `desk_listing` is refused if it came by the
|
||||
/// desk door: listing is the Mind's own act, on the Admit door, with a receipt saying who.
|
||||
fn refuse_documents_at_the_wrong_door(door: Door, docs: &Docs<'_>) -> Result<(), MindRefusal> {
|
||||
match docs.batch.iter().find(|staged| match staged.kind {
|
||||
PipelineKind::DeskAnswer => door != Door::Desk,
|
||||
PipelineKind::DeskListing => door == Door::Desk,
|
||||
_ => false,
|
||||
}) {
|
||||
Some(staged) if staged.kind == PipelineKind::DeskListing => Err(MindRefusal::DeskRequestInvalid { field: "desk_listing".into() }),
|
||||
Some(staged) => Err(MindRefusal::DeskAnswerOutsideDesk { id: staged.key.clone() }),
|
||||
None => Ok(()),
|
||||
/// Every staged `desk_answer`, whether the caller sent it or a derivation
|
||||
/// produced it, is refused unless it came by the desk door.
|
||||
fn refuse_desk_answers_outside_desk(door: Door, docs: &Docs<'_>) -> Result<(), MindRefusal> {
|
||||
match docs.batch.iter().find(|staged| staged.kind == PipelineKind::DeskAnswer) {
|
||||
Some(staged) if door != Door::Desk => Err(MindRefusal::DeskAnswerOutsideDesk { id: staged.key.clone() }),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -166,7 +160,7 @@ impl<S: MindStore> Mind<S> {
|
|||
for envelope in envelopes {
|
||||
docs.push(stage(envelope, &mind)?)?;
|
||||
}
|
||||
refuse_documents_at_the_wrong_door(door, &docs)?;
|
||||
refuse_desk_answers_outside_desk(door, &docs)?;
|
||||
// A6
|
||||
let carries_instance = docs.batch.iter().filter(|staged| staged.kind == PipelineKind::Instance).count() == 1;
|
||||
if self.is_empty() && !carries_instance {
|
||||
|
|
@ -190,7 +184,7 @@ impl<S: MindStore> Mind<S> {
|
|||
docs.push(stage(envelope, &mind)?)?;
|
||||
}
|
||||
}
|
||||
refuse_documents_at_the_wrong_door(door, &docs)?;
|
||||
refuse_desk_answers_outside_desk(door, &docs)?;
|
||||
for staged in &docs.batch[originals..] {
|
||||
resolve(&docs, staged, &mind, external, &mut strong)?;
|
||||
}
|
||||
|
|
@ -268,9 +262,17 @@ impl<S: MindStore> Mind<S> {
|
|||
if self.is_empty() {
|
||||
return Err(MindRefusal::MissingIdentity);
|
||||
}
|
||||
// P1 to P3: the document alone, the one check an offline reader of a state file shares.
|
||||
// P1
|
||||
persona::validate_shape(&state)?;
|
||||
// P2
|
||||
let mind = self.instance().clone();
|
||||
persona::validate_document(&mind, &state)?;
|
||||
if state.get("personaId").and_then(Value::as_str) != Some(mind.0.as_str()) {
|
||||
return Err(MindRefusal::PersonaForeign { instance: mind.0 });
|
||||
}
|
||||
// P3
|
||||
if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") {
|
||||
return Err(MindRefusal::PersonaNotCanonical);
|
||||
}
|
||||
// P4
|
||||
let stored = self.stored_updated_at()?;
|
||||
if stored != expected_updated_at {
|
||||
|
|
@ -625,9 +627,6 @@ fn check(docs: &Docs<'_>, staged: &Staged, mind: &Slug, import: Option<&ImportSo
|
|||
}
|
||||
// Decided in `answer_desk` before the document exists; no other door can stage one.
|
||||
D::DeskAnswer(_) => Ok(()),
|
||||
// The question is a citation (`listed`), so a missing one is refused with every other missing referent, and
|
||||
// the key derivation holds it to the listing's own campaign.
|
||||
D::DeskListing(_) => Ok(()),
|
||||
D::Ruling(ruling) => {
|
||||
if ruling.operator_quote.is_some() && ruling.authority != RulingAuthority::Operator {
|
||||
return Err(MindRefusal::QuoteWithoutOperator { ruling: key.into() });
|
||||
|
|
@ -663,7 +662,7 @@ fn check(docs: &Docs<'_>, staged: &Staged, mind: &Slug, import: Option<&ImportSo
|
|||
return Err(MindRefusal::RepoNotInCampaign { repo: spec.repo.0.clone() });
|
||||
}
|
||||
for ruling in &spec.rulings {
|
||||
if !(docs.in_force(K::Ruling, &ruling.0) || historic && root_and_local(&ruling.0).0 != root) {
|
||||
if !(historic && root_and_local(&ruling.0).0 != root) && !docs.in_force(K::Ruling, &ruling.0) {
|
||||
return Err(MindRefusal::CitesResolvedDocument { kind: K::Ruling, id: ruling.0.clone() });
|
||||
}
|
||||
}
|
||||
|
|
@ -906,7 +905,6 @@ fn matrix(subject: PipelineKind, outcome: &ResolutionOutcome) -> bool {
|
|||
(K::Target, O::Superseded { by }) => all(by, K::Target),
|
||||
(K::Question, O::Answered { by }) => by.kind == K::Ruling,
|
||||
(K::Question, O::Withdrawn { .. }) => true,
|
||||
(K::DeskListing, O::Withdrawn { .. }) => true,
|
||||
(K::Ruling, O::Superseded { by }) => all(by, K::Ruling),
|
||||
(K::CutSpec, O::Superseded { by }) => all(by, K::CutSpec),
|
||||
(K::CutSpec, O::Withdrawn { .. }) => true,
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@
|
|||
|
||||
use chrono::{DateTime, Duration, SecondsFormat, SubsecRound, Utc};
|
||||
use eureka_pipeline::{
|
||||
AccountId,
|
||||
DeskAuthority, DeskOutcome, DeskRefusal, PipelineDeskAnswer, PipelineDocument, PipelineKind, PipelineQuestion, PipelineRefusal,
|
||||
PipelineResolution, RequestId, ResolutionOutcome, Sha256Hex, Short, Slug, Words,
|
||||
};
|
||||
|
|
@ -146,7 +145,7 @@ fn counts_under(answer: &PipelineDeskAnswer, current: &Sha256Hex) -> bool {
|
|||
/// `answer_desk` runs before it reads the fork and the door runs before its showability gate.
|
||||
pub(crate) fn bound_answer<'a>(docs: &'a Docs<'_>, answerer: &Short, request_id: &RequestId) -> Option<(&'a str, &'a PipelineDeskAnswer)> {
|
||||
docs.of_kind(PipelineKind::DeskAnswer).find_map(|(key, document)| match document {
|
||||
PipelineDocument::DeskAnswer(held) if held.answerer.0 == answerer.0 && held.request_id == *request_id => Some((key, held)),
|
||||
PipelineDocument::DeskAnswer(held) if held.answerer == *answerer && held.request_id == *request_id => Some((key, held)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
|
@ -315,7 +314,7 @@ impl<S: MindStore> Mind<S> {
|
|||
claim_in_future,
|
||||
request_id: request.request_id.clone(),
|
||||
body_sha256: body_sha256.clone(),
|
||||
answerer: AccountId(stamp.answerer.0.clone()),
|
||||
answerer: stamp.answerer.clone(),
|
||||
authority: stamp.authority,
|
||||
outcome,
|
||||
};
|
||||
|
|
@ -426,7 +425,7 @@ mod tests {
|
|||
const LIST: [&str; 6] = ["x", "y", "z", "a", "op", "dec"];
|
||||
|
||||
fn stamp_as(who: &str, authority: DeskAuthority, list: &[&str]) -> DeskStamp {
|
||||
DeskStamp { answerer: account(who), authority, deciders: list.iter().map(|id| account(id)).collect() }
|
||||
DeskStamp { answerer: s(who), authority, deciders: list.iter().map(|id| s(id)).collect() }
|
||||
}
|
||||
|
||||
fn decider(who: &str) -> DeskStamp {
|
||||
|
|
@ -532,7 +531,7 @@ mod tests {
|
|||
let mut mind = desk();
|
||||
stored(ask(&mut mind, &decider("z"), pick(FORK, "Q1", "A", "2026-11-10T12:00:00Z")));
|
||||
stored(ask(&mut mind, &decider("a"), pick(FORK, "Q1", "A", "2026-11-10T12:00:00Z")));
|
||||
assert_eq!(held(&mind, &counted(&mind, FORK).unwrap()).answerer, acct("z"));
|
||||
assert_eq!(held(&mind, &counted(&mind, FORK).unwrap()).answerer, s("z"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -781,7 +780,7 @@ mod tests {
|
|||
let record = held(&mind, &answer);
|
||||
assert_eq!(record.outcome, outcome);
|
||||
assert_eq!(outcome, DeskOutcome::Refused { code: DeskRefusal::NotADecider, retracts: None });
|
||||
assert_eq!((record.answerer, record.authority, record.answered_at), (acct("guest"), DeskAuthority::Steward, s(at)));
|
||||
assert_eq!((record.answerer, record.authority, record.answered_at), (s("guest"), DeskAuthority::Steward, s(at)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -791,7 +790,7 @@ mod tests {
|
|||
for (who, authority) in [("op", DeskAuthority::Operator), ("dec", DeskAuthority::Steward), ("x", DeskAuthority::Member)] {
|
||||
let (answer, _) = stored(ask(&mut mind, &stamp_as(who, authority, &LIST), pick(FORK, "Q1", "A", at)));
|
||||
let record = held(&mind, &answer);
|
||||
assert_eq!((record.answerer, record.authority), (acct(who), authority));
|
||||
assert_eq!((record.answerer, record.authority), (s(who), authority));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -937,7 +936,7 @@ mod tests {
|
|||
assert_eq!(counted(&mind, FORK), Some(answer));
|
||||
}
|
||||
|
||||
/// Libby's vectors (CultLib d3025d3c, `contracts/cultnet/governance/fork-card-vectors.json`, the `optionsHash` array):
|
||||
/// Libby's vectors (CultLib 6231ecad, `contracts/cultnet/governance/fork-card-vectors.json`, the `optionsHash` array):
|
||||
/// the seven of the binding file, A to G, and the eight she adds. Each is recomputed from its shown members.
|
||||
fn vectors() -> Vec<serde_json::Value> {
|
||||
let file: serde_json::Value = serde_json::from_str(include_str!("../vectors/fork-card-vectors.json")).unwrap();
|
||||
|
|
@ -1040,7 +1039,7 @@ mod tests {
|
|||
let DeskAnswerOutcome::Stored { receipt_id, .. } = outcome else { panic!("{outcome:?}") };
|
||||
let receipt = mind.receipts().unwrap().into_iter().find(|receipt| receipt.receipt_id == receipt_id).unwrap();
|
||||
assert_eq!(receipt.provenance.faculty, faculty, "{authority:?}");
|
||||
assert_eq!(receipt.provenance.agent, account("x"));
|
||||
assert_eq!(receipt.provenance.agent, s("x"));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1207,10 +1206,10 @@ mod tests {
|
|||
let image = first.image().unwrap();
|
||||
let found = Docs::at(image, image.head).find(K::DeskAnswer, &key("Q1", 1)).cloned();
|
||||
let Some(PipelineDocument::DeskAnswer(mut held)) = found else { panic!("stored") };
|
||||
held.answerer = eureka_pipeline::AccountId(long.clone());
|
||||
held.answerer = s(&long);
|
||||
store.plant(PipelineDocument::DeskAnswer(held).prepare(&cache).unwrap());
|
||||
let mut mind = opened(store, INSTANCE);
|
||||
let stamp = DeskStamp { answerer: s(&long), ..stamp_as("x", DeskAuthority::Member, &LIST) };
|
||||
let stamp = stamp_as(&long, DeskAuthority::Member, &LIST);
|
||||
let before = head(&mind);
|
||||
assert_eq!(replayed(ask(&mut mind, &stamp, request)), (key("Q1", 1), DeskOutcome::Counted));
|
||||
assert_eq!(head(&mind), before);
|
||||
|
|
@ -1263,8 +1262,8 @@ mod tests {
|
|||
assert_eq!(stored(ask(&mut mind, &decider("x"), sent.clone())), (key("Q1", 1), DeskOutcome::Counted));
|
||||
let (y_answer, y_outcome) = stored(ask(&mut mind, &decider("y"), sent.clone()));
|
||||
assert_eq!((y_answer.as_str(), &y_outcome), (key("Q1", 2).as_str(), &DeskOutcome::Revision { of: s(&key("Q1", 1)) }));
|
||||
assert_eq!(held(&mind, &y_answer).answerer, acct("y"));
|
||||
assert_eq!(held(&mind, &key("Q1", 1)).answerer, acct("x"));
|
||||
assert_eq!(held(&mind, &y_answer).answerer, s("y"));
|
||||
assert_eq!(held(&mind, &key("Q1", 1)).answerer, s("x"));
|
||||
// x's later retry still returns n1; y's returns n2.
|
||||
assert_eq!(replayed(ask(&mut mind, &decider("x"), sent.clone())).0, key("Q1", 1));
|
||||
assert_eq!(replayed(ask(&mut mind, &decider("y"), sent)).0, key("Q1", 2));
|
||||
|
|
@ -1468,7 +1467,7 @@ mod tests {
|
|||
let before = head(&mind);
|
||||
let id = request.request_id.clone();
|
||||
let (answer, outcome) = stored(ask(&mut mind, &decider("y"), request.clone()));
|
||||
assert_eq!(outcome, DeskOutcome::Refused { code: DeskRefusal::BadRetraction, retracts: sent.2.map(s) }, "{what}");
|
||||
assert_eq!(outcome, DeskOutcome::Refused { code: DeskRefusal::BadRetraction, retracts: sent.2.map(|target| s(target)) }, "{what}");
|
||||
assert_eq!(head(&mind), before + 1, "{what} is stored");
|
||||
// The record keeps what was sent: the choice, the note and the target it named.
|
||||
let record = held(&mind, &answer);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! The fork desk's answer wire, Huginn's half: Libby's answer-side documents
|
||||
//! (CultLib `contracts/cultnet/governance/`, the contract file and its vectors at d3025d3c)
|
||||
//! (CultLib `contracts/cultnet/governance/`, the contract file and its vectors at e57fbaee)
|
||||
//! as Rust types, the one conversion between her `n<seq>` answer ids and the
|
||||
//! record keys, the projection of a stored answer, the refusal mapping and the
|
||||
//! showability predicate, and `Mind::desk_answer`, the one call that runs them in order.
|
||||
|
|
@ -20,7 +20,7 @@ pub use reads::{CardSchema, CardStatus, EntrySchema, ForkCard, ForkCursor, ForkE
|
|||
|
||||
use chrono::{DateTime, Utc};
|
||||
use eureka_pipeline::{
|
||||
AccountId, DeskAuthority, DeskOutcome, DeskRefusal, PipelineDeskAnswer, PipelineDocument, PipelineKind, PipelineQuestion, RequestId, Sha256Hex, Short, Slug, Words,
|
||||
DeskAuthority, DeskOutcome, DeskRefusal, PipelineDeskAnswer, PipelineDocument, PipelineKind, PipelineQuestion, RequestId, Sha256Hex, Short, Slug, Words,
|
||||
};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
@ -147,10 +147,7 @@ pub struct ForkDeskAnswer {
|
|||
pub answered_at: String,
|
||||
pub received_at: String,
|
||||
pub claim_in_future: bool,
|
||||
/// The answering account, or nil in a non-decider's view (the key is kept). A stored answer always has one.
|
||||
#[serde(deserialize_with = "required")]
|
||||
#[schemars(required)]
|
||||
pub answerer: Option<String>,
|
||||
pub answerer: String,
|
||||
pub authority: DeskAuthority,
|
||||
pub request_id: String,
|
||||
}
|
||||
|
|
@ -183,12 +180,12 @@ pub struct ForkRefusal {
|
|||
/// `Refused` is any other Mind refusal; an `Unavailable` is Bifrost's to turn into its 503, and
|
||||
/// Huginn writes no document for it.
|
||||
///
|
||||
/// The trust boundary of the reads (ruling `desk-read-visibility-withheld-ids`): `Forks` and `Fork`
|
||||
/// carry every answer's note, to whatever the peer-checked socket carries; Bifrost strips notes
|
||||
/// at its door (a stripped read serves `note: null`, CultLib `fork-card.md`). Huginn itself
|
||||
/// withholds the account ids from a reader who is not a decider (`deciders` empty, `answerer` nil,
|
||||
/// counts in their place). Huginn must be reachable only by Bifrost's peer-checked socket: the
|
||||
/// peer-uid check IS the whole authentication, and a second reader of that socket is a note leak.
|
||||
/// The trust boundary of the reads (ruling `desk-read-visibility-whole-record`): `Forks` and `Fork`
|
||||
/// carry the WHOLE record, every answer's note included, to whatever the peer-checked socket
|
||||
/// carries. Huginn strips nothing and gates nothing; Bifrost applies visibility at its door (a
|
||||
/// stripped read serves `note: null`, CultLib `fork-card.md`). Huginn must therefore be reachable
|
||||
/// only by Bifrost's peer-checked socket: the peer-uid check IS the whole authentication, and a
|
||||
/// second reader of that socket is a note leak.
|
||||
// One value per call, built and encoded once; a box would only add a deref to every reader.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
|
|
@ -232,33 +229,18 @@ pub const DESK_PAGE_BUDGET: usize = DESK_MAX_RESPONSE_BYTES - DESK_ENVELOPE_MARG
|
|||
/// Most deciders one call carries (CultLib `card.deciders` `maxItems`).
|
||||
pub const DESK_DECIDERS_MAX: usize = 64;
|
||||
|
||||
/// An account id read from the wire: a lowercase D-format UUID, or the decoder's refusal, which names the
|
||||
/// field and never quotes the value.
|
||||
fn account_id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<AccountId, D::Error> {
|
||||
let id = AccountId(String::deserialize(deserializer)?);
|
||||
id.validate_account().map_err(|_| serde::de::Error::custom("not an account id: a lowercase D-format UUID"))?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// A decider list, read whole or not at all: one to `DESK_DECIDERS_MAX` account ids, none twice. A
|
||||
/// bad list is the decoder's refusal, which names the field and never quotes an id.
|
||||
fn deciders<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<AccountId>, D::Error> {
|
||||
/// A decider list, read whole or not at all: one to `DESK_DECIDERS_MAX` subjects, none twice. A
|
||||
/// bad list is the decoder's refusal, which names the field and never quotes a subject.
|
||||
fn deciders<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<Short>, D::Error> {
|
||||
struct List;
|
||||
/// One list entry, through the same grammar as `subject`.
|
||||
struct Account(AccountId);
|
||||
impl<'de> Deserialize<'de> for Account {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
account_id(deserializer).map(Self)
|
||||
}
|
||||
}
|
||||
impl<'de> serde::de::Visitor<'de> for List {
|
||||
type Value = Vec<AccountId>;
|
||||
type Value = Vec<Short>;
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("a list of distinct deciders")
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<AccountId>, A::Error> {
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<Short>, A::Error> {
|
||||
let mut list = Vec::new();
|
||||
while let Some(Account(subject)) = seq.next_element::<Account>()? {
|
||||
while let Some(subject) = seq.next_element::<Short>()? {
|
||||
if list.len() == DESK_DECIDERS_MAX {
|
||||
return Err(serde::de::Error::custom("too many deciders"));
|
||||
}
|
||||
|
|
@ -279,7 +261,7 @@ fn deciders<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<Acc
|
|||
fn deciders_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
schemars::json_schema!({
|
||||
"type": "array",
|
||||
"items": generator.subschema_for::<AccountId>(),
|
||||
"items": generator.subschema_for::<Short>(),
|
||||
"minItems": 1,
|
||||
"maxItems": DESK_DECIDERS_MAX,
|
||||
"uniqueItems": true
|
||||
|
|
@ -293,33 +275,31 @@ fn deciders_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schem
|
|||
/// the set refuses the whole payload.
|
||||
///
|
||||
/// The reads, `Forks` and `Fork`, carry NO `authority` (CultLib `list_request` and
|
||||
/// `read_request` are closed and have none; one that names it is refused whole). Their `deciders`
|
||||
/// feed the showability gate, and `subject` decides the view: a subject in `deciders` is a decider,
|
||||
/// sees every showable fork and is told the ids; any other reads only the forks the Mind lists
|
||||
/// (a `desk_listing` in force) and is told counts in the ids' place. `Forks` takes the contract's `list_request` fields flat
|
||||
/// beside them (`status`, `cursor`, `limit`), each key written, `null` where absent. Bifrost
|
||||
/// strips notes; see `DeskResponse` for the trust boundary. These docs and the doc of `Mind::desk_forks`/`Mind::desk_fork` are the
|
||||
/// `read_request` are closed and have none; one that names it is refused whole). Their `subject`
|
||||
/// and `deciders` gate nothing: `deciders` only fills the card's `deciders` and the showability
|
||||
/// gate, `subject` is read by no read. `Forks` takes the contract's `list_request` fields flat
|
||||
/// beside them (`status`, `cursor`, `limit`), each key written, `null` where absent. Huginn
|
||||
/// answers every read with the whole record and Bifrost applies visibility; see `DeskResponse`
|
||||
/// for the trust boundary. These docs and the doc of `Mind::desk_forks`/`Mind::desk_fork` are the
|
||||
/// reads spec.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum DeskRequest {
|
||||
Answer {
|
||||
mind: Slug,
|
||||
#[serde(deserialize_with = "account_id")]
|
||||
subject: AccountId,
|
||||
subject: Short,
|
||||
authority: DeskAuthority,
|
||||
#[serde(deserialize_with = "deciders")]
|
||||
#[schemars(schema_with = "deciders_schema")]
|
||||
deciders: Vec<AccountId>,
|
||||
deciders: Vec<Short>,
|
||||
request: ForkAnswerRequest,
|
||||
},
|
||||
Forks {
|
||||
mind: Slug,
|
||||
#[serde(deserialize_with = "account_id")]
|
||||
subject: AccountId,
|
||||
subject: Short,
|
||||
#[serde(deserialize_with = "deciders")]
|
||||
#[schemars(schema_with = "deciders_schema")]
|
||||
deciders: Vec<AccountId>,
|
||||
deciders: Vec<Short>,
|
||||
#[serde(deserialize_with = "required")]
|
||||
#[schemars(required)]
|
||||
status: Option<ListStatus>,
|
||||
|
|
@ -330,11 +310,10 @@ pub enum DeskRequest {
|
|||
},
|
||||
Fork {
|
||||
mind: Slug,
|
||||
#[serde(deserialize_with = "account_id")]
|
||||
subject: AccountId,
|
||||
subject: Short,
|
||||
#[serde(deserialize_with = "deciders")]
|
||||
#[schemars(schema_with = "deciders_schema")]
|
||||
deciders: Vec<AccountId>,
|
||||
deciders: Vec<Short>,
|
||||
fork_id: String,
|
||||
},
|
||||
}
|
||||
|
|
@ -356,7 +335,7 @@ impl DeskRequest {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn deciders(&self) -> &[AccountId] {
|
||||
pub fn deciders(&self) -> &[Short] {
|
||||
match self {
|
||||
Self::Answer { deciders, .. } | Self::Forks { deciders, .. } | Self::Fork { deciders, .. } => deciders,
|
||||
}
|
||||
|
|
@ -480,7 +459,7 @@ fn project(key: &str, stored: &PipelineDeskAnswer) -> Result<ForkDeskAnswer, Min
|
|||
answered_at: stored.answered_at.0.clone(),
|
||||
received_at: stored.received_at.0.clone(),
|
||||
claim_in_future: stored.claim_in_future,
|
||||
answerer: Some(stored.answerer.0.clone()),
|
||||
answerer: stored.answerer.0.clone(),
|
||||
authority: stored.authority,
|
||||
request_id: stored.request_id.0.clone(),
|
||||
})
|
||||
|
|
@ -549,13 +528,10 @@ impl<S: MindStore> Mind<S> {
|
|||
};
|
||||
let image = self.image()?;
|
||||
let docs = Docs::at(image, image.head);
|
||||
// A fork this reader may not see is unshowable here too, by the read side's own `visible`: the answer path
|
||||
// must not tell a hidden fork from a missing one, nor store a refusal for it. A request already stored replays
|
||||
// whatever the decider list is now (the lookup is `answer_desk`'s, asked here only so `showable` does not
|
||||
// shadow it), but never to a reader who can no longer see the fork: the counted answer id and `as_of` it
|
||||
// would carry are the fork's current state, so that replay is `fork_unknown` too (ruling clause 3).
|
||||
let replay = bound_answer(&docs, &subject, &sent.request_id).is_some();
|
||||
let unshowable = matches!(docs.find(PipelineKind::Question, &sent.fork.0), Some(PipelineDocument::Question(question)) if (!replay && !showable(question, deciders)) || !reads::visible(&docs, &sent.fork.0, deciders.contains(&subject)));
|
||||
// A request already stored replays whatever the list is now: the lookup is `answer_desk`'s,
|
||||
// asked here only so the gate does not shadow it.
|
||||
let unshowable = bound_answer(&docs, &subject, &sent.request_id).is_none()
|
||||
&& matches!(docs.find(PipelineKind::Question, &sent.fork.0), Some(PipelineDocument::Question(question)) if !showable(question, deciders));
|
||||
if unshowable {
|
||||
return Ok(DeskResponse::NotStored(fork_unknown()));
|
||||
}
|
||||
|
|
@ -569,7 +545,7 @@ impl<S: MindStore> Mind<S> {
|
|||
let Some(PipelineDocument::DeskAnswer(stored)) = docs.find(PipelineKind::DeskAnswer, &key) else { return Err(unreadable_key()) };
|
||||
let fork = stored.fork.0.as_str();
|
||||
let counted_answer_id = counted_answer(&docs, fork).map(|counted| answer_seq(fork, &counted).map(n_text).ok_or_else(unreadable_key)).transpose()?;
|
||||
Ok(DeskResponse::Answered { answer: project(&key, stored)?, counted_answer_id, as_of: image.head })
|
||||
Ok((DeskResponse::Answered { answer: project(&key, stored)?, counted_answer_id, as_of: image.head }))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -590,7 +566,7 @@ mod tests {
|
|||
const LIST: [&str; 4] = ["x", "y", "z", "op"];
|
||||
const AT: &str = "2026-11-10T12:00:00Z";
|
||||
|
||||
// ---- Libby's vectors: CultLib d3025d3c, `contracts/cultnet/governance/fork-card-vectors.json` ----
|
||||
// ---- Libby's vectors: CultLib 6231ecad, `contracts/cultnet/governance/fork-card-vectors.json` ----
|
||||
|
||||
fn vectors() -> Value {
|
||||
serde_json::from_str(include_str!("../vectors/fork-card-vectors.json")).unwrap()
|
||||
|
|
@ -619,11 +595,6 @@ mod tests {
|
|||
fn desk() -> Mind<MemoryStore> {
|
||||
let mut mind = seeded();
|
||||
committed(admit(&mut mind, vec![question_n(1), question_n(2)]));
|
||||
// Listed, so a reader who is not a decider reaches them (an unlisted fork is the reads' own tests').
|
||||
for fork in [FORK, FORK2] {
|
||||
let listing = D::DeskListing(eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: s(fork), reason: "Listed.".into() });
|
||||
committed(admit(&mut mind, vec![listing]));
|
||||
}
|
||||
mind
|
||||
}
|
||||
|
||||
|
|
@ -659,14 +630,14 @@ mod tests {
|
|||
}
|
||||
|
||||
fn deciders(list: &[&str]) -> Vec<Short> {
|
||||
list.iter().map(|who| account(who)).collect()
|
||||
list.iter().map(|who| s(who)).collect()
|
||||
}
|
||||
|
||||
/// The response and whether the call committed anything: a replay, a refused body and a gate
|
||||
/// refusal store nothing, so the head does not move.
|
||||
fn ask_as(mind: &mut Mind<MemoryStore>, who: &str, list: &[&str], request: ForkAnswerRequest) -> (DeskResponse, bool) {
|
||||
let before = head(mind);
|
||||
let response = mind.desk_answer(&deciders(list), account(who), DeskAuthority::Member, request, now());
|
||||
let response = mind.desk_answer(&deciders(list), s(who), DeskAuthority::Member, request, now());
|
||||
(response, head(mind) != before)
|
||||
}
|
||||
|
||||
|
|
@ -805,8 +776,7 @@ mod tests {
|
|||
claim_in_future: message["claim_in_future"].as_bool().unwrap(),
|
||||
request_id: RequestId(text("request_id").unwrap()),
|
||||
body_sha256: Sha256Hex("0".repeat(64)),
|
||||
// A withheld vector names no answerer: store a placeholder, the vector is the non-decider's view of it.
|
||||
answerer: AccountId(text("answerer").unwrap_or_else(|| "e0d1c2b3-a495-4687-8879-6a5b4c3d2e1f".into())),
|
||||
answerer: Short(text("answerer").unwrap()),
|
||||
authority,
|
||||
outcome,
|
||||
};
|
||||
|
|
@ -817,14 +787,10 @@ mod tests {
|
|||
fn stored_answers_project_to_the_desk_answer_vectors() {
|
||||
let file = vectors();
|
||||
let valid = rows(&file["deskAnswer"]["valid"]);
|
||||
assert_eq!(valid.len(), 8);
|
||||
assert_eq!(valid.len(), 5);
|
||||
for (name, message, bytes) in &valid {
|
||||
let (key, stored) = stored_from(message);
|
||||
let mut projected = project(&key, &stored).unwrap();
|
||||
// A null answerer is a non-decider's view of the stored answer.
|
||||
if message["answerer"].is_null() {
|
||||
projected.answerer = None;
|
||||
}
|
||||
let projected = project(&key, &stored).unwrap();
|
||||
assert_eq!(&encode(&projected), bytes, "{name}");
|
||||
}
|
||||
// Each answer inside her results is the projection of an equivalent record too.
|
||||
|
|
@ -1313,54 +1279,6 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
/// Ruling clause 3: a stored request replays whatever the decider list is now, but never to a reader who can no
|
||||
/// longer see the fork. The replay would carry the fork's current counted answer id and head, so it is the same
|
||||
/// bytes a missing fork answers with; the stored word itself comes back once the fork is listed again.
|
||||
#[test]
|
||||
fn a_stored_answer_does_not_replay_to_a_reader_who_can_no_longer_see_the_fork() {
|
||||
let mut mind = desk();
|
||||
let hash = hash_of(&mind, FORK);
|
||||
// Dan is not a decider: his answer to the listed fork is a stored refusal and counts nothing.
|
||||
let dan_request = wire(FORK, &hash);
|
||||
let (first, wrote) = ask(&mut mind, "d", dan_request.clone());
|
||||
let (refused, counted, _) = answered(first);
|
||||
assert!((wrote, refused.outcome.as_str(), refused.code.is_some(), counted) == (true, "Refused", true, None), "{refused:?}");
|
||||
// A decider answers, so the fork now has a counted answer a replay could name.
|
||||
let x_request = wire(FORK, &hash);
|
||||
let (counted_by_x, _) = ask(&mut mind, "x", x_request.clone());
|
||||
assert!(answered(counted_by_x).1.is_some());
|
||||
// Still listed: the replay is the stored word, with the fork's current state.
|
||||
let before = head(&mind);
|
||||
let (listed_replay, wrote) = ask(&mut mind, "d", dan_request.clone());
|
||||
assert!(!wrote);
|
||||
let (_, counted, as_of) = answered(listed_replay);
|
||||
assert_eq!((counted.is_some(), as_of), (true, before));
|
||||
// Unlisted: the replay is fork_unknown, byte for byte a fork that does not exist, and writes nothing.
|
||||
let withdrawal = crate::fixtures::resolution_n(
|
||||
eureka_pipeline::PipelineRef { kind: PipelineKind::DeskListing, id: s("eureka-state:desk_listing:Q1") },
|
||||
1,
|
||||
eureka_pipeline::ResolutionOutcome::Withdrawn { reason: "unlisted".into() },
|
||||
);
|
||||
let withdrawal_key = eureka_pipeline::pipeline_key(&withdrawal).unwrap();
|
||||
committed(admit(&mut mind, vec![withdrawal]));
|
||||
let before = head(&mind);
|
||||
let (hidden, wrote) = ask(&mut mind, "d", dan_request.clone());
|
||||
assert!(!wrote);
|
||||
let (missing, _) = ask(&mut mind, "d", ForkAnswerRequest { fork_id: "eureka-state:question:Q99".into(), ..wire(FORK, &hash) });
|
||||
assert_eq!(not_stored(hidden.clone()).code, ForkRefusalCode::ForkUnknown);
|
||||
assert_eq!(encode(&hidden), encode(&missing));
|
||||
// A decider is told the fork whether or not it is listed.
|
||||
let (decider_replay, wrote) = ask(&mut mind, "x", x_request);
|
||||
assert!(!wrote && answered(decider_replay).1.is_some());
|
||||
assert_eq!(head(&mind), before);
|
||||
// Relisted: the stored word replays again.
|
||||
let subject = eureka_pipeline::PipelineRef { kind: PipelineKind::Resolution, id: s(&withdrawal_key) };
|
||||
committed(admit(&mut mind, vec![crate::fixtures::resolution(subject, eureka_pipeline::ResolutionOutcome::Withdrawn { reason: "listed again".into() })]));
|
||||
let (relisted, wrote) = ask(&mut mind, "d", dan_request);
|
||||
assert!(!wrote);
|
||||
assert_eq!(answered(relisted).0.outcome, "Refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn showable_needs_two_options_text_depends_and_a_decider() {
|
||||
let D::Question(plain) = question("Q9", &["A", "B"], "A") else { unreachable!() };
|
||||
|
|
@ -1430,9 +1348,9 @@ mod tests {
|
|||
let (other, committed) = ask(&mut mind, "y", request.clone());
|
||||
let (other, _, _) = answered(other);
|
||||
assert!(committed);
|
||||
assert_eq!((other.answer_id.as_str(), other.answerer.as_deref().unwrap(), other.outcome.as_str(), other.request_id.as_str()), ("n2", account("y").0.as_str(), "Revision", request.request_id.as_str()));
|
||||
assert_eq!((other.answer_id.as_str(), other.answerer.as_str(), other.outcome.as_str(), other.request_id.as_str()), ("n2", "y", "Revision", request.request_id.as_str()));
|
||||
let (original, _, _) = answered(ask(&mut mind, "x", request.clone()).0);
|
||||
assert_eq!((original.answer_id.as_str(), original.answerer.as_deref().unwrap()), ("n1", account("x").0.as_str()));
|
||||
assert_eq!((original.answer_id.as_str(), original.answerer.as_str()), ("n1", "x"));
|
||||
// V17 and V18: an id that is no lowercase D-format UUID is body_invalid naming request_id, and binds nothing.
|
||||
let before = head(&mind);
|
||||
for bad in ["retry-1", "0000000A-0000-4000-8000-00000000000B", "{00000000-0000-4000-8000-000000000001}", "00000000-0000-4000-8000-0000000000010", "", " 00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000001 ", "00000000-0000-4000-8000-000000000001\n", "00000000-0000-4000-8000-000000000001x"] {
|
||||
|
|
@ -1547,7 +1465,6 @@ mod tests {
|
|||
assert_eq!(shown_hash(&question).0, her_hash, "{name}: the card's hash");
|
||||
let mut mind = seeded();
|
||||
committed(admit(&mut mind, vec![D::Question(question)]));
|
||||
committed(admit(&mut mind, vec![D::DeskListing(eureka_pipeline::PipelineDeskListing { campaign: slug("eureka-state"), listed: s(FORK), reason: "Listed.".into() })]));
|
||||
let list: Vec<&str> = card["deciders"].as_array().unwrap().iter().map(|who| who.as_str().unwrap()).collect();
|
||||
if card["status"] == "closed" {
|
||||
close(&mut mind, FORK, "RQ1", "no");
|
||||
|
|
@ -1644,27 +1561,27 @@ mod tests {
|
|||
let mut mind = desk();
|
||||
let hash = hash_of(&mind, FORK);
|
||||
// The operator's own account, off the list, is no decider; a member on the list is.
|
||||
let off = mind.desk_answer(&deciders(&["x"]), account("op"), DeskAuthority::Operator, wire(FORK, &hash), now());
|
||||
let off = mind.desk_answer(&deciders(&["x"]), s("op"), DeskAuthority::Operator, wire(FORK, &hash), now());
|
||||
assert_eq!(answered(off).0.code, Some(ForkAnswerCode::NotADecider));
|
||||
let on = mind.desk_answer(&deciders(&["m"]), account("m"), DeskAuthority::Member, wire(FORK, &hash), now());
|
||||
let on = mind.desk_answer(&deciders(&["m"]), s("m"), DeskAuthority::Member, wire(FORK, &hash), now());
|
||||
let (answer, _, _) = answered(on);
|
||||
assert_eq!((answer.outcome.as_str(), answer.authority, answer.answerer.as_deref().unwrap()), ("Counted", DeskAuthority::Member, account("m").0.as_str()));
|
||||
assert_eq!((answer.outcome.as_str(), answer.authority, answer.answerer.as_str()), ("Counted", DeskAuthority::Member, "m"));
|
||||
}
|
||||
|
||||
// ---- the desk request on the wire: deciders ride each call, at most 64, never stored ----
|
||||
|
||||
use crate::envelope::{OperationFailure, decode_desk_request, encode_desk_request};
|
||||
|
||||
fn list_of(n: usize) -> Vec<AccountId> {
|
||||
(0..n).map(|at| acct(&format!("d{at}"))).collect()
|
||||
fn list_of(n: usize) -> Vec<Short> {
|
||||
(0..n).map(|at| s(&format!("d{at}"))).collect()
|
||||
}
|
||||
|
||||
/// Each request kind of the desk, carrying `list`.
|
||||
fn desk_requests(mind: &str, list: &[AccountId], hash: &str) -> [DeskRequest; 3] {
|
||||
fn desk_requests(mind: &str, list: &[Short], hash: &str) -> [DeskRequest; 3] {
|
||||
[
|
||||
DeskRequest::Answer { mind: slug(mind), subject: acct("d0"), authority: DeskAuthority::Member, deciders: list.to_vec(), request: wire(FORK, hash) },
|
||||
DeskRequest::Forks { mind: slug(mind), subject: acct("d0"), deciders: list.to_vec(), status: None, cursor: None, limit: ForkLimit::new(10).unwrap() },
|
||||
DeskRequest::Fork { mind: slug(mind), subject: acct("d0"), deciders: list.to_vec(), fork_id: FORK.into() },
|
||||
DeskRequest::Answer { mind: slug(mind), subject: s("d0"), authority: DeskAuthority::Member, deciders: list.to_vec(), request: wire(FORK, hash) },
|
||||
DeskRequest::Forks { mind: slug(mind), subject: s("d0"), deciders: list.to_vec(), status: None, cursor: None, limit: ForkLimit::new(10).unwrap() },
|
||||
DeskRequest::Fork { mind: slug(mind), subject: s("d0"), deciders: list.to_vec(), fork_id: FORK.into() },
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -1687,7 +1604,7 @@ mod tests {
|
|||
// 64 deciders through to the Mind: the subject is listed and counts.
|
||||
let DeskRequest::Answer { subject, authority, deciders, request, .. } = through_the_door(&desk_requests(INSTANCE, &list_of(64), &hash)[0]).unwrap() else { panic!("not an answer") };
|
||||
let before = head(&mind);
|
||||
let response = mind.desk_answer(&deciders.iter().map(|id| s(&id.0)).collect::<Vec<_>>(), s(&subject.0), authority, request, now());
|
||||
let response = mind.desk_answer(&deciders, subject, authority, request, now());
|
||||
assert!(head(&mind) > before);
|
||||
assert_eq!(answered(response).0.outcome, "Counted");
|
||||
|
||||
|
|
@ -1707,7 +1624,7 @@ mod tests {
|
|||
let hash = hash_of(&mind, FORK);
|
||||
let before = (head(&mind), stored_count(&mind, FORK));
|
||||
let mut twice = list_of(3);
|
||||
twice.push(acct("d1"));
|
||||
twice.push(s("d1"));
|
||||
for (what, list) in [("empty", vec![]), ("duplicate", twice)] {
|
||||
for sent in desk_requests(INSTANCE, &list, &hash) {
|
||||
let failure = through_the_door(&sent).unwrap_err();
|
||||
|
|
@ -1743,6 +1660,6 @@ mod tests {
|
|||
// The same request to the mind it names is answered.
|
||||
let DeskRequest::Answer { mind: named, subject, authority, deciders, request } = through_the_door(&desk_requests(INSTANCE, &list_of(4), &hash)[0]).unwrap() else { panic!("not an answer") };
|
||||
mind.require_instance(&named).unwrap();
|
||||
assert_eq!(answered(mind.desk_answer(&deciders.iter().map(|id| s(&id.0)).collect::<Vec<_>>(), s(&subject.0), authority, request, now())).0.outcome, "Counted");
|
||||
assert_eq!(answered(mind.desk_answer(&deciders, subject, authority, request, now())).0.outcome, "Counted");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -74,19 +74,6 @@ impl<'i> Docs<'i> {
|
|||
self.image.id_of(kind, id).filter(|row| self.visible(*row)).map(|row| self.image.row(row).ordinal)
|
||||
}
|
||||
|
||||
/// When the document was first admitted, in UTC: an imported document's source receipt
|
||||
/// (`imported_from.committed_at`) wins over this mind's own `admitted_at`. `None` when the
|
||||
/// document is not held at this snapshot or the time does not parse as RFC3339 (an import's
|
||||
/// `committed_at` is only checked as non-empty text at admission). Also `None` when the UTC year is
|
||||
/// outside 0..=9999: CultLib's instant pattern has four year digits, and a local time near the edge
|
||||
/// can convert out of range.
|
||||
pub(crate) fn first_admitted_at(&self, kind: PipelineKind, id: &str) -> Option<chrono::DateTime<chrono::Utc>> {
|
||||
let row = self.image.id_of(kind, id).filter(|row| self.visible(*row))?;
|
||||
let admission = &self.image.row(row).view.admission;
|
||||
let text = admission.provenance.imported_from.as_ref().map_or(admission.admitted_at.as_str(), |source| source.committed_at.0.as_str());
|
||||
chrono::DateTime::parse_from_rfc3339(text).ok().map(|time| time.with_timezone(&chrono::Utc)).filter(|time| (0..=9999).contains(&chrono::Datelike::year(time)))
|
||||
}
|
||||
|
||||
pub(crate) fn find(&self, kind: PipelineKind, id: &str) -> Option<&PipelineDocument> {
|
||||
self.in_batch(kind, id).or_else(|| self.in_image(kind, id))
|
||||
}
|
||||
|
|
@ -401,8 +388,7 @@ pub(crate) fn line_of(document: &PipelineDocument) -> Option<Lineage<'_>> {
|
|||
| D::Pulse(_)
|
||||
| D::Reply(_)
|
||||
| D::Thought(_)
|
||||
| D::DeskAnswer(_)
|
||||
| D::DeskListing(_) => None,
|
||||
| D::DeskAnswer(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -456,11 +442,10 @@ pub enum CitationRole {
|
|||
DayThrough,
|
||||
Fork,
|
||||
Answer,
|
||||
Listed,
|
||||
}
|
||||
|
||||
impl CitationRole {
|
||||
pub const ALL: [CitationRole; 27] = [
|
||||
pub const ALL: [CitationRole; 26] = [
|
||||
Self::RaisedIn,
|
||||
Self::Answers,
|
||||
Self::Rulings,
|
||||
|
|
@ -487,7 +472,6 @@ impl CitationRole {
|
|||
Self::DayThrough,
|
||||
Self::Fork,
|
||||
Self::Answer,
|
||||
Self::Listed,
|
||||
];
|
||||
|
||||
/// The wire spelling, equal to the referring field's name.
|
||||
|
|
@ -519,7 +503,6 @@ impl CitationRole {
|
|||
Self::DayThrough => "day_through",
|
||||
Self::Fork => "fork",
|
||||
Self::Answer => "answer",
|
||||
Self::Listed => "listed",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -547,7 +530,6 @@ impl CitationRole {
|
|||
Self::Run => K::Reply,
|
||||
Self::Reads => K::Thought,
|
||||
Self::Fork | Self::Answer => K::DeskAnswer,
|
||||
Self::Listed => K::DeskListing,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -557,7 +539,7 @@ impl CitationRole {
|
|||
pub fn target_kinds(self) -> Vec<PipelineKind> {
|
||||
use PipelineKind as K;
|
||||
match self {
|
||||
Self::Answers | Self::Questions | Self::Forks | Self::Fork | Self::Listed => vec![K::Question],
|
||||
Self::Answers | Self::Questions | Self::Forks | Self::Fork => vec![K::Question],
|
||||
Self::Rulings => vec![K::Ruling],
|
||||
Self::CutSpec => vec![K::CutSpec],
|
||||
Self::CutReport => vec![K::CutReport],
|
||||
|
|
@ -675,7 +657,6 @@ pub(crate) fn citations(document: &PipelineDocument) -> Vec<(CitationRole, Pipel
|
|||
DeskOutcome::Counted | DeskOutcome::Refused { .. } => {}
|
||||
}
|
||||
}
|
||||
D::DeskListing(listing) => edges.push((R::Listed, cited(K::Question, &listing.listed))),
|
||||
D::Campaign(_) | D::Target(_) | D::Instance(_) | D::Stewardship(_) | D::Pulse(_) => {}
|
||||
}
|
||||
edges
|
||||
|
|
|
|||
|
|
@ -408,9 +408,9 @@ mod tests {
|
|||
fn desk_answer() -> DeskRequest {
|
||||
DeskRequest::Answer {
|
||||
mind: slug(INSTANCE),
|
||||
subject: crate::fixtures::acct("user-7"),
|
||||
subject: crate::fixtures::s("user-7"),
|
||||
authority: DeskAuthority::Member,
|
||||
deciders: vec![crate::fixtures::acct("user-7")],
|
||||
deciders: vec![crate::fixtures::s("user-7")],
|
||||
request: ForkAnswerRequest {
|
||||
schema_version: crate::desk_wire::RequestSchema::V0,
|
||||
fork_id: "eureka-state:question:Q1".into(),
|
||||
|
|
@ -425,7 +425,7 @@ mod tests {
|
|||
}
|
||||
|
||||
fn desk_requests() -> [(DeskRequest, &'static str); 3] {
|
||||
let (mind, subject, deciders) = (slug(INSTANCE), crate::fixtures::acct("user-7"), vec![crate::fixtures::acct("user-7")]);
|
||||
let (mind, subject, deciders) = (slug(INSTANCE), crate::fixtures::s("user-7"), vec![crate::fixtures::s("user-7")]);
|
||||
[
|
||||
(desk_answer(), "Answer"),
|
||||
(DeskRequest::Forks { mind: mind.clone(), subject: subject.clone(), deciders: deciders.clone(), status: Some(crate::desk_wire::ListStatus::Open), cursor: crate::desk_wire::ForkCursor::new(7), limit: crate::desk_wire::ForkLimit::new(50).unwrap() }, "Forks"),
|
||||
|
|
@ -549,7 +549,7 @@ mod tests {
|
|||
answered_at: "2026-11-10T12:00:00Z".into(),
|
||||
received_at: "2026-11-10T12:00:01Z".into(),
|
||||
claim_in_future: false,
|
||||
answerer: Some("user-7".into()),
|
||||
answerer: "user-7".into(),
|
||||
authority: DeskAuthority::Member,
|
||||
request_id: "00000000-0000-4000-8000-000000000001".into(),
|
||||
},
|
||||
|
|
@ -579,13 +579,13 @@ mod tests {
|
|||
fn a_maximal_desk_message_fits_the_frame() {
|
||||
let long = |n: usize| "x".repeat(n);
|
||||
let wire = |message: &CultNetMessage| encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0).unwrap().len();
|
||||
let deciders: Vec<_> = (0..64).map(|at| crate::fixtures::acct(&format!("decider {at}"))).collect();
|
||||
let deciders: Vec<_> = (0..64).map(|at| crate::fixtures::s(&format!("{at:0>200}"))).collect();
|
||||
let mut sized = vec![];
|
||||
for (request, _) in desk_requests() {
|
||||
let widest = match request {
|
||||
DeskRequest::Answer { mind, request, authority, .. } => DeskRequest::Answer {
|
||||
mind,
|
||||
subject: crate::fixtures::acct("the widest subject"),
|
||||
subject: crate::fixtures::s(&long(200)),
|
||||
authority,
|
||||
deciders: deciders.clone(),
|
||||
request: ForkAnswerRequest {
|
||||
|
|
@ -596,10 +596,10 @@ mod tests {
|
|||
},
|
||||
},
|
||||
DeskRequest::Forks { mind, status, cursor, limit, .. } => {
|
||||
DeskRequest::Forks { mind, subject: crate::fixtures::acct("the widest subject"), deciders: deciders.clone(), status, cursor, limit }
|
||||
DeskRequest::Forks { mind, subject: crate::fixtures::s(&long(200)), deciders: deciders.clone(), status, cursor, limit }
|
||||
}
|
||||
DeskRequest::Fork { mind, .. } => {
|
||||
DeskRequest::Fork { mind, subject: crate::fixtures::acct("the widest subject"), deciders: deciders.clone(), fork_id: long(200) }
|
||||
DeskRequest::Fork { mind, subject: crate::fixtures::s(&long(200)), deciders: deciders.clone(), fork_id: long(200) }
|
||||
}
|
||||
};
|
||||
let message = encode_desk_request("m-10", &widest, Some(long(200))).unwrap();
|
||||
|
|
@ -607,8 +607,7 @@ mod tests {
|
|||
sized.push(wire(&message));
|
||||
}
|
||||
assert!(sized.iter().all(|size| *size <= DESK_MAX_REQUEST_BYTES), "{sized:?} against {DESK_MAX_REQUEST_BYTES}");
|
||||
// 64 account ids of 36 bytes and a 4,000-byte note: the widest answer a request can carry.
|
||||
assert!(sized[0] > 4000 + 64 * 36, "the test builds a request that is actually large: {sized:?}");
|
||||
assert!(sized[0] > DESK_MAX_REQUEST_BYTES / 4, "the test builds a request that is actually large: {sized:?}");
|
||||
|
||||
let answer = ForkDeskAnswer {
|
||||
schema_version: crate::desk_wire::AnswerSchema::V0,
|
||||
|
|
@ -624,7 +623,7 @@ mod tests {
|
|||
answered_at: "2026-11-10T12:00:00.123456789+00:00".into(),
|
||||
received_at: "2026-11-10T12:00:00.123456789+00:00".into(),
|
||||
claim_in_future: true,
|
||||
answerer: Some(long(200)),
|
||||
answerer: long(200),
|
||||
authority: DeskAuthority::Operator,
|
||||
request_id: "00000000-0000-4000-8000-000000000001".into(),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -56,21 +56,6 @@ pub(crate) fn s(value: &str) -> Short {
|
|||
value.into()
|
||||
}
|
||||
|
||||
/// A deterministic Bifrost account id for a test's name for someone: a lowercase D-format UUID.
|
||||
pub(crate) fn account(name: &str) -> Short {
|
||||
// An id already in account form stands for itself.
|
||||
if name.len() == 36 && name.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f' | b'-')) {
|
||||
return Short(name.into());
|
||||
}
|
||||
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
|
||||
Short(format!("{:08x}-{:04x}-4000-8000-{:012x}", hash >> 32, (hash >> 16) & 0xffff, hash & 0xffff_ffff_ffff))
|
||||
}
|
||||
|
||||
/// The same, as the stored type.
|
||||
pub(crate) fn acct(name: &str) -> eureka_pipeline::AccountId {
|
||||
eureka_pipeline::AccountId(account(name).0)
|
||||
}
|
||||
|
||||
pub(crate) fn l(value: &str) -> Label {
|
||||
value.into()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -150,7 +150,7 @@ mod tests {
|
|||
fn view(document: PipelineDocument, ordinal: u64) -> PipelineDocumentView {
|
||||
let key = pipeline_key(&document).unwrap();
|
||||
let id = PipelineRef { kind: document.kind(), id: s(&key) };
|
||||
let faculty = if ordinal.is_multiple_of(2) { Faculty::Hands } else { Faculty::Soul };
|
||||
let faculty = if ordinal % 2 == 0 { Faculty::Hands } else { Faculty::Soul };
|
||||
let admission = AdmissionFacts {
|
||||
receipt_id: format!("receipt-{ordinal}"),
|
||||
admitted_at: format!("2026-11-08T16:{ordinal:02}:00Z"),
|
||||
|
|
@ -226,7 +226,7 @@ mod tests {
|
|||
let to_source = [held.clone(), vec![moved(RECEIVER, 4)]].concat();
|
||||
assert_eq!(plan(&slug(CAMPAIGN), &slug(RECEIVER), &slug(RECEIVER), to_source), Err(ImportFault::SourceIsReceiver));
|
||||
let other_root = view(
|
||||
resolution(r(K::Campaign, "elsewhere:campaign:self"), ResolutionOutcome::Moved { to: slug(RECEIVER) }),
|
||||
resolution(r(K::Campaign, &format!("elsewhere:campaign:self")), ResolutionOutcome::Moved { to: slug(RECEIVER) }),
|
||||
4,
|
||||
);
|
||||
assert_eq!(plan_of([held, vec![other_root]].concat()), Err(ImportFault::NotMoved), "another root's move does not move this one");
|
||||
|
|
|
|||
|
|
@ -105,8 +105,8 @@ pub fn index_text(document: &PipelineDocument) -> Option<String> {
|
|||
lines.push(&idea.idea.0);
|
||||
lines.push(&idea.tradeoffs.0);
|
||||
}
|
||||
// A desk answer is a person's words and a listing's reason is no retrieval text: neither is indexed.
|
||||
D::Instance(_) | D::Stewardship(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::DeskAnswer(_) | D::DeskListing(_) => {}
|
||||
// A desk answer is a person's words, not indexed.
|
||||
D::Instance(_) | D::Stewardship(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::DeskAnswer(_) => {}
|
||||
}
|
||||
lines.retain(|line| !line.is_empty());
|
||||
if lines.is_empty() {
|
||||
|
|
|
|||
|
|
@ -663,6 +663,7 @@ fn an_import_never_cites_or_resolves_a_follow_up_the_receiver_wrote() {
|
|||
let native = follow_up("FU-N", r(K::Question, &q1));
|
||||
let native_ref = r(K::FollowUp, &pipeline_key(&native).unwrap());
|
||||
committed(admit(&mut recv, vec![native]));
|
||||
let before = head(&recv);
|
||||
// An imported record that withdraws the receiver's own follow-up mixes a replay into her work.
|
||||
assert_eq!(
|
||||
refusal(import_from_kiko(&mut recv, vec![resolution(native_ref.clone(), ResolutionOutcome::Withdrawn { reason: "x".into() })])),
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ fn declared_names(node: &Value, names: &mut BTreeSet<String>) {
|
|||
|
||||
/// Rule 1: the document is valid against the published schema. The first
|
||||
/// failure is the refusal; it names where and which keyword, never the value.
|
||||
fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
|
||||
pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
|
||||
let compiled = compiled()?;
|
||||
let Err(error) = compiled.validator.validate(state) else { return Ok(()) };
|
||||
let mut path = error
|
||||
|
|
@ -115,21 +115,6 @@ fn validate_shape(state: &Value) -> Result<(), MindRefusal> {
|
|||
})
|
||||
}
|
||||
|
||||
/// Rules P1 to P3 of a put, the ones that read the document alone: it is valid against the published schema (P1), it is
|
||||
/// this mind's (`personaId` is `instance`, P2), and its provenance is canonical (P3). A put applies these first and then
|
||||
/// the rules that read the store; a reader of a state file outside the mind (`mind-persona project --state`) applies
|
||||
/// these and nothing else, so a file it accepts is one a put would not refuse for its content.
|
||||
pub fn validate_document(instance: &Slug, state: &Value) -> Result<(), MindRefusal> {
|
||||
validate_shape(state)?;
|
||||
if state.get("personaId").and_then(Value::as_str) != Some(instance.0.as_str()) {
|
||||
return Err(MindRefusal::PersonaForeign { instance: instance.0.clone() });
|
||||
}
|
||||
if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") {
|
||||
return Err(MindRefusal::PersonaNotCanonical);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A stored persona envelope's document.
|
||||
pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result<Value, MindRefusal> {
|
||||
rmp_serde::from_slice::<HuginnPersonaEntry>(&envelope.payload)
|
||||
|
|
@ -279,50 +264,6 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
/// Map 16.6: `embodiment` is optional. A document passes with it and without it, and the field is as closed as the
|
||||
/// rest of the schema: an unknown key inside it is refused at the door.
|
||||
#[test]
|
||||
fn embodiment_is_optional_and_closed() {
|
||||
let schema = schema_file();
|
||||
let validator = jsonschema::draft7::new(&schema).unwrap();
|
||||
let sense = json!({
|
||||
"id": "sense-spectrogram", "status": "active", "label": "spectrogram hearing",
|
||||
"summary": "She hears by rendering a sound as a spectrogram and looking at it.",
|
||||
"lacks": "not a human ear", "builtOn": T1, "updatedAt": T1
|
||||
});
|
||||
let mut with = persona(INSTANCE, T1);
|
||||
with["embodiment"] = json!({ "senses": [sense.clone()], "actuators": [] });
|
||||
assert!(validator.is_valid(&persona(INSTANCE, T1)) && validator.is_valid(&with));
|
||||
let mut empty = persona(INSTANCE, T1);
|
||||
empty["embodiment"] = json!({});
|
||||
assert!(validator.is_valid(&empty), "both lists are optional");
|
||||
|
||||
let store = MemoryStore::new();
|
||||
let mut mind = seeded_over(&store);
|
||||
let mut stray = with.clone();
|
||||
stray["embodiment"]["senses"][0]["ears"] = json!("human");
|
||||
assert_eq!(refused(put(&mut mind, stray, None)), invalid("/embodiment/senses/0/*", "additionalProperties"));
|
||||
let mut stray_list = with.clone();
|
||||
stray_list["embodiment"]["smell"] = json!([]);
|
||||
assert_eq!(refused(put(&mut mind, stray_list, None)), invalid("/embodiment/*", "additionalProperties"));
|
||||
let mut unlabelled = with;
|
||||
unlabelled["embodiment"]["senses"][0].as_object_mut().unwrap().remove("label");
|
||||
assert_eq!(refused(put(&mut mind, unlabelled, None)), invalid("/embodiment/senses/0/label", "required"));
|
||||
}
|
||||
|
||||
/// Map 16.35.9 (T1, T2): a hold and a promise are not her state. A put carrying either old field, even empty, is
|
||||
/// is refused at the door. The names are assembled, so a scan for the old fields finds no writer of them.
|
||||
#[test]
|
||||
fn holds_and_promises_are_not_her_state() {
|
||||
for field in [concat!("hol", "ds"), concat!("commit", "ments")] {
|
||||
let store = MemoryStore::new();
|
||||
let mut mind = seeded_over(&store);
|
||||
let mut with = persona(INSTANCE, T1);
|
||||
with[field] = json!([]);
|
||||
assert_eq!(refused(put(&mut mind, with, None)), invalid("/*", "additionalProperties"), "{field}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_names_are_every_property_name_at_any_depth() {
|
||||
let schema = json!({
|
||||
|
|
|
|||
|
|
@ -166,8 +166,6 @@ pub enum PipelineFacts {
|
|||
/// the one that counts for its fork at the read's snapshot, derived by `counted_answer` and never
|
||||
/// stored: a retracted `Counted` answer reads `counts: false`, the promoted next answer `true`.
|
||||
DeskAnswer { fork: Short, sequence: u32, outcome: Short, counts: bool, authority: DeskAuthority },
|
||||
/// The question this listing lets members read.
|
||||
DeskListing { listed: Short },
|
||||
}
|
||||
|
||||
impl PipelineFacts {
|
||||
|
|
@ -308,7 +306,6 @@ impl PipelineFacts {
|
|||
counts: counted_of(&value.fork.0).as_deref() == Some(id.id.0.as_str()),
|
||||
authority: value.authority,
|
||||
},
|
||||
D::DeskListing(value) => Self::DeskListing { listed: value.listed.clone() },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1852,7 +1849,7 @@ mod tests {
|
|||
|
||||
// Two desk answers on the open fork Q2: the second is a Revision of the first.
|
||||
let D::Question(shown) = question("Q2", &["A", "B"], "A") else { unreachable!() };
|
||||
let stamp = crate::desk::DeskStamp { answerer: crate::fixtures::account("x"), authority: eureka_pipeline::DeskAuthority::Member, deciders: vec![crate::fixtures::account("x")] };
|
||||
let stamp = crate::desk::DeskStamp { answerer: s("x"), authority: eureka_pipeline::DeskAuthority::Member, deciders: vec![s("x")] };
|
||||
let pick = |n: u32| crate::desk::DeskAnswerRequest {
|
||||
fork: s(&q2),
|
||||
options_hash: crate::desk::options_hash(&shown),
|
||||
|
|
@ -1865,10 +1862,6 @@ mod tests {
|
|||
assert!(matches!(mind.answer_desk(stamp.clone(), pick(n), now()), crate::desk::DeskAnswerOutcome::Stored { .. }));
|
||||
}
|
||||
|
||||
// The Mind lists Q2: one `listed` edge.
|
||||
committed(admit(&mut mind, vec![D::DeskListing(eureka_pipeline::PipelineDeskListing { campaign: slug(CAMPAIGN), listed: s(&q2), reason: "Members may read why.".into() })]));
|
||||
let listing = id("desk_listing", "Q2");
|
||||
|
||||
let (n1, f1_closed, f2_closed) = (
|
||||
id("resolution", "question.Q1.n1"),
|
||||
id("resolution", &format!("finding.{}.n1", f1.rsplit(':').next().unwrap())),
|
||||
|
|
@ -1917,9 +1910,8 @@ mod tests {
|
|||
(CitationRole::Fork, &answer_1, &q2),
|
||||
(CitationRole::Fork, &answer_2, &q2),
|
||||
(CitationRole::Answer, &answer_2, &answer_1),
|
||||
(CitationRole::Listed, &listing, &q2),
|
||||
];
|
||||
assert_eq!(CitationRole::ALL.len(), 27);
|
||||
assert_eq!(CitationRole::ALL.len(), 26);
|
||||
for role in CitationRole::ALL {
|
||||
let selection =
|
||||
Selection { cited: Some(Incoming { role: role.name().into(), exists: true }), ..Selection::default() };
|
||||
|
|
@ -2792,16 +2784,13 @@ mod tests {
|
|||
/// The upgrade gate on a real store (ruling readback-gate-and-materialized-image):
|
||||
/// the one function `Mind::read_back` over a scratch copy of a state root.
|
||||
/// Opens the store read-write, so run it on a copy, never the live file.
|
||||
/// `HUGINN_MIND_INSTANCE` names the instance whose store it opens, `eureka`
|
||||
/// when unset, so every Mind's store is gated the same way before a release
|
||||
/// moves her daemon. Measured about 30 s in debug at 11,328 documents.
|
||||
/// Measured about 30 s in debug at 11,328 documents.
|
||||
#[test]
|
||||
#[ignore = "needs HUGINN_MIND_SNAPSHOT, a scratch copy of a Huginn state root"]
|
||||
fn stored_documents_read_back() {
|
||||
let root = std::env::var("HUGINN_MIND_SNAPSHOT").expect("HUGINN_MIND_SNAPSHOT names a scratch copy of the state root");
|
||||
let instance = std::env::var("HUGINN_MIND_INSTANCE").unwrap_or_else(|_| "eureka".into());
|
||||
let started = std::time::Instant::now();
|
||||
let mind = Mind::open(std::path::Path::new(&root), &Slug(instance)).unwrap();
|
||||
let mind = Mind::open(std::path::Path::new(&root), &Slug("eureka".into())).unwrap();
|
||||
let count = mind.read_back().unwrap();
|
||||
println!("read back {count} stored documents in {:?}", started.elapsed());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -330,13 +330,13 @@ impl CacheBackingStore for LandsThenFails {
|
|||
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
|
||||
self.inner.pull_all()
|
||||
}
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.push(entry)
|
||||
}
|
||||
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.delete(entry)
|
||||
}
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<Vec<String>> {
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
|
||||
self.inner.push_all(entries, options)
|
||||
}
|
||||
}
|
||||
|
|
@ -547,13 +547,13 @@ impl CacheBackingStore for FailsTheLook {
|
|||
}
|
||||
self.inner.pull_all()
|
||||
}
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.push(entry)
|
||||
}
|
||||
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.delete(entry)
|
||||
}
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<Vec<String>> {
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
|
||||
self.inner.push_all(entries, options)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -374,7 +374,7 @@ mod tests {
|
|||
self.inner.pull_all()
|
||||
}
|
||||
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<String> {
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> anyhow::Result<()> {
|
||||
self.inner.push(entry)
|
||||
}
|
||||
|
||||
|
|
@ -382,7 +382,7 @@ mod tests {
|
|||
self.inner.delete(entry)
|
||||
}
|
||||
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> anyhow::Result<Vec<String>> {
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> anyhow::Result<()> {
|
||||
self.inner.push_all(entries, options)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
//! Credential redaction: the only code that knows the shape of a secret in text.
|
||||
//!
|
||||
//! `redact_url_userinfo` redacts URL credentials (the Self run's journal and reply). `scrub` is chat ingest's door: every message body
|
||||
//! `redact_url_userinfo` redacts URL credentials (the Self run's journal and reply,
|
||||
//! the Persona's structured output). `scrub` is chat ingest's door: every message body
|
||||
//! passes it before it is chunked, embedded or stored, and it also runs the URL rule.
|
||||
//! Shapes only; nothing here reads meaning, and a hit is a kind, never a value.
|
||||
|
||||
/// The one redaction of URL credentials. Call it at each place a string the CLI produced enters the journal, her mind or chat: today
|
||||
/// the Self result (`result_text`: journal line and Reply). It does not cover claude's stderr (inherited) or the CLI's transcript files.
|
||||
/// the Self result (`result_text`: journal line and Reply) and the structured output of a Persona or Sleep result
|
||||
/// (`persona::structured_output`, string by string). It does not cover claude's stderr (inherited) or the CLI's transcript files.
|
||||
///
|
||||
/// A forge token rides in a remote URL, so every `scheme://` and every protocol-relative `//` opens an authority, read as git, curl and
|
||||
/// RFC 3986 read it: it ends at the first `/`, `?`, `#`, backslash, quote, backtick, parenthesis, bracket, angle bracket or ASCII whitespace
|
||||
|
|
@ -157,7 +159,7 @@ fn zero_width(c: char) -> bool {
|
|||
pub fn scrub(text: &str) -> Scrubbed {
|
||||
let mut hits = Vec::new();
|
||||
let mut stripped: String = text.chars().filter(|c| !zero_width(*c)).collect();
|
||||
let passes: [(ScrubKind, Finder); 6] = [
|
||||
let passes: [(ScrubKind, fn(&str, usize) -> Option<usize>); 6] = [
|
||||
(ScrubKind::PemBlock, pem_block),
|
||||
(ScrubKind::AuthorizationHeader, authorization_line),
|
||||
(ScrubKind::AccessToken, access_token),
|
||||
|
|
@ -174,10 +176,7 @@ pub fn scrub(text: &str) -> Scrubbed {
|
|||
if hits.is_empty() { Scrubbed { text: text.to_owned(), hits } } else { Scrubbed { text: urls, hits } }
|
||||
}
|
||||
|
||||
/// A scrub pass: finds the end of one secret starting at a byte offset, if one starts there.
|
||||
type Finder = fn(&str, usize) -> Option<usize>;
|
||||
|
||||
fn replace_matches(text: &str, kind: ScrubKind, find: Finder, hits: &mut Vec<ScrubKind>) -> String {
|
||||
fn replace_matches(text: &str, kind: ScrubKind, find: fn(&str, usize) -> Option<usize>, hits: &mut Vec<ScrubKind>) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut at = 0;
|
||||
while at < text.len() {
|
||||
|
|
@ -464,7 +463,7 @@ mod tests {
|
|||
"123e4567-e89b-12d3-a456-426614174000", "!abc:s", "$Ab3dEf-9_zQ", "user@example.com", "ssh://git@host/r.git",
|
||||
"https://github.com/@user", "pkg@1.2.3", "the bearer of bad news", "Authorization is a header",
|
||||
"padding like dGVzdA== in prose", "```\nlet x = 1;\n```", "the BEGIN PRIVATE KEY header", "a token of thanks",
|
||||
"AKIAshort", "ghp_short", "eyJ is a prefix", "naïve café — 日本語 with Bearer in it",
|
||||
"AKIAshort", "ghp_short", "eyJ is a prefix", "naïve café — 日本語 with Bearer in it",
|
||||
] {
|
||||
let out = scrub(same);
|
||||
assert_eq!(out.text, same);
|
||||
|
|
@ -474,9 +473,9 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn multibyte_text_around_a_secret_never_panics_the_scrub() {
|
||||
let body = format!("日本 \u{a0}é Bearer {} → ünï", "A1b2".repeat(6));
|
||||
assert_eq!(scrub(&body).text, "日本 \u{a0}é <redacted> → ünï");
|
||||
let seed = "é日 sk-aaaaaaaaaaaaaaaaaaaa -----BEGIN PRIVATE KEY----- authorization: é eyJa.b.c https://u:p@h/x";
|
||||
let body = format!("日本 \u{a0}é Bearer {} → ünï", "A1b2".repeat(6));
|
||||
assert_eq!(scrub(&body).text, "日本 \u{a0}é <redacted> → ünï");
|
||||
let seed = "é日 sk-aaaaaaaaaaaaaaaaaaaa -----BEGIN PRIVATE KEY----- authorization: é eyJa.b.c https://u:p@h/x";
|
||||
let chars: Vec<char> = seed.chars().collect();
|
||||
for start in 0..chars.len() {
|
||||
for end in start..=chars.len() {
|
||||
|
|
|
|||
|
|
@ -117,10 +117,6 @@ pub enum MindRefusal {
|
|||
/// reached.
|
||||
CursorInvalid { message: String },
|
||||
Unavailable { detail: String },
|
||||
/// The request reached the persona door, which answers reads and the
|
||||
/// mind's own persona document and nothing that writes the mind
|
||||
/// (`HuginnMindRequest::reaches_persona_door`). Nothing was written.
|
||||
NotThisDoor,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for MindRefusal {
|
||||
|
|
|
|||
|
|
@ -248,7 +248,7 @@ impl SelectionRow {
|
|||
D::Stewardship(stewardship) => vec![stewardship.repo.identity()],
|
||||
D::HandOff(hand_off) => vec![hand_off.repo.identity()],
|
||||
D::Ruling(PipelineRuling { authority: RulingAuthority::Steward { repo, .. }, .. }) => vec![repo.identity()],
|
||||
D::Target(_) | D::Question(_) | D::Ruling(_) | D::Verdict(_) | D::Finding(_) | D::Instance(_) | D::Resolution(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::Thought(_) | D::Memory(_) | D::Research(_) | D::Idea(_) | D::DeskAnswer(_) | D::DeskListing(_) => {
|
||||
D::Target(_) | D::Question(_) | D::Ruling(_) | D::Verdict(_) | D::Finding(_) | D::Instance(_) | D::Resolution(_) | D::Run(_) | D::Pulse(_) | D::Reply(_) | D::Thought(_) | D::Memory(_) | D::Research(_) | D::Idea(_) | D::DeskAnswer(_) => {
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
|
|
@ -466,7 +466,7 @@ mod tests {
|
|||
/// refused at the substrate's door.
|
||||
#[test]
|
||||
fn each_kind_declares_exactly_its_aliases_and_none_is_numeric() {
|
||||
let table: [(K, &[&str]); 22] = [
|
||||
let table: [(K, &[&str]); 21] = [
|
||||
(K::Campaign, &["repo"]),
|
||||
(K::Target, &[]),
|
||||
(K::Question, &[]),
|
||||
|
|
@ -488,7 +488,6 @@ mod tests {
|
|||
(K::Reply, &[]),
|
||||
(K::Thought, &[]),
|
||||
(K::DeskAnswer, &[]),
|
||||
(K::DeskListing, &[]),
|
||||
];
|
||||
for (kind, extra) in table {
|
||||
let want = [&["root", "in_force", "faculty"][..], extra].concat();
|
||||
|
|
@ -504,7 +503,7 @@ mod tests {
|
|||
/// twenty-one.
|
||||
#[test]
|
||||
fn each_kind_declares_the_roles_it_carries_and_their_targets() {
|
||||
let table: [(K, &[&str]); 22] = [
|
||||
let table: [(K, &[&str]); 21] = [
|
||||
(K::Campaign, &[]),
|
||||
(K::Target, &[]),
|
||||
(K::Question, &["raised_in"]),
|
||||
|
|
@ -526,14 +525,13 @@ mod tests {
|
|||
(K::Reply, &["run"]),
|
||||
(K::Thought, &["reads"]),
|
||||
(K::DeskAnswer, &["fork", "answer"]),
|
||||
(K::DeskListing, &["listed"]),
|
||||
];
|
||||
for (kind, roles) in table {
|
||||
assert_eq!(sorted(Vocabulary.declared_roles(kind.type_id())), strings(roles), "{kind:?}");
|
||||
}
|
||||
assert_eq!(Vocabulary.target_leaves("answers"), vec![K::Question.type_id().to_string()]);
|
||||
assert_eq!(Vocabulary.target_leaves("rulings"), vec![K::Ruling.type_id().to_string()]);
|
||||
assert_eq!(Vocabulary.target_leaves("subject").len(), 22);
|
||||
assert_eq!(Vocabulary.target_leaves("subject").len(), 21);
|
||||
assert_eq!(
|
||||
sorted(Vocabulary.target_leaves("claims")),
|
||||
sorted([K::CutSpec, K::Finding, K::FollowUp].iter().map(|kind| kind.type_id().to_string()).collect())
|
||||
|
|
|
|||
|
|
@ -116,9 +116,9 @@ pub(crate) mod test_stores {
|
|||
Ok(self.rows())
|
||||
}
|
||||
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.plant(entry.clone());
|
||||
Ok(entry.stored_at.clone())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
|
|
@ -126,9 +126,9 @@ pub(crate) mod test_stores {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], _options: PushAllOptions) -> Result<Vec<String>> {
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], _options: PushAllOptions) -> Result<()> {
|
||||
*self.rows.lock().unwrap() = entries.iter().map(|entry| (identity(entry), entry.clone())).collect();
|
||||
Ok(entries.iter().map(|entry| entry.stored_at.clone()).collect())
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -199,7 +199,7 @@ pub(crate) mod test_stores {
|
|||
self.inner.pull_all()
|
||||
}
|
||||
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()> {
|
||||
self.inner.push(entry)
|
||||
}
|
||||
|
||||
|
|
@ -207,7 +207,7 @@ pub(crate) mod test_stores {
|
|||
self.inner.delete(entry)
|
||||
}
|
||||
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<Vec<String>> {
|
||||
fn push_all(&mut self, entries: &[CultCacheEnvelope], options: PushAllOptions) -> Result<()> {
|
||||
self.inner.push_all(entries, options)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -286,9 +286,8 @@ pub const CHAT_ROOMS_MAX: usize = 16;
|
|||
/// [after, before]. `texts` (none to `SOURCE_TEXTS_MAX`) is the meaning match,
|
||||
/// several fused as in a source search; with none the search is a listing:
|
||||
/// chunks oldest first, at most `top_k`, `ChatHits.truncated` saying more
|
||||
/// exist. Within one room the caller narrows with `after_ms` = the last hit's
|
||||
/// `ts_end_ms + 1`; across rooms spans overlap and that loses chunks, so list
|
||||
/// one room at a time.
|
||||
/// exist, and the caller narrows with `after_ms` = the last hit's
|
||||
/// `ts_end_ms + 1`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ChatQuery {
|
||||
pub texts: Vec<Line>,
|
||||
|
|
@ -430,28 +429,6 @@ impl HuginnMindRequest {
|
|||
}
|
||||
}
|
||||
|
||||
/// Whether the persona door answers this request. The persona door is the
|
||||
/// daemon's second listener, the only one a Persona's uid can reach: it
|
||||
/// serves the mind's reads and her own persona document, and refuses
|
||||
/// every write to the mind (`MindRefusal::NotThisDoor`). The match has no
|
||||
/// wildcard, so a new request does not compile until it is classified
|
||||
/// here.
|
||||
pub fn reaches_persona_door(&self) -> bool {
|
||||
match self {
|
||||
Self::Whoami
|
||||
| Self::View { .. }
|
||||
| Self::Query { .. }
|
||||
| Self::PersonaGet { .. }
|
||||
| Self::PersonaPut { .. }
|
||||
| Self::SearchSources { .. }
|
||||
| Self::SearchChat { .. }
|
||||
| Self::ChatWindow { .. }
|
||||
| Self::StewardedActivity { .. }
|
||||
| Self::RootsTouched { .. } => true,
|
||||
Self::Admit(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance the request declares; `Whoami` declares none.
|
||||
pub fn instance(&self) -> Option<&Slug> {
|
||||
match self {
|
||||
|
|
@ -655,7 +632,6 @@ mod tests {
|
|||
scores: Some(vec![0.5]),
|
||||
}),
|
||||
HuginnMindResponse::Refused(refusal),
|
||||
HuginnMindResponse::Refused(MindRefusal::NotThisDoor),
|
||||
HuginnMindResponse::Persona(None),
|
||||
HuginnMindResponse::Persona(Some(PersonaStateView {
|
||||
value: serde_json::json!({ "personaId": INSTANCE }),
|
||||
|
|
|
|||
|
|
@ -3,10 +3,9 @@
|
|||
//! are what the door speaks. `docs/desk-feed-door.md` is the contract they pin; the README in the
|
||||
//! fixtures directory lists them.
|
||||
//!
|
||||
//! The entry-bearing fixtures carry the reader-count shapes (`raised_at`, `decider_count`,
|
||||
//! `answerer_count`, a nullable `answerer`), a decider's view and a non-decider's. CultLib's own bytes
|
||||
//! for those shapes are vendored at one commit in `fixtures/desk-feed/cultlib-d3025d3c/`; Huginn's
|
||||
//! real types decode and re-encode every one of them byte for byte (checked below).
|
||||
//! No fixture written here carries a card: Huginn's types do not carry `raised_at`, `decider_count`,
|
||||
//! `answerer_count` or a nullable `answerer` yet. Those shapes are CultLib's own bytes, vendored at
|
||||
//! one commit in `fixtures/desk-feed/cultlib-d3025d3c/` and checked below.
|
||||
//!
|
||||
//! `cargo test -p huginn-mind --test desk_feed_fixtures` compares every file with what the
|
||||
//! encoders produce now. `HUGINN_WRITE_DESK_FIXTURES=1` rewrites them instead.
|
||||
|
|
@ -18,11 +17,11 @@ use sha2::{Digest, Sha256};
|
|||
use cultnet_rs::{CultNetMessage, CultNetWireContract, encode_cultnet_message_to_vec, encode_frame};
|
||||
use huginn_mind::MindRefusal;
|
||||
use huginn_mind::desk_wire::{
|
||||
fork_too_large_read, AnswerSchema, CardSchema, CardStatus, DeskRequest, DeskResponse, EntrySchema, ForkCard, ForkCursor, ForkDeskAnswer, ForkEntry, ForkLimit,
|
||||
ForkList, ForkOption, ForkRecord, ForkRefusal, ForkRefusalCode, ForkRef, ListSchema, ListStatus, RecordSchema,
|
||||
fork_too_large_read, AnswerSchema, DeskRequest, DeskResponse, ForkCursor, ForkDeskAnswer, ForkLimit, ForkList, ForkRecord, ForkRefusal, ForkRefusalCode,
|
||||
ListSchema, ListStatus, RecordSchema,
|
||||
};
|
||||
use huginn_mind::envelope::{OperationFailure, decode_desk_request, encode_desk_failure, encode_desk_request, encode_desk_response};
|
||||
use huginn_mind::eureka_pipeline::{AccountId, DeskAuthority, Slug};
|
||||
use huginn_mind::envelope::{OperationFailure, encode_desk_failure, encode_desk_request, encode_desk_response};
|
||||
use huginn_mind::eureka_pipeline::{DeskAuthority, Short, Slug};
|
||||
|
||||
const RUNTIME: &str = "huginn-eureka";
|
||||
/// Account ids as Bifrost sends them: `UserAccount.Id` rendered lowercase D-format
|
||||
|
|
@ -32,21 +31,19 @@ const READER: &str = "5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6f";
|
|||
const OTHER_DECIDER: &str = "0b9d7e3a-6c21-4f58-a0d4-9e8f7a6b5c4d";
|
||||
/// A member who answered but is not a decider: their answer is stored `Refused(not_a_decider)`.
|
||||
const OUTSIDER: &str = "c3a1f2e4-7b6d-4e8f-9a0b-1c2d3e4f5a6b";
|
||||
/// A member the call's deciders do not name, who reads as a non-decider.
|
||||
const NON_DECIDER: &str = "9e8d7c6b-5a49-4382-b1a0-f9e8d7c6b5a4";
|
||||
/// A question Eureka's mind holds (asked 2026-11-11). The answers, notes and hash in `record()` are
|
||||
/// synthetic: the hash is CultLib's sample digest, not this question's.
|
||||
const FORK: &str = "eureka-substrate:question:desk-listing-authority";
|
||||
|
||||
fn a(text: &str) -> AccountId {
|
||||
AccountId(text.into())
|
||||
fn s(text: &str) -> Short {
|
||||
Short(text.into())
|
||||
}
|
||||
|
||||
fn forks(status: Option<ListStatus>, cursor: Option<u64>, limit: u8) -> DeskRequest {
|
||||
DeskRequest::Forks {
|
||||
mind: Slug("eureka".into()),
|
||||
subject: a(READER),
|
||||
deciders: vec![a(READER), a(OTHER_DECIDER)],
|
||||
subject: s(READER),
|
||||
deciders: vec![s(READER), s(OTHER_DECIDER)],
|
||||
status,
|
||||
cursor: cursor.and_then(ForkCursor::new),
|
||||
limit: ForkLimit::new(limit).unwrap(),
|
||||
|
|
@ -54,23 +51,7 @@ fn forks(status: Option<ListStatus>, cursor: Option<u64>, limit: u8) -> DeskRequ
|
|||
}
|
||||
|
||||
fn read() -> DeskRequest {
|
||||
DeskRequest::Fork { mind: Slug("eureka".into()), subject: a(READER), deciders: vec![a(READER), a(OTHER_DECIDER)], fork_id: FORK.into() }
|
||||
}
|
||||
|
||||
/// The same reads from a subject the call's deciders do not name: a non-decider.
|
||||
fn forks_as_non_decider() -> DeskRequest {
|
||||
DeskRequest::Forks {
|
||||
mind: Slug("eureka".into()),
|
||||
subject: a(NON_DECIDER),
|
||||
deciders: vec![a(READER), a(OTHER_DECIDER)],
|
||||
status: Some(ListStatus::Open),
|
||||
cursor: None,
|
||||
limit: ForkLimit::new(50).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_as_non_decider() -> DeskRequest {
|
||||
DeskRequest::Fork { mind: Slug("eureka".into()), subject: a(NON_DECIDER), deciders: vec![a(READER), a(OTHER_DECIDER)], fork_id: FORK.into() }
|
||||
DeskRequest::Fork { mind: Slug("eureka".into()), subject: s(READER), deciders: vec![s(READER), s(OTHER_DECIDER)], fork_id: FORK.into() }
|
||||
}
|
||||
|
||||
fn list(open_count: u64, recorded_count: u64) -> DeskResponse {
|
||||
|
|
@ -92,7 +73,7 @@ fn refusal(code: ForkRefusalCode, error: &str) -> DeskResponse {
|
|||
DeskResponse::NotStored(ForkRefusal { schema_version: huginn_mind::desk_wire::RefusalSchema::V0, code, error: error.into() })
|
||||
}
|
||||
|
||||
fn answer(id: &str, outcome: &str, of: Option<&str>, answerer: Option<&str>, note: &str, received_at: &str) -> ForkDeskAnswer {
|
||||
fn answer(id: &str, outcome: &str, of: Option<&str>, answerer: &str, note: &str, received_at: &str) -> ForkDeskAnswer {
|
||||
ForkDeskAnswer {
|
||||
schema_version: AnswerSchema::V0,
|
||||
answer_id: id.into(),
|
||||
|
|
@ -107,76 +88,35 @@ fn answer(id: &str, outcome: &str, of: Option<&str>, answerer: Option<&str>, not
|
|||
answered_at: received_at.into(),
|
||||
received_at: received_at.into(),
|
||||
claim_in_future: false,
|
||||
answerer: answerer.map(str::to_string),
|
||||
answerer: answerer.into(),
|
||||
authority: DeskAuthority::Member,
|
||||
request_id: format!("00000000-0000-4000-8000-00000000000{}", &id[1..]),
|
||||
}
|
||||
}
|
||||
|
||||
/// A fork's record with a counted answer, a decider's revision, a refusal and a retraction: four
|
||||
/// answers by three accounts. A decider's view names every answerer; a non-decider's names none and
|
||||
/// keeps the count.
|
||||
fn record(decider: bool) -> ForkRecord {
|
||||
let who = |id: &'static str| decider.then_some(id);
|
||||
/// A fork's record with a counted answer and a decider's revision, answerer ids raw: the door sends
|
||||
/// them raw and Bifrost masks them for a reader who is not a decider.
|
||||
fn record() -> ForkRecord {
|
||||
ForkRecord {
|
||||
schema_version: RecordSchema::V0,
|
||||
fork_id: FORK.into(),
|
||||
options_hash: HASH.into(),
|
||||
options_hash: "7d95fc87d532420611fe415c1def27a3447617bb68235f46e3af130aea361c48".into(),
|
||||
counted_answer_id: Some("n1".into()),
|
||||
answerer_count: 3,
|
||||
answers: vec![
|
||||
answer("n1", "Counted", None, who(READER), "The asker lists her own forks.", "2026-11-11T17:00:00Z"),
|
||||
answer("n2", "Revision", Some("n1"), who(OTHER_DECIDER), "Agreed.", "2026-11-11T17:05:00Z"),
|
||||
ForkDeskAnswer { code: Some(huginn_mind::desk_wire::ForkAnswerCode::NotADecider), ..answer("n3", "Refused", None, who(OUTSIDER), "Me too.", "2026-11-11T17:06:00Z") },
|
||||
answer("n1", "Counted", None, READER, "The asker lists her own forks.", "2026-11-11T17:00:00Z"),
|
||||
answer("n2", "Revision", Some("n1"), OTHER_DECIDER, "Agreed.", "2026-11-11T17:05:00Z"),
|
||||
ForkDeskAnswer { code: Some(huginn_mind::desk_wire::ForkAnswerCode::NotADecider), ..answer("n3", "Refused", None, OUTSIDER, "Me too.", "2026-11-11T17:06:00Z") },
|
||||
// A second answer by an account already counted: four answers, three answerers.
|
||||
ForkDeskAnswer {
|
||||
retracts: Some("n2".into()),
|
||||
choice: None,
|
||||
note: None,
|
||||
..answer("n4", "Retraction", None, who(OTHER_DECIDER), "", "2026-11-11T17:07:00Z")
|
||||
..answer("n4", "Retraction", None, OTHER_DECIDER, "", "2026-11-11T17:07:00Z")
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const HASH: &str = "7d95fc87d532420611fe415c1def27a3447617bb68235f46e3af130aea361c48";
|
||||
|
||||
/// The fork's card. A decider's view lists the call's ids; a non-decider's lists none and keeps the count.
|
||||
fn card(decider: bool, raised_at: Option<&str>) -> ForkCard {
|
||||
ForkCard {
|
||||
schema_version: CardSchema::V0,
|
||||
fork_id: FORK.into(),
|
||||
title: "Who may list a fork?".into(),
|
||||
context: "A fork is read by members only once it is listed.".into(),
|
||||
options: vec![ForkOption { id: "asking-mind".into(), text: "The asking Mind lists her own forks.".into() }, ForkOption { id: "operator".into(), text: "An operator lists them.".into() }],
|
||||
recommendation: "asking-mind".into(),
|
||||
depends: Vec::new(),
|
||||
leans: None,
|
||||
flag: None,
|
||||
raised_in: Some(ForkRef { kind: "Idea".into(), id: "eureka-substrate:idea:desk-door-map".into() }),
|
||||
raised_at: raised_at.map(str::to_string),
|
||||
deciders: if decider { vec![READER.into(), OTHER_DECIDER.into()] } else { Vec::new() },
|
||||
decider_count: 2,
|
||||
status: CardStatus::Open,
|
||||
ruling: None,
|
||||
ruled_from: Vec::new(),
|
||||
order: 41,
|
||||
options_hash: HASH.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(decider: bool, raised_at: Option<&str>) -> ForkEntry {
|
||||
ForkEntry { schema_version: EntrySchema::V0, card: card(decider, raised_at), record: record(decider) }
|
||||
}
|
||||
|
||||
/// One open fork on the page; the counts are the page's visible set.
|
||||
fn list_of(entry: ForkEntry) -> DeskResponse {
|
||||
DeskResponse::Forks {
|
||||
list: ForkList { schema_version: ListSchema::V0, mind: "eureka".into(), stamp: "s10190".into(), open_count: 1, recorded_count: 0, forks: vec![entry], next_cursor: None },
|
||||
as_of: 10190,
|
||||
}
|
||||
}
|
||||
|
||||
/// The named MessagePack payload a CultNet operation message carries (base64 in the envelope).
|
||||
fn payload(message: &CultNetMessage) -> Vec<u8> {
|
||||
use base64::Engine;
|
||||
|
|
@ -196,24 +136,6 @@ fn hex(bytes: &[u8]) -> String {
|
|||
text
|
||||
}
|
||||
|
||||
/// A request message whose payload is `request` with one field changed to something the typed request
|
||||
/// cannot hold: what a client that skips the account grammar would send.
|
||||
fn malformed(id: &str, request: &DeskRequest, edit: impl Fn(&mut serde_json::Value)) -> CultNetMessage {
|
||||
use base64::Engine;
|
||||
let mut value = serde_json::to_value(request).unwrap();
|
||||
edit(&mut value);
|
||||
CultNetMessage::OperationRequest {
|
||||
message_id: id.into(),
|
||||
service_id: huginn_mind::desk_wire::DESK_SERVICE_ID.into(),
|
||||
operation: "fork".into(),
|
||||
payload_schema: huginn_mind::desk_wire::DESK_REQUEST_SCHEMA.into(),
|
||||
payload_encoding: "messagepack-base64".into(),
|
||||
payload: base64::engine::general_purpose::STANDARD.encode(rmp_serde::to_vec_named(&value).unwrap()),
|
||||
source_runtime_id: None,
|
||||
target_runtime_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every fixture: its file stem and its bytes. A message gives `.frame.bin`, `.frame.hex` and,
|
||||
/// for an operation message, `.payload.msgpack` and `.payload.hex`; a bare payload gives the last two.
|
||||
fn fixtures() -> Vec<(String, Vec<u8>)> {
|
||||
|
|
@ -232,22 +154,6 @@ fn fixtures() -> Vec<(String, Vec<u8>)> {
|
|||
message("list-open-cursor.request", encode_desk_request("m-2", &forks(Some(ListStatus::Open), Some(42), 50), None).unwrap());
|
||||
message("list-counts.request", encode_desk_request("m-3", &forks(Some(ListStatus::Open), None, 0), None).unwrap());
|
||||
message("read.request", encode_desk_request("m-4", &read(), None).unwrap());
|
||||
message("list-non-decider.request", encode_desk_request("m-5", &forks_as_non_decider(), None).unwrap());
|
||||
message("read-non-decider.request", encode_desk_request("m-6", &read_as_non_decider(), None).unwrap());
|
||||
message("list-open.response", encode_desk_response("m-1", "forks", &list_of(entry(true, Some("2026-11-11T16:40:12Z"))), RUNTIME).unwrap());
|
||||
message("list-open-non-decider.response", encode_desk_response("m-5", "forks", &list_of(entry(false, Some("2026-11-11T16:40:12Z"))), RUNTIME).unwrap());
|
||||
// raised_at nil: the question's first admission is unknown.
|
||||
message("read.response", encode_desk_response("m-4", "fork", &DeskResponse::Fork { entry: entry(true, None), as_of: 10190 }, RUNTIME).unwrap());
|
||||
message("read-non-decider.response", encode_desk_response("m-6", "fork", &DeskResponse::Fork { entry: entry(false, None), as_of: 10190 }, RUNTIME).unwrap());
|
||||
// A decider or subject that is no account id is refused at decode, naming the field.
|
||||
for (name, id, request) in [
|
||||
("read-mxid-decider", "m-7", malformed("m-7", &read(), |value| value["Fork"]["deciders"][0] = "@heimdall:gamecult.org".into())),
|
||||
("read-email-subject", "m-8", malformed("m-8", &read(), |value| value["Fork"]["subject"] = "meta@gamecult.org".into())),
|
||||
] {
|
||||
message(&format!("{name}.request"), request.clone());
|
||||
let failure = decode_desk_request(&request).expect_err("the door refuses it");
|
||||
message(&format!("{name}.failure.response"), encode_desk_failure(id, "fork", &failure, RUNTIME));
|
||||
}
|
||||
message("list-empty.response", encode_desk_response("m-1", "forks", &list(0, 0), RUNTIME).unwrap());
|
||||
message("list-counts.response", encode_desk_response("m-3", "forks", &list(3, 5), RUNTIME).unwrap());
|
||||
message(
|
||||
|
|
@ -279,11 +185,9 @@ fn fixtures() -> Vec<(String, Vec<u8>)> {
|
|||
encode_desk_failure("m-1", "forks", &OperationFailure { code: "payload-not-a-request".into(), message: "field Forks.limit: out-of-range".into() }, RUNTIME),
|
||||
);
|
||||
message("error.response", CultNetMessage::Error { error: "huginn.desk refuses a message_id over 256 bytes".into(), code: None, details: None });
|
||||
for (name, decider) in [("record-whole", true), ("record-withheld", false)] {
|
||||
let bytes = rmp_serde::to_vec_named(&record(decider)).unwrap();
|
||||
files.push((format!("{name}.payload.msgpack"), bytes.clone()));
|
||||
files.push((format!("{name}.payload.hex"), hex(&bytes).into_bytes()));
|
||||
}
|
||||
let whole = rmp_serde::to_vec_named(&record()).unwrap();
|
||||
files.push(("record-whole.payload.msgpack".into(), whole.clone()));
|
||||
files.push(("record-whole.payload.hex".into(), hex(&whole).into_bytes()));
|
||||
files
|
||||
}
|
||||
|
||||
|
|
@ -317,7 +221,8 @@ fn account_id(text: &str) -> bool {
|
|||
}
|
||||
|
||||
/// Every account id the fixtures carry is a Bifrost account id, never a Matrix id, email or
|
||||
/// handle, and the door refuses any other shape at decode, naming the field and never the value.
|
||||
/// handle. The door does not refuse other shapes yet (`Short`, any 200 bytes); that refusal is owed
|
||||
/// by `cut-desk-feed-listing.r6`, and this pins the grammar it must enforce.
|
||||
#[test]
|
||||
fn every_account_id_in_the_fixtures_is_a_lowercase_d_format_uuid() {
|
||||
for request in [forks(Some(ListStatus::Open), None, 50), read()] {
|
||||
|
|
@ -327,15 +232,7 @@ fn every_account_id_in_the_fixtures_is_a_lowercase_d_format_uuid() {
|
|||
assert!(account_id(&subject.0), "subject");
|
||||
assert!(request.deciders().iter().all(|decider| account_id(&decider.0)), "deciders");
|
||||
}
|
||||
assert!(record(true).answers.iter().all(|answer| account_id(answer.answerer.as_deref().unwrap())), "answerer");
|
||||
for (request, field, value) in [
|
||||
(malformed("m-7", &read(), |value| value["Fork"]["deciders"][0] = "@heimdall:gamecult.org".into()), "deciders", "@heimdall:gamecult.org"),
|
||||
(malformed("m-8", &read(), |value| value["Fork"]["subject"] = "meta@gamecult.org".into()), "subject", "meta@gamecult.org"),
|
||||
] {
|
||||
let failure = decode_desk_request(&request).expect_err("a request outside the grammar is refused");
|
||||
assert_eq!(failure.code, "payload-not-a-request");
|
||||
assert!(failure.message.contains(field) && !failure.message.contains(value), "{}", failure.message);
|
||||
}
|
||||
assert!(record().answers.iter().all(|answer| account_id(&answer.answerer)), "answerer");
|
||||
for shape in [
|
||||
"@heimdall:gamecult.org",
|
||||
"meta@gamecult.org",
|
||||
|
|
@ -606,60 +503,28 @@ impl Value {
|
|||
}
|
||||
}
|
||||
|
||||
/// Huginn's real types against CultLib's bytes: each of the 14 vendored vectors decodes into the type
|
||||
/// that names it and re-encodes to the same bytes.
|
||||
/// Huginn's real types against CultLib's bytes. A decider's answers already decode (the answer keeps
|
||||
/// its 16 keys). The card and the record do not: `ForkCard` has no `raised_at` or `decider_count`,
|
||||
/// `ForkRecord` no `answerer_count`, and `ForkDeskAnswer.answerer` is a non-null string, and each type
|
||||
/// refuses unknown keys. This pins the gap `cut-desk-feed-listing` closes; when it does, these
|
||||
/// refusals become successful decodes of the same bytes and this test changes with them.
|
||||
#[test]
|
||||
fn huginn_types_decode_and_re_encode_every_vendored_vector_byte_for_byte() {
|
||||
fn round_trip<T: serde::Serialize + serde::de::DeserializeOwned>(name: &str) {
|
||||
let bytes = vendored(name);
|
||||
let value = rmp_serde::from_slice::<T>(&bytes).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
assert!(rmp_serde::to_vec_named(&value).unwrap() == bytes, "{name} does not re-encode byte for byte");
|
||||
fn huginn_types_do_not_yet_carry_the_pinned_shapes() {
|
||||
use huginn_mind::desk_wire::ForkCard;
|
||||
for name in ["answer-counted", "answer-refused-stale"] {
|
||||
rmp_serde::from_slice::<ForkDeskAnswer>(&vendored(name)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
}
|
||||
assert_eq!(VENDORED.len(), 14);
|
||||
for (name, _) in VENDORED {
|
||||
match name.split('-').next().unwrap() {
|
||||
"card" => round_trip::<ForkCard>(name),
|
||||
"answer" => round_trip::<ForkDeskAnswer>(name),
|
||||
"entry" => round_trip::<ForkEntry>(name),
|
||||
other => panic!("{name}: no type for {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Negative first: a non-decider's bytes hold no account id, in any fixture Huginn writes for that view.
|
||||
#[test]
|
||||
fn a_non_decider_fixture_holds_no_account_id() {
|
||||
let ids = [READER, OTHER_DECIDER, OUTSIDER, NON_DECIDER];
|
||||
let withheld = |bytes: &[u8]| ids.iter().filter(|id| holds(bytes, id)).count();
|
||||
let files = fixtures();
|
||||
let bytes_of = |name: &str| files.iter().find(|(file, _)| file == name).unwrap_or_else(|| panic!("no fixture {name}")).1.clone();
|
||||
for name in ["list-open-non-decider.response.payload.msgpack", "read-non-decider.response.payload.msgpack", "record-withheld.payload.msgpack"] {
|
||||
let bytes = bytes_of(name);
|
||||
assert_eq!(withheld(&bytes), 0, "{name} carries an account id");
|
||||
}
|
||||
// The decider's twins do name them, so the search above can fail.
|
||||
for name in ["list-open.response.payload.msgpack", "record-whole.payload.msgpack"] {
|
||||
assert!(withheld(&bytes_of(name)) >= 3, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The record header is `86` with `answerer_count` fifth, the card `DE 00 12` with `raised_at` and
|
||||
/// `decider_count` where CultLib puts them, in Huginn's own bytes.
|
||||
#[test]
|
||||
fn huginns_own_card_and_record_bytes_have_the_pinned_headers_and_keys() {
|
||||
let card_bytes = rmp_serde::to_vec_named(&card(true, Some("2026-11-11T16:40:12Z"))).unwrap();
|
||||
assert_eq!(card_bytes[..3], [0xde, 0x00, 0x12]);
|
||||
assert_eq!(decode(&card_bytes).keys(), CARD_KEYS);
|
||||
check_card(&decode(&card_bytes), false);
|
||||
let withheld_bytes = rmp_serde::to_vec_named(&card(false, None)).unwrap();
|
||||
check_card(&decode(&withheld_bytes), true);
|
||||
assert_eq!(decode(&withheld_bytes).get("raised_at"), &Value::Nil);
|
||||
for decider in [true, false] {
|
||||
let record_bytes = rmp_serde::to_vec_named(&record(decider)).unwrap();
|
||||
assert_eq!(record_bytes[0], 0x86);
|
||||
let decoded = decode(&record_bytes);
|
||||
assert_eq!(decoded.keys(), RECORD_KEYS);
|
||||
assert_eq!(decoded.get("answerer_count").int(), 3);
|
||||
decoded.list_of_answers().iter().for_each(|answer| check_answer(answer, decider));
|
||||
fn refused<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> String {
|
||||
rmp_serde::from_slice::<T>(bytes).err().expect("the real type refuses these bytes").to_string()
|
||||
}
|
||||
assert!(refused::<ForkCard>(&vendored("card-operator-fork")).contains("raised_at"));
|
||||
assert!(refused::<ForkCard>(&vendored("card-withheld-deciders")).contains("raised_at"));
|
||||
for name in ["answer-withheld-answerer", "answer-withheld-answerer-revision", "answer-withheld-answerer-retraction"] {
|
||||
assert!(refused::<ForkDeskAnswer>(&vendored(name)).contains("string"), "{name}");
|
||||
}
|
||||
// The record is the entry's last key: its bytes run from the `86` after the key to the end.
|
||||
let entry = vendored("entry-open-counted");
|
||||
let key = [&[0xa6u8][..], b"record", &[0x86]].concat();
|
||||
let at = entry.windows(key.len()).position(|window| window == key).expect("the record key") + key.len() - 1;
|
||||
assert!(refused::<ForkRecord>(&entry[at..]).contains("answerer_count"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,9 +15,9 @@ Each case has up to four files:
|
|||
Hex is lowercase with one trailing newline. The fork id is a question Eureka's mind holds. The
|
||||
record's answers, notes and hash are synthetic.
|
||||
|
||||
**The listing gate is live in Huginn.** A reader who is not on the call's deciders sees only forks the
|
||||
Mind lists (`docs/desk-feed-door.md`); `list-empty.response` is what such a reader gets from a Mind with
|
||||
nothing listed.
|
||||
**The listing gate is not live.** On `main` every showable question goes to every reader. Do not
|
||||
put a Mind that holds private questions behind a live receiver before `cut-desk-feed-listing`
|
||||
lands (see `docs/desk-feed-door.md`).
|
||||
|
||||
| case | direction | content |
|
||||
|---|---|---|
|
||||
|
|
@ -25,16 +25,6 @@ nothing listed.
|
|||
| `list-open-cursor.request` | Bifrost to Huginn | `Forks`, status open, cursor `c42`, limit 50 |
|
||||
| `list-counts.request` | Bifrost to Huginn | `Forks`, status open, limit 0 (counts and stamp only) |
|
||||
| `read.request` | Bifrost to Huginn | `Fork` for one fork id |
|
||||
| `list-non-decider.request` | Bifrost to Huginn | `Forks` as above, from a subject who is not on the call's deciders |
|
||||
| `read-non-decider.request` | Bifrost to Huginn | `Fork`, from a subject who is not on the call's deciders |
|
||||
| `list-open.response` | Huginn to Bifrost | a decider's page of one open fork: card with `raised_at` a string, `decider_count` 2 and both ids, record with `answerer_count` 3 and every `answerer` named |
|
||||
| `list-open-non-decider.response` | Huginn to Bifrost | the same page for a non-decider: `deciders` empty, `decider_count` 2, every `answerer` nil, `answerer_count` 3; no account id anywhere in its bytes |
|
||||
| `read.response` | Huginn to Bifrost | a decider's read of one fork, `raised_at` nil |
|
||||
| `read-non-decider.response` | Huginn to Bifrost | the same read for a non-decider, `raised_at` nil, no account id |
|
||||
| `read-mxid-decider.request` | client to Huginn | a `Fork` whose first decider is a Matrix id, so outside the account grammar; refused at decode |
|
||||
| `read-mxid-decider.failure.response` | Huginn to Bifrost | the operation failure for it: `payload-not-a-request`, naming `deciders`, never quoting the id |
|
||||
| `read-email-subject.request` | client to Huginn | a `Fork` whose subject is an email address; refused at decode |
|
||||
| `read-email-subject.failure.response` | Huginn to Bifrost | the operation failure for it, naming `subject` |
|
||||
| `list-empty.response` | Huginn to Bifrost | an empty Mind, or nothing listed to this reader: counts 0, `forks: []` |
|
||||
| `list-counts.response` | Huginn to Bifrost | the limit-0 answer: open 3, recorded 5, `forks: []` |
|
||||
| `read-unknown.response` | Huginn to Bifrost | `NotStored` `fork_unknown` (Bifrost: 404) |
|
||||
|
|
@ -45,10 +35,10 @@ nothing listed.
|
|||
| `unavailable.response` | Huginn to Bifrost | `Refused` `Unavailable` (Bifrost: 503 for this Mind) |
|
||||
| `failure.response` | Huginn to Bifrost | operation failure, `payloadSchema` `gamecult.cultnet.operation_failure.v1` (Bifrost: 503) |
|
||||
| `error.response` | Huginn to Bifrost | CultNet `Error` message, no payload (Bifrost: 503) |
|
||||
| `record-whole` | fragment | `gamecult.fork.record.v0` in a decider's view: all four answer variants (Counted, Revision, Refused, Retraction) by three accounts, answerer ids and notes whole, `answerer_count` 3 (6 keys) |
|
||||
| `record-withheld` | fragment | the same record in a non-decider's view: every `answerer` nil, notes whole, `answerer_count` 3 |
|
||||
| `record-whole` | fragment | `gamecult.fork.record.v0` with all four answer variants (Counted, Revision, Refused, Retraction) by three accounts, answerer ids and notes whole: what the door sends today (5 keys, no `answerer_count`) |
|
||||
|
||||
The reader-count shapes (`raised_at`, `decider_count`, `answerer_count`, nullable `answerer`) are
|
||||
also CultLib's own bytes, vendored unedited in `cultlib-d3025d3c/` (see its README for the pinned
|
||||
commit and each vector). Huginn's types decode every one of them and re-encode it byte for byte;
|
||||
the fixtures above are what Huginn's encoders write for the same shapes.
|
||||
CultLib's own bytes, vendored unedited in `cultlib-d3025d3c/` (see its README for the pinned commit and
|
||||
each vector). They are not Huginn's output: Huginn's types do not carry those shapes yet.
|
||||
`cut-desk-feed-listing` and `cut-desk-feed-raised-at` replace them with entry-bearing fixtures the
|
||||
encoders write, after decoding these bytes into the real types.
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
Source: `GameCult/CultLib` at commit `d3025d3c19674803ad32eb2335461b8cbc22bd28` (#118, on
|
||||
`3a51bbab` #117, on `af914253` #115), file `contracts/cultnet/governance/fork-card-vectors.json`. Each `.msgpack` file is
|
||||
the vector's `messagePackHex` decoded to bytes, nothing else changed. Do not edit them or rewrite them
|
||||
from Huginn's encoders: they are the reference Huginn's types are checked against (see
|
||||
from Huginn's encoders: Huginn's own types do not carry these shapes yet (see
|
||||
`docs/desk-feed-door.md`). To re-pin, take the new commit's vectors and update the sha here, in
|
||||
`docs/desk-feed-door.md` and in `CULTLIB_SHA` in `desk_feed_fixtures.rs`.
|
||||
|
||||
|
|
@ -25,4 +25,4 @@ from Huginn's encoders: they are the reference Huginn's types are checked agains
|
|||
| `entry-withheld-closed-with-ruling-and-a-refusal` | `transport.entry.valid` `withheld_closed_with_ruling_and_a_refusal` | its non-decider twin, count 2 |
|
||||
|
||||
The test `desk_feed_fixtures.rs` checks each file's SHA-256, decodes it with a decoder of its own
|
||||
(not `rmp_serde`), then decodes it into Huginn's real type and re-encodes it, byte for byte.
|
||||
(not `rmp_serde`), and then tries Huginn's real types.
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
000001a287a96d6573736167654964a36d2d35a96f7065726174696f6ea5666f726b73a77061796c6f6164d9f06761564762334a726334616b62576c755a4b5a6c64584a6c6132476e63335669616d566a644e6b6b4f5755345a44646a4e6d49744e5745304f5330304d7a67794c574978595441745a6a6c6c4f475133597a5a694e5745307147526c59326c6b5a584a7a6b746b6b4e575977597a4a694d5755744f4745305a433030597a4e694c546c6c4e3259744d574579596a4e6a4e4751315a545a6d32535177596a6c6b4e32557a59533032597a49784c54526d4e5467745954426b4e4330355a54686d4e324532596a566a4e47536d633352686448567a704739775a57366d5933567963323979774b5673615731706444493daf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61b6687567696e6e2e6465736b5f726571756573742e7631ad736368656d6156657273696f6ebc63756c746e65742e6f7065726174696f6e5f726571756573742e7630a9736572766963654964ab687567696e6e2e6465736b
|
||||
|
|
@ -1 +0,0 @@
|
|||
81a5466f726b7386a46d696e64a6657572656b61a77375626a656374d92439653864376336622d356134392d343338322d623161302d663965386437633662356134a8646563696465727392d92435663063326231652d386134642d346333622d396537662d316132623363346435653666d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a6737461747573a46f70656ea6637572736f72c0a56c696d697432
|
||||
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>¥Forks†¤mind¦eureka§subjectÙ$9e8d7c6b-5a49-4382-b1a0-f9e8d7c6b5a4¨deciders’Ù$5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6fÙ$0b9d7e3a-6c21-4f58-a0d4-9e8f7a6b5c4d¦status¤open¦cursorÀ¥limit2
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
000001738aab646961676e6f737469637391b57061796c6f61642d6e6f742d612d72657175657374a96d6573736167654964a36d2d38a96f7065726174696f6ea4666f726ba77061796c6f6164d9606771526a6232526c745842686557787659575174626d39304c574574636d56786457567a644b64745a584e7a5957646c3253466d615756735a43424762334a724c6e4e31596d706c5933513649476c75646d467361575174646d46736457553daf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61d92567616d6563756c742e63756c746e65742e6f7065726174696f6e5f6661696c7572652e7631ad736368656d6156657273696f6ebd63756c746e65742e6f7065726174696f6e5f726573706f6e73652e7630a9736572766963654964ab687567696e6e2e6465736baf736f7572636552756e74696d654964ad687567696e6e2d657572656b61a6737461747573a872656a6563746564
|
||||
|
|
@ -1 +0,0 @@
|
|||
82a4636f6465b57061796c6f61642d6e6f742d612d72657175657374a76d657373616765d9216669656c6420466f726b2e7375626a6563743a20696e76616c69642d76616c7565
|
||||
|
|
@ -1 +0,0 @@
|
|||
うcodeオpayload-not-a-requestァmessageル!field Fork.subject: invalid-value
|
||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
000001ad87a96d6573736167654964a36d2d38a96f7065726174696f6ea4666f726ba77061796c6f6164d9fc6761524762334a72684b686b5a574e705a47567963354c5a4a44566d4d474d79596a466c4c5468684e4751744e474d7a596930355a54646d4c5446684d6d497a597a526b4e5755325a746b6b4d4749355a44646c4d3245744e6d4d794d5330305a6a55344c5745775a4451744f5755345a6a64684e6d4931597a526b70325a76636d74666157545a4d475631636d56725953317a64574a7a64484a68644755366358566c63335270623234365a47567a6179317361584e306157356e4c57463164476876636d6c30656152746157356b706d5631636d56725961647a64574a715a574e307357316c644746415a3246745a574e316248517562334a6eaf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61b6687567696e6e2e6465736b5f726571756573742e7631ad736368656d6156657273696f6ebc63756c746e65742e6f7065726174696f6e5f726571756573742e7630a9736572766963654964ab687567696e6e2e6465736b
|
||||
|
|
@ -1 +0,0 @@
|
|||
81a4466f726b84a8646563696465727392d92435663063326231652d386134642d346333622d396537662d316132623363346435653666d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a46d696e64a6657572656b61a77375626a656374b16d6574614067616d6563756c742e6f7267
|
||||
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>¤Fork„¨deciders’Ù$5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6fÙ$0b9d7e3a-6c21-4f58-a0d4-9e8f7a6b5c4d§fork_idÙ0eureka-substrate:question:desk-listing-authority¤mind¦eureka§subject±meta@gamecult.org
|
||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
000001778aab646961676e6f737469637391b57061796c6f61642d6e6f742d612d72657175657374a96d6573736167654964a36d2d37a96f7065726174696f6ea4666f726ba77061796c6f6164d9646771526a6232526c745842686557787659575174626d39304c574574636d56786457567a644b64745a584e7a5957646c3253566d615756735a43424762334a724c6d526c59326c6b5a584a7a577a42644f694270626e5a6862476c6b4c585a686248566caf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61d92567616d6563756c742e63756c746e65742e6f7065726174696f6e5f6661696c7572652e7631ad736368656d6156657273696f6ebd63756c746e65742e6f7065726174696f6e5f726573706f6e73652e7630a9736572766963654964ab687567696e6e2e6465736baf736f7572636552756e74696d654964ad687567696e6e2d657572656b61a6737461747573a872656a6563746564
|
||||
|
|
@ -1 +0,0 @@
|
|||
82a4636f6465b57061796c6f61642d6e6f742d612d72657175657374a76d657373616765d9256669656c6420466f726b2e64656369646572735b305d3a20696e76616c69642d76616c7565
|
||||
|
|
@ -1 +0,0 @@
|
|||
うcodeオpayload-not-a-requestァmessageル%field Fork.deciders[0]: invalid-value
|
||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
000001b687a96d6573736167654964a36d2d37a96f7065726174696f6ea4666f726ba77061796c6f6164da01046761524762334a72684b686b5a574e705a47567963354b325147686c6157316b595778734f6d64686257566a645778304c6d39795a396b6b4d4749355a44646c4d3245744e6d4d794d5330305a6a55344c5745775a4451744f5755345a6a64684e6d4931597a526b70325a76636d74666157545a4d475631636d56725953317a64574a7a64484a68644755366358566c63335270623234365a47567a6179317361584e306157356e4c57463164476876636d6c30656152746157356b706d5631636d56725961647a64574a715a574e30325351315a6a426a4d6d49785a5330345954526b4c54526a4d3249744f5755335a69307859544a694d324d305a44566c4e6d593daf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61b6687567696e6e2e6465736b5f726571756573742e7631ad736368656d6156657273696f6ebc63756c746e65742e6f7065726174696f6e5f726571756573742e7630a9736572766963654964ab687567696e6e2e6465736b
|
||||
|
|
@ -1 +0,0 @@
|
|||
81a4466f726b84a8646563696465727392b6406865696d64616c6c3a67616d6563756c742e6f7267d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a46d696e64a6657572656b61a77375626a656374d92435663063326231652d386134642d346333622d396537662d316132623363346435653666
|
||||
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>¤Fork„¨deciders’¶@heimdall:gamecult.orgÙ$0b9d7e3a-6c21-4f58-a0d4-9e8f7a6b5c4d§fork_idÙ0eureka-substrate:question:desk-listing-authority¤mind¦eureka§subjectÙ$5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6f
|
||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
000001ca87a96d6573736167654964a36d2d36a96f7065726174696f6ea4666f726ba77061796c6f6164da01186761524762334a72684b52746157356b706d5631636d56725961647a64574a715a574e30325351355a54686b4e324d3259693031595451354c54517a4f444974596a46684d43316d4f5755345a44646a4e6d49315954536f5a47566a6157526c636e4f53325351315a6a426a4d6d49785a5330345954526b4c54526a4d3249744f5755335a69307859544a694d324d305a44566c4e6d625a4a4442694f5751335a544e684c545a6a4d6a45744e4759314f4331684d4751304c546c6c4f47593359545a694e574d305a4b646d62334a7258326c6b3254426c64584a6c6132457463335669633352795958526c4f6e46315a584e30615739754f6d526c6332737462476c7a64476c755a7931686458526f62334a7064486b3daf7061796c6f6164456e636f64696e67b26d6573736167657061636b2d626173653634ad7061796c6f6164536368656d61b6687567696e6e2e6465736b5f726571756573742e7631ad736368656d6156657273696f6ebc63756c746e65742e6f7065726174696f6e5f726571756573742e7630a9736572766963654964ab687567696e6e2e6465736b
|
||||
|
|
@ -1 +0,0 @@
|
|||
81a4466f726b84a46d696e64a6657572656b61a77375626a656374d92439653864376336622d356134392d343338322d623161302d663965386437633662356134a8646563696465727392d92435663063326231652d386134642d346333622d396537662d316132623363346435653666d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479
|
||||
|
|
@ -1 +0,0 @@
|
|||
<EFBFBD>¤Fork„¤mind¦eureka§subjectÙ$9e8d7c6b-5a49-4382-b1a0-f9e8d7c6b5a4¨deciders’Ù$5f0c2b1e-8a4d-4c3b-9e7f-1a2b3c4d5e6fÙ$0b9d7e3a-6c21-4f58-a0d4-9e8f7a6b5c4d§fork_idÙ0eureka-substrate:question:desk-listing-authority
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
|
|
@ -1 +1 @@
|
|||
86ad736368656d6156657273696f6eb767616d6563756c742e666f726b2e7265636f72642e7630a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438b1636f756e7465645f616e737765725f6964a26e31ae616e7377657265725f636f756e7403a7616e737765727394de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e31a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a7436f756e746564a26f66c0a87265747261637473c0a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465be5468652061736b6572206c6973747320686572206f776e20666f726b732eab616e7377657265645f6174b4323032362d31312d31315431373a30303a30305aab72656365697665645f6174b4323032362d31312d31315431373a30303a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92435663063326231652d386134642d346333622d396537662d316132623363346435653666a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303031de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e32a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a85265766973696f6ea26f66a26e31a87265747261637473c0a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465a74167726565642eab616e7377657265645f6174b4323032362d31312d31315431373a30353a30305aab72656365697665645f6174b4323032362d31312d31315431373a30353a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303032de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e33a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a752656675736564a26f66c0a87265747261637473c0a4636f6465ad6e6f745f615f64656369646572ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465a74d6520746f6f2eab616e7377657265645f6174b4323032362d31312d31315431373a30363a30305aab72656365697665645f6174b4323032362d31312d31315431373a30363a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92463336131663265342d376236642d346538662d396130622d316332643365346635613662a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303033de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e34a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65aa52657472616374696f6ea26f66c0a87265747261637473a26e32a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365c0a46e6f7465c0ab616e7377657265645f6174b4323032362d31312d31315431373a30373a30305aab72656365697665645f6174b4323032362d31312d31315431373a30373a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303034
|
||||
85ad736368656d6156657273696f6eb767616d6563756c742e666f726b2e7265636f72642e7630a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438b1636f756e7465645f616e737765725f6964a26e31a7616e737765727394de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e31a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a7436f756e746564a26f66c0a87265747261637473c0a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465be5468652061736b6572206c6973747320686572206f776e20666f726b732eab616e7377657265645f6174b4323032362d31312d31315431373a30303a30305aab72656365697665645f6174b4323032362d31312d31315431373a30303a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92435663063326231652d386134642d346333622d396537662d316132623363346435653666a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303031de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e32a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a85265766973696f6ea26f66a26e31a87265747261637473c0a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465a74167726565642eab616e7377657265645f6174b4323032362d31312d31315431373a30353a30305aab72656365697665645f6174b4323032362d31312d31315431373a30353a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303032de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e33a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a752656675736564a26f66c0a87265747261637473c0a4636f6465ad6e6f745f615f64656369646572ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465a74d6520746f6f2eab616e7377657265645f6174b4323032362d31312d31315431373a30363a30305aab72656365697665645f6174b4323032362d31312d31315431373a30363a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92463336131663265342d376236642d346538662d396130622d316332643365346635613662a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303033de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e34a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65aa52657472616374696f6ea26f66c0a87265747261637473a26e32a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365c0a46e6f7465c0ab616e7377657265645f6174b4323032362d31312d31315431373a30373a30305aab72656365697665645f6174b4323032362d31312d31315431373a30373a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572d92430623964376533612d366332312d346635382d613064342d396538663761366235633464a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303034
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
86ad736368656d6156657273696f6eb767616d6563756c742e666f726b2e7265636f72642e7630a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438b1636f756e7465645f616e737765725f6964a26e31ae616e7377657265725f636f756e7403a7616e737765727394de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e31a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a7436f756e746564a26f66c0a87265747261637473c0a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465be5468652061736b6572206c6973747320686572206f776e20666f726b732eab616e7377657265645f6174b4323032362d31312d31315431373a30303a30305aab72656365697665645f6174b4323032362d31312d31315431373a30303a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572c0a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303031de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e32a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a85265766973696f6ea26f66a26e31a87265747261637473c0a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465a74167726565642eab616e7377657265645f6174b4323032362d31312d31315431373a30353a30305aab72656365697665645f6174b4323032362d31312d31315431373a30353a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572c0a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303032de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e33a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65a752656675736564a26f66c0a87265747261637473c0a4636f6465ad6e6f745f615f64656369646572ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365ab61736b696e672d6d696e64a46e6f7465a74d6520746f6f2eab616e7377657265645f6174b4323032362d31312d31315431373a30363a30305aab72656365697665645f6174b4323032362d31312d31315431373a30363a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572c0a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303033de0010ad736368656d6156657273696f6eb767616d6563756c742e6465736b5f616e737765722e7630a9616e737765725f6964a26e34a7666f726b5f6964d930657572656b612d7375627374726174653a7175657374696f6e3a6465736b2d6c697374696e672d617574686f72697479a76f7574636f6d65aa52657472616374696f6ea26f66c0a87265747261637473a26e32a4636f6465c0ac6f7074696f6e735f68617368d94037643935666338376435333234323036313166653431356331646566323761333434373631376262363832333566343665336166313330616561333631633438a663686f696365c0a46e6f7465c0ab616e7377657265645f6174b4323032362d31312d31315431373a30373a30305aab72656365697665645f6174b4323032362d31312d31315431373a30373a30305aaf636c61696d5f696e5f667574757265c2a8616e737765726572c0a9617574686f72697479a64d656d626572aa726571756573745f6964d92430303030303030302d303030302d343030302d383030302d303030303030303030303034
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
|
|
@ -9,13 +9,13 @@ publish.workspace = true
|
|||
# operator's brakes: a root-owned per-instance CultCache
|
||||
# store (`control`), the operator's CLI over it (`cli`, the `mind-control`
|
||||
# binary) and the one fail-closed reader every acting organ calls
|
||||
# (`control::read_effective`). It also holds her units under systemd (`launch`)
|
||||
# and her port to her mind (`queue`). The heartbeat (`heartbeat`, the
|
||||
# `mind-heartbeat` binary) wakes her by starting her unit. The actuator
|
||||
# (`control::read_effective`). It also holds the launch primitive (`launch`,
|
||||
# `queue`): the one way her organs open a run and start its unit. The heartbeat
|
||||
# (`heartbeat`, the `mind-heartbeat` binary) runs the shared heartbeat over them. The actuator
|
||||
# (`self_run`, the `mind-self-run` binary) carries her one open Self run.
|
||||
#
|
||||
# The Persona organ (`persona`, the `mind-persona` binary) reads the brakes and
|
||||
# carries no turn until the three-stage turn lands (map C3). The connector transport is ModelConnector's kit client, pinned to
|
||||
# The Persona organ (`persona`, the `mind-persona` binary) drains her pending chat
|
||||
# through ports. The connector transport is ModelConnector's kit client, pinned to
|
||||
# the kit's revision (`connector`); the chat transport is cultnet-rs's RUDP client
|
||||
# to Bifrost's mouth (`chat_rudp`). `rmp-serde` is the chat documents' positional
|
||||
# MessagePack codec (`chat_client`); `sha2` derives the mouth's connection id from
|
||||
|
|
@ -23,11 +23,11 @@ publish.workspace = true
|
|||
# two until the workspace pin and the kit's meet.
|
||||
# `rmp-serde` is also the lease wire (`lease_client`): the connector's MessagePack frames.
|
||||
#
|
||||
# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Persona stage's prompt (`projection`), so
|
||||
# that membrane's text stays Ghostlight's. The Projector's frame is Huginn's own (map section 16.3), and so is the one quote
|
||||
# locator (`projection::span`, map 16.30.4); `unicode-segmentation` serves it.
|
||||
# Every stage asks through the connector kit's client (`model-connector`).
|
||||
# `toml` reads `persona-tuning.toml`, the Projector's knobs (`projection::tuning`); parse and serde only.
|
||||
# The stream organ (`stream`, the `mind-stream` binary) builds its Projector prompt with Ghostlight's
|
||||
# `ghostlight-persona-projection`, pinned to a revision, so the membrane's text stays Ghostlight's; it
|
||||
# asks its Projector through the connector kit's client (`model-connector`, one turn per tick) and speaks to the base
|
||||
# model's host on loopback over `ureq` 3 with default features off (plain HTTP, no TLS), as the
|
||||
# daemon's embedder does, and stays below 3.4 for the same reason.
|
||||
#
|
||||
# `serde_json` reads Claude Code's stream-json, a foreign owner's wire (`self_run`);
|
||||
# `uuid`'s v5 makes a Self run's session id derivable from the run's id.
|
||||
|
|
@ -41,17 +41,12 @@ eureka-pipeline = { path = "../eureka-pipeline" }
|
|||
eureka-state = { path = "../eureka-state", default-features = false }
|
||||
ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" }
|
||||
huginn-mind = { path = "../huginn-mind" }
|
||||
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector" }
|
||||
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector" }
|
||||
rmp-serde = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
toml = { version = "0.9", default-features = false, features = ["std", "serde", "parse"] }
|
||||
unicode-general-category = "1"
|
||||
# Clips on grapheme boundaries (`projection::select::clip`), so no ZWJ sequence is split; already in the graph through Ghostlight.
|
||||
unicode-segmentation = "1"
|
||||
# The domain digest's forge reads (`projection::domain`, map 16.22.2): plain HTTP to the forge's loopback API, the same
|
||||
# crate and features the daemon's forge read uses, so the graph gains no crate.
|
||||
ureq = { version = "~3.3", default-features = false }
|
||||
uuid = { version = "1", default-features = false, features = ["v5"] }
|
||||
|
||||
|
|
@ -59,9 +54,8 @@ uuid = { version = "1", default-features = false, features = ["v5"] }
|
|||
libc = "0.2"
|
||||
# The lease socket: SCM_RIGHTS receive with MSG_CMSG_CLOEXEC and the descriptor
|
||||
# duplicates, as safe calls (the library forbids unsafe code). Already in the
|
||||
# graph through tempfile; this adds its `net` feature, and `fs` for the attachment
|
||||
# saver's descriptor-relative writes (openat, linkat, unlinkat).
|
||||
rustix = { version = "1", default-features = false, features = ["std", "net", "fs"] }
|
||||
# graph through tempfile; this adds its `net` feature only.
|
||||
rustix = { version = "1", default-features = false, features = ["std", "net"] }
|
||||
|
||||
# `syn`, `quote` and `proc-macro2` read the library's own source for
|
||||
# tests/public_surface.rs, which pins its public surface. All three are already
|
||||
|
|
@ -71,9 +65,9 @@ proc-macro2 = "1"
|
|||
quote = "1"
|
||||
syn = { version = "2", features = ["full"] }
|
||||
tempfile = "3"
|
||||
# A real kit server (`serve` over a scripted `ProviderBackend`) proves the Projector's connector wire, not a fake of it.
|
||||
# A real kit server (`serve` over a scripted `ProviderBackend`) proves the stream's Projector wire, not a fake of it.
|
||||
# Same revision as the dependency; the `daemon` feature is test-only.
|
||||
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5", package = "model-connector", features = ["daemon"] }
|
||||
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector", features = ["daemon"] }
|
||||
|
||||
[lib]
|
||||
name = "mind_body"
|
||||
|
|
@ -91,6 +85,10 @@ path = "src/bin/mind-self-run.rs"
|
|||
name = "mind-persona"
|
||||
path = "src/bin/mind-persona.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "mind-stream"
|
||||
path = "src/bin/mind-stream.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "mind-heartbeat"
|
||||
path = "src/bin/mind-heartbeat.rs"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# mind-body
|
||||
|
||||
The Mind's body: the control store, the unit launcher, the `mind-heartbeat`, the
|
||||
inert `mind-persona` organ and the `mind-self-run` actuator.
|
||||
The Mind's body: the control store, the launch primitive, the `mind-heartbeat`
|
||||
timeline and the `mind-self-run` actuator.
|
||||
|
||||
`mind-self-run --instance <slug> [--endpoint rudp://<ip>:<port>]` runs inside
|
||||
`mind-self@<instance>`. It finds her one open Self run, starts `claude` over
|
||||
|
|
@ -12,9 +12,7 @@ wrong or the mind cannot be reached.
|
|||
|
||||
## The heartbeat
|
||||
|
||||
`mind-heartbeat` is the one process that decides who wakes and when. It starts a Persona's unit and writes no Mind: the beat (`HEARTBEAT_BEAT_S`, default 1800 s) goes to the idle, released Mind that has waited longest, bent by a member addressing her, and the operator or another Mind naming a Persona wakes her at once, once per message. `mind-heartbeat timeline` prints its latest record.
|
||||
|
||||
`mind-persona` reads the brakes and exits `dead`, or drains: one turn in each room with a waking line (at most three), one put of her state and one trace record per turn, one ack. `mind-persona trace --instance <slug> [--last N]` prints her trace. Nothing launches `mind-self-run`.
|
||||
`mind-heartbeat` is the one process that decides who wakes and when: each beat falls when the Minds' voted tempo has passed and goes to the Mind that has waited longest, bent by the urgency she declares and a member addressing her; the operator tagging or naming a Persona launches her at once. `mind-heartbeat timeline` prints its latest record.
|
||||
|
||||
The actuator has its own ignored test, `the_real_bin_finds_her_run_...` in
|
||||
`tests/self_run.rs`: the real `mind-self-run` against the real daemon with a
|
||||
|
|
@ -29,22 +27,3 @@ Mutation testing of the actuator, with the globs that reach the library and the
|
|||
binary: `cargo mutants -p mind-body -f "**/src/self_run.rs" -f
|
||||
"**/src/bin/mind-self-run.rs"`. The binary's mutants are killed only by the
|
||||
lane above.
|
||||
|
||||
## Before the live switch
|
||||
|
||||
The Persona turn's reads run live only once the heartbeat switch lands. Simulations and harness runs read fixtures
|
||||
(`[domain]`, `[cast.domain]`) and need none of this. One gamecult-ops change carries all of it, ruled by Self on
|
||||
2026-11-20:
|
||||
|
||||
- **The forge, for persona uids.** `mind_fence`'s `persona` chain rejects every local TCP port but 4110, 80 and 443, so
|
||||
a Persona cannot reach the forge's loopback API (`http://127.0.0.1:3310`), and port 80 only redirects to HTTPS. Her
|
||||
domain digest and her `repo` reads need an accept for tcp 127.0.0.1:3310 from `@persona_uids`. Until then a live read
|
||||
fails whole and the packet leaves the section out, as designed. mind-body carries no TLS; the forge is read on loopback.
|
||||
- **Web reads (K24).** A `web` read fetches a page whose address stands in her prose or in what reached her. The
|
||||
persona chain lets public addresses out (it rejects only local, private, link-local and multicast ones), so egress on
|
||||
tcp 80 and 443 to the public internet is already open for persona uids; what is missing is TLS: mind-body carries none,
|
||||
so a live `https` read fails as "the read failed". A live web read needs either a TLS-capable client in the organ or an
|
||||
egress fetcher on loopback for persona uids (an accept beside 4110 in `persona`); it is one ops-and-body decision with
|
||||
the forge accept above. Repo reads use the forge accept above; mind reads use her read door.
|
||||
- **Her read door.** Each Persona reaches only her own door (`huginn` set: uid . port). The digest and her reads use it
|
||||
as `HUGINN_ENDPOINT`; nothing to change.
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
responder 3: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 2 lines are the Minds' alone.
|
||||
responder 4: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko answered it. Meta, who runs the place last spoke a few minutes ago. The last 3 lines are the Minds' alone.
|
||||
responder 5: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 4 lines are the Minds' alone.
|
||||
responder 6: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 5 lines are the Minds' alone.
|
||||
responder 7: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 6 lines are the Minds' alone.
|
||||
responder 8: Meta, who runs the place asked the room a question, and "weksa", someone he does not know; "heimdall", someone he does not know; Kiko; "libby", someone he does not know; "void", someone he does not know; "nibu", someone he does not know; "aqua", someone he does not know answered it. Meta, who runs the place last spoke a few minutes ago. The last 7 lines a…
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
quiet-beat.toml: - the conversation: Someone he does not know has been talking to the room; Kiko has been talking to the room. | The last 3 lines are the Minds' alone.
|
||||
operator-warm.toml: - the conversation: Meta, who runs the place has been talking with him. | Meta, who runs the place is waiting on him. Meta, who runs the place last spoke just now.
|
||||
mind-teases.toml: - the conversation: Kiko has been talking with him; he has been talking to the room; someone he does not know has been talking to the room. | The last 3 lines are the Minds' alone.
|
||||
deru-passing.toml: - the conversation: Someone he does not know has been talking to the room; Deru has been talking to the room. | Deru last spoke just now.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue