create-lathe 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/bin/create-lathe.js +80 -0
  4. package/dist/framework.lock +113 -0
  5. package/dist/package/crates/instrument/Cargo.lock +415 -0
  6. package/dist/package/crates/instrument/Cargo.toml +27 -0
  7. package/dist/package/crates/instrument/examples/instrument.rs +73 -0
  8. package/dist/package/crates/instrument/src/client.rs +128 -0
  9. package/dist/package/crates/instrument/src/lib.rs +32 -0
  10. package/dist/package/crates/instrument/src/logging.rs +109 -0
  11. package/dist/package/crates/instrument/src/protocol.rs +49 -0
  12. package/dist/package/crates/instrument/src/registry.rs +166 -0
  13. package/dist/package/crates/instrument/src/selftest.rs +314 -0
  14. package/dist/package/crates/instrument/src/server.rs +303 -0
  15. package/dist/package/crates/instrument/tests/command_log.rs +60 -0
  16. package/dist/package/crates/instrument/tests/round_trip.rs +134 -0
  17. package/dist/package/crates/instrument/tests/selftest_fail.rs +25 -0
  18. package/dist/package/crates/instrument/tests/selftest_pass.rs +24 -0
  19. package/dist/package/crates/instrument/tests/support/mod.rs +38 -0
  20. package/dist/package/pi/context/journal-de-lot.md +24 -0
  21. package/dist/package/pi/context/tech-skill.md +19 -0
  22. package/dist/package/pi/context/ticket-closed.md +18 -0
  23. package/dist/package/scripts/framework.py +1314 -0
  24. package/dist/package/scripts/gates.py +1134 -0
  25. package/dist/package/scripts/setup.py +195 -0
  26. package/dist/package/skills/bootstrap/SKILL.md +110 -0
  27. package/dist/package/skills/documentation/SKILL.md +110 -0
  28. package/dist/package/skills/documentation/references/agents-md.md +70 -0
  29. package/dist/package/skills/documentation/references/corpus.md +112 -0
  30. package/dist/package/skills/journal/SKILL.md +81 -0
  31. package/dist/package/skills/journal/references/entry.md +172 -0
  32. package/dist/package/skills/lathe/SKILL.md +168 -0
  33. package/dist/package/skills/lathe/evals/routing.md +196 -0
  34. package/dist/package/skills/lathe/references/install.md +128 -0
  35. package/dist/package/skills/lathe/references/invariants.md +31 -0
  36. package/dist/package/skills/mutants/SKILL.md +85 -0
  37. package/dist/package/skills/mutants/references/cargo-mutants.md +176 -0
  38. package/dist/package/skills/mutants/references/triage.md +88 -0
  39. package/dist/package/skills/optimize/SKILL.md +87 -0
  40. package/dist/package/skills/optimize/references/codspeed.md +126 -0
  41. package/dist/package/skills/probe/SKILL.md +82 -0
  42. package/dist/package/skills/probe/references/wait-and-read.md +53 -0
  43. package/dist/package/skills/replicate-ui/SKILL.md +64 -0
  44. package/dist/package/skills/rust/SKILL.md +147 -0
  45. package/dist/package/skills/rust/references/errors.md +63 -0
  46. package/dist/package/skills/rust/references/unsafe.md +65 -0
  47. package/dist/package/skills/scaffold/SKILL.md +78 -0
  48. package/dist/package/skills/scaffold/profiles/rust-cli/.cargo/config.toml +2 -0
  49. package/dist/package/skills/scaffold/profiles/rust-cli/AGENTS.md +22 -0
  50. package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.lock +7 -0
  51. package/dist/package/skills/scaffold/profiles/rust-cli/Cargo.toml +17 -0
  52. package/dist/package/skills/scaffold/profiles/rust-cli/README.md +15 -0
  53. package/dist/package/skills/scaffold/profiles/rust-cli/deny.toml +14 -0
  54. package/dist/package/skills/scaffold/profiles/rust-cli/rustfmt.toml +2 -0
  55. package/dist/package/skills/scaffold/profiles/rust-cli/src/main.rs +38 -0
  56. package/dist/package/skills/scaffold/profiles/rust-cli/tests/cli.rs +27 -0
  57. package/dist/package/skills/scaffold/profiles/rust-library/.cargo/config.toml +2 -0
  58. package/dist/package/skills/scaffold/profiles/rust-library/AGENTS.md +21 -0
  59. package/dist/package/skills/scaffold/profiles/rust-library/Cargo.lock +7 -0
  60. package/dist/package/skills/scaffold/profiles/rust-library/Cargo.toml +18 -0
  61. package/dist/package/skills/scaffold/profiles/rust-library/README.md +15 -0
  62. package/dist/package/skills/scaffold/profiles/rust-library/deny.toml +14 -0
  63. package/dist/package/skills/scaffold/profiles/rust-library/rustfmt.toml +2 -0
  64. package/dist/package/skills/scaffold/profiles/rust-library/src/lib.rs +25 -0
  65. package/dist/package/skills/scaffold/profiles/rust-native-desktop/.cargo/config.toml +2 -0
  66. package/dist/package/skills/scaffold/profiles/rust-native-desktop/AGENTS.md +23 -0
  67. package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.lock +9252 -0
  68. package/dist/package/skills/scaffold/profiles/rust-native-desktop/Cargo.toml +24 -0
  69. package/dist/package/skills/scaffold/profiles/rust-native-desktop/README.md +15 -0
  70. package/dist/package/skills/scaffold/profiles/rust-native-desktop/deny.toml +35 -0
  71. package/dist/package/skills/scaffold/profiles/rust-native-desktop/rustfmt.toml +2 -0
  72. package/dist/package/skills/scaffold/profiles/rust-native-desktop/src/main.rs +74 -0
  73. package/dist/package/skills/scaffold/references/gates.md +29 -0
  74. package/dist/package/skills/scaffold/references/profiles.md +36 -0
  75. package/dist/package/skills/update/SKILL.md +115 -0
  76. package/dist/package/skills/verify-visual/SKILL.md +82 -0
  77. package/dist/package/skills/verify-visual/references/baseline.md +46 -0
  78. package/dist/package/skills/visual-loop/SKILL.md +72 -0
  79. package/dist/package/workflows/batch-to-review.md +41 -0
  80. package/dist/package/workflows/framework-improvement.md +38 -0
  81. package/dist/package/workflows/hard-bug.md +37 -0
  82. package/dist/package/workflows/new-rust-cli.md +33 -0
  83. package/dist/package/workflows/new-rust-desktop-app.md +41 -0
  84. package/dist/package/workflows/new-rust-library.md +34 -0
  85. package/dist/package/workflows/performance-work.md +41 -0
  86. package/dist/package/workflows/ui-change.md +40 -0
  87. package/package.json +33 -4
@@ -0,0 +1,109 @@
1
+ use std::{
2
+ fmt,
3
+ fs::OpenOptions,
4
+ io,
5
+ path::{Path, PathBuf},
6
+ str::FromStr,
7
+ };
8
+
9
+ use tracing_subscriber::{Layer, filter::LevelFilter, fmt as fmt_layer, layer::SubscriberExt};
10
+
11
+ /// Chemin du fichier JSON. Variable obligatoire : sans fichier, une application
12
+ /// GUI n'a aucun journal fiable.
13
+ pub const LOG_PATH_ENV: &str = "APP_LOG";
14
+ /// Niveau de journalisation optionnel (`error`, `warn`, `info`, `debug`,
15
+ /// `trace`, `off`). `info` par défaut.
16
+ pub const LOG_LEVEL_ENV: &str = "APP_LOG_LEVEL";
17
+
18
+ /// Garde le thread d'écriture vivant. Le déposer vide la file : c'est la raison
19
+ /// pour laquelle le binaire rend un code de sortie au lieu d'appeler
20
+ /// `std::process::exit`, qui peut perdre les derniers événements.
21
+ pub struct LoggingGuard {
22
+ _worker: tracing_appender::non_blocking::WorkerGuard,
23
+ }
24
+
25
+ #[derive(Debug)]
26
+ pub enum LoggingError {
27
+ MissingPath,
28
+ Open { path: PathBuf, source: io::Error },
29
+ InvalidLevel(String),
30
+ Install(String),
31
+ }
32
+
33
+ impl fmt::Display for LoggingError {
34
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
35
+ match self {
36
+ Self::MissingPath => write!(
37
+ formatter,
38
+ "{LOG_PATH_ENV} n'est pas défini: chemin du fichier de log requis"
39
+ ),
40
+ Self::Open { path, source } => write!(
41
+ formatter,
42
+ "ouverture du fichier de log « {} » impossible: {source}",
43
+ path.display()
44
+ ),
45
+ Self::InvalidLevel(level) => {
46
+ write!(formatter, "{LOG_LEVEL_ENV} invalide: « {level} »")
47
+ }
48
+ Self::Install(message) => {
49
+ write!(formatter, "abonné de traçage déjà installé: {message}")
50
+ }
51
+ }
52
+ }
53
+ }
54
+
55
+ impl std::error::Error for LoggingError {
56
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
57
+ match self {
58
+ Self::Open { source, .. } => Some(source),
59
+ Self::MissingPath | Self::InvalidLevel(_) | Self::Install(_) => None,
60
+ }
61
+ }
62
+ }
63
+
64
+ /// Installe les deux couches : JSON vers le fichier `path`, humain compact vers
65
+ /// stderr. Le fichier est ouvert en ajout : une session n'efface pas la précédente.
66
+ /// stdout n'est jamais utilisé, et stderr n'est pas bufferisé : chaque ligne est
67
+ /// écrite immédiatement.
68
+ pub fn init(path: &Path, level: LevelFilter) -> Result<LoggingGuard, LoggingError> {
69
+ let file = OpenOptions::new()
70
+ .create(true)
71
+ .append(true)
72
+ .open(path)
73
+ .map_err(|source| LoggingError::Open {
74
+ path: path.to_path_buf(),
75
+ source,
76
+ })?;
77
+ let (writer, worker) = tracing_appender::non_blocking(file);
78
+
79
+ let file_layer = fmt_layer::layer()
80
+ .json()
81
+ .with_ansi(false)
82
+ .with_writer(writer)
83
+ .with_filter(level);
84
+ let stderr_layer = fmt_layer::layer()
85
+ .compact()
86
+ .with_ansi(false)
87
+ .with_writer(io::stderr)
88
+ .with_filter(level);
89
+
90
+ let subscriber = tracing_subscriber::registry()
91
+ .with(file_layer)
92
+ .with(stderr_layer);
93
+ tracing::subscriber::set_global_default(subscriber)
94
+ .map_err(|error| LoggingError::Install(error.to_string()))?;
95
+
96
+ Ok(LoggingGuard { _worker: worker })
97
+ }
98
+
99
+ /// Lit `APP_LOG` et `APP_LOG_LEVEL`, puis installe les couches.
100
+ pub fn init_from_env() -> Result<LoggingGuard, LoggingError> {
101
+ let path = std::env::var_os(LOG_PATH_ENV).ok_or(LoggingError::MissingPath)?;
102
+ let level = match std::env::var(LOG_LEVEL_ENV) {
103
+ Ok(value) => {
104
+ LevelFilter::from_str(&value).map_err(|_| LoggingError::InvalidLevel(value))?
105
+ }
106
+ Err(_) => LevelFilter::INFO,
107
+ };
108
+ init(Path::new(&path), level)
109
+ }
@@ -0,0 +1,49 @@
1
+ use serde::{Deserialize, Serialize};
2
+ use serde_json::Value;
3
+
4
+ /// Une requête du protocole : le nom de la commande et ses paramètres.
5
+ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6
+ pub struct Request {
7
+ pub command: String,
8
+ #[serde(default)]
9
+ pub params: Value,
10
+ }
11
+
12
+ impl Request {
13
+ pub fn new(command: impl Into<String>, params: Value) -> Self {
14
+ Self {
15
+ command: command.into(),
16
+ params,
17
+ }
18
+ }
19
+ }
20
+
21
+ /// La réponse du protocole. `data` et `error` sont toujours présents, à `null`
22
+ /// quand ils ne s'appliquent pas : un client peut lire les deux champs sans
23
+ /// deviner la forme de l'objet.
24
+ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25
+ pub struct Response {
26
+ pub ok: bool,
27
+ #[serde(default)]
28
+ pub data: Option<Value>,
29
+ #[serde(default)]
30
+ pub error: Option<String>,
31
+ }
32
+
33
+ impl Response {
34
+ pub fn success(data: Value) -> Self {
35
+ Self {
36
+ ok: true,
37
+ data: Some(data),
38
+ error: None,
39
+ }
40
+ }
41
+
42
+ pub fn failure(error: impl Into<String>) -> Self {
43
+ Self {
44
+ ok: false,
45
+ data: None,
46
+ error: Some(error.into()),
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,166 @@
1
+ use std::{
2
+ collections::BTreeMap,
3
+ fmt,
4
+ sync::{Mutex, MutexGuard, PoisonError},
5
+ time::Duration,
6
+ };
7
+
8
+ use serde_json::{Value, json};
9
+
10
+ /// Signature d'une commande : elle reçoit les paramètres et rend une donnée ou
11
+ /// un message d'erreur destiné au client.
12
+ pub type Handler = Box<dyn Fn(Value) -> Result<Value, String> + Send + Sync>;
13
+
14
+ /// Les commandes du protocole, toujours disponibles et impossibles à écraser.
15
+ pub const PROTOCOL_COMMANDS: [&str; 4] = ["list", "state", "action", "wait"];
16
+
17
+ /// Plafond de `wait` : une commande ne peut pas immobiliser le serveur plus
18
+ /// longtemps que cette durée, même si le client demande davantage.
19
+ pub const MAX_WAIT_MS: u64 = 2_000;
20
+
21
+ #[derive(Debug, Default)]
22
+ struct State {
23
+ revision: u64,
24
+ values: BTreeMap<String, Value>,
25
+ }
26
+
27
+ /// Registre de commandes et état partagé du serveur.
28
+ pub struct Instrument {
29
+ commands: BTreeMap<String, Handler>,
30
+ state: Mutex<State>,
31
+ }
32
+
33
+ /// Refus d'enregistrement d'une commande.
34
+ #[derive(Debug, Clone, PartialEq, Eq)]
35
+ pub enum RegistryError {
36
+ EmptyName,
37
+ Reserved(String),
38
+ Duplicate(String),
39
+ }
40
+
41
+ impl fmt::Display for RegistryError {
42
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
43
+ match self {
44
+ Self::EmptyName => write!(formatter, "le nom de commande ne peut pas être vide"),
45
+ Self::Reserved(name) => {
46
+ write!(formatter, "le nom « {name} » est réservé au protocole")
47
+ }
48
+ Self::Duplicate(name) => {
49
+ write!(formatter, "la commande « {name} » est déjà enregistrée")
50
+ }
51
+ }
52
+ }
53
+ }
54
+
55
+ impl std::error::Error for RegistryError {}
56
+
57
+ impl Instrument {
58
+ pub fn new() -> Self {
59
+ Self {
60
+ commands: BTreeMap::new(),
61
+ state: Mutex::new(State::default()),
62
+ }
63
+ }
64
+
65
+ /// Enregistre une commande. Les noms du protocole et les doublons sont
66
+ /// refusés explicitement plutôt qu'écrasés en silence.
67
+ pub fn command<F>(
68
+ &mut self,
69
+ name: impl Into<String>,
70
+ handler: F,
71
+ ) -> Result<&mut Self, RegistryError>
72
+ where
73
+ F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
74
+ {
75
+ let name = name.into();
76
+ if name.trim().is_empty() {
77
+ return Err(RegistryError::EmptyName);
78
+ }
79
+ if PROTOCOL_COMMANDS.contains(&name.as_str()) {
80
+ return Err(RegistryError::Reserved(name));
81
+ }
82
+ if self.commands.contains_key(&name) {
83
+ return Err(RegistryError::Duplicate(name));
84
+ }
85
+ self.commands.insert(name, Box::new(handler));
86
+ Ok(self)
87
+ }
88
+
89
+ /// Exécute une commande et rend la donnée de réponse.
90
+ pub fn invoke(&self, command: &str, params: Value) -> Result<Value, String> {
91
+ match command {
92
+ "list" => Ok(json!({ "commands": self.command_names() })),
93
+ "state" => Ok(self.snapshot()),
94
+ "action" => self.action(params),
95
+ "wait" => wait(params),
96
+ _ => match self.commands.get(command) {
97
+ Some(handler) => handler(params),
98
+ None => Err(format!("commande inconnue: {command}")),
99
+ },
100
+ }
101
+ }
102
+
103
+ fn command_names(&self) -> Value {
104
+ let mut names: Vec<String> = PROTOCOL_COMMANDS
105
+ .iter()
106
+ .map(|name| (*name).to_owned())
107
+ .collect();
108
+ names.extend(self.commands.keys().cloned());
109
+ names.sort();
110
+ names.dedup();
111
+ Value::Array(names.into_iter().map(Value::String).collect())
112
+ }
113
+
114
+ fn snapshot(&self) -> Value {
115
+ let state = self.lock_state();
116
+ let values: serde_json::Map<String, Value> = state
117
+ .values
118
+ .iter()
119
+ .map(|(key, value)| (key.clone(), value.clone()))
120
+ .collect();
121
+ json!({ "revision": state.revision, "values": values })
122
+ }
123
+
124
+ fn action(&self, params: Value) -> Result<Value, String> {
125
+ let object = params
126
+ .as_object()
127
+ .ok_or("action: paramètres attendus sous forme d'objet")?;
128
+ let key = object
129
+ .get("key")
130
+ .and_then(Value::as_str)
131
+ .filter(|key| !key.is_empty())
132
+ .ok_or("action: 'key' doit être une chaîne non vide")?;
133
+ let value = object
134
+ .get("value")
135
+ .cloned()
136
+ .ok_or("action: 'value' est requis")?;
137
+
138
+ let mut state = self.lock_state();
139
+ state.revision = state.revision.saturating_add(1);
140
+ let revision = state.revision;
141
+ state.values.insert(key.to_owned(), value);
142
+ Ok(json!({ "revision": revision, "key": key }))
143
+ }
144
+
145
+ /// Un empoisonnement du verrou viendrait d'un panic interne, pas d'une
146
+ /// entrée cliente : on reprend l'état plutôt que de paniquer à nouveau.
147
+ fn lock_state(&self) -> MutexGuard<'_, State> {
148
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
149
+ }
150
+ }
151
+
152
+ impl Default for Instrument {
153
+ fn default() -> Self {
154
+ Self::new()
155
+ }
156
+ }
157
+
158
+ fn wait(params: Value) -> Result<Value, String> {
159
+ let requested = params
160
+ .get("milliseconds")
161
+ .and_then(Value::as_u64)
162
+ .ok_or("wait: 'milliseconds' doit être un entier positif ou nul")?;
163
+ let waited = requested.min(MAX_WAIT_MS);
164
+ std::thread::sleep(Duration::from_millis(waited));
165
+ Ok(json!({ "requested_ms": requested, "waited_ms": waited }))
166
+ }
@@ -0,0 +1,314 @@
1
+ use std::{
2
+ io::{self},
3
+ path::PathBuf,
4
+ sync::atomic::{AtomicU64, Ordering},
5
+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},
6
+ };
7
+
8
+ use serde_json::{Value, json};
9
+
10
+ use crate::{
11
+ client::{Client, ClientError, DEFAULT_TIMEOUT},
12
+ registry::Instrument,
13
+ server::{PathError, Server, validate_socket_path},
14
+ };
15
+
16
+ static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
17
+
18
+ /// Une assertion nommée : le nom reste stable, la raison est lisible par un
19
+ /// humain et par un script.
20
+ #[derive(Debug, Clone, PartialEq, Eq)]
21
+ pub struct Outcome {
22
+ pub name: &'static str,
23
+ pub result: Result<(), String>,
24
+ }
25
+
26
+ #[derive(Debug, Clone, Default)]
27
+ pub struct SelftestOptions {
28
+ /// Nom d'assertion à faire échouer volontairement. Sert à prouver que le
29
+ /// rapport distingue PASS de FAIL et rend bien le code de sortie 1.
30
+ pub break_assertion: Option<String>,
31
+ }
32
+
33
+ /// Exécute la suite sur un état temporaire : socket et registre neufs, répertoire
34
+ /// supprimé au retour. Aucun panic n'est utilisé comme mécanisme d'échec.
35
+ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
36
+ let mut checker = Checker {
37
+ outcomes: Vec::new(),
38
+ broken: options.break_assertion.clone(),
39
+ };
40
+
41
+ checker.check("socket-path-limit", || {
42
+ let limit = crate::server::MAX_SOCKET_PATH_BYTES;
43
+ let mut long = PathBuf::new();
44
+ long.push("a".repeat(limit + 20));
45
+ long.push("s");
46
+ let bytes = long.as_os_str().as_encoded_bytes().len();
47
+ match validate_socket_path(&long) {
48
+ Err(PathError::TooLong {
49
+ bytes: seen,
50
+ limit: seen_limit,
51
+ }) if seen == bytes && seen_limit == limit => Ok(()),
52
+ other => Err(format!(
53
+ "chemin de {bytes} octets non refusé comme prévu: {other:?}"
54
+ )),
55
+ }
56
+ });
57
+
58
+ let temp = match TempDir::new("in") {
59
+ Ok(temp) => temp,
60
+ Err(error) => {
61
+ checker.fail(
62
+ "temp-dir",
63
+ format!("répertoire temporaire impossible: {error}"),
64
+ );
65
+ return checker.outcomes;
66
+ }
67
+ };
68
+ let socket = temp.path().join("s");
69
+
70
+ let mut instrument = Instrument::new();
71
+ checker.check("register-custom", || {
72
+ instrument
73
+ .command("echo", |params| Ok(json!({ "echo": params })))
74
+ .map(|_| ())
75
+ .map_err(|error| error.to_string())
76
+ });
77
+
78
+ let mut server = match Server::start(instrument, &socket) {
79
+ Ok(server) => {
80
+ checker.check("server-start", || Ok(()));
81
+ server
82
+ }
83
+ Err(error) => {
84
+ checker.fail("server-start", error.to_string());
85
+ return checker.outcomes;
86
+ }
87
+ };
88
+
89
+ #[cfg(unix)]
90
+ checker.check("socket-permissions", || {
91
+ use std::os::unix::fs::PermissionsExt;
92
+
93
+ let mode = std::fs::metadata(&socket)
94
+ .map_err(|error| format!("métadonnées du socket: {error}"))?
95
+ .permissions()
96
+ .mode()
97
+ & 0o777;
98
+ if mode == 0o600 {
99
+ Ok(())
100
+ } else {
101
+ Err(format!("mode {mode:o}, attendu 600"))
102
+ }
103
+ });
104
+
105
+ let mut client = match Client::connect(&socket, DEFAULT_TIMEOUT) {
106
+ Ok(client) => {
107
+ checker.check("client-connect", || Ok(()));
108
+ client
109
+ }
110
+ Err(error) => {
111
+ checker.fail("client-connect", error.to_string());
112
+ server.shutdown();
113
+ return checker.outcomes;
114
+ }
115
+ };
116
+
117
+ checker.check("list", || {
118
+ let data = client.call("list", Value::Null).map_err(stringify)?;
119
+ let commands = data
120
+ .get("commands")
121
+ .and_then(Value::as_array)
122
+ .ok_or("réponse sans tableau 'commands'")?;
123
+ for expected in ["list", "state", "action", "wait", "echo"] {
124
+ if !commands.iter().any(|name| name.as_str() == Some(expected)) {
125
+ return Err(format!("commande absente de list: {expected}"));
126
+ }
127
+ }
128
+ Ok(())
129
+ });
130
+
131
+ checker.check("state-initial", || {
132
+ let data = client.call("state", Value::Null).map_err(stringify)?;
133
+ if data.get("revision").and_then(Value::as_u64) != Some(0) {
134
+ return Err(format!("révision initiale inattendue: {data}"));
135
+ }
136
+ let values = data
137
+ .get("values")
138
+ .and_then(Value::as_object)
139
+ .ok_or("réponse sans objet 'values'")?;
140
+ if !values.is_empty() {
141
+ return Err(format!("état initial non vide: {data}"));
142
+ }
143
+ Ok(())
144
+ });
145
+
146
+ checker.check("action", || {
147
+ let data = client
148
+ .call("action", json!({ "key": "selftest", "value": { "n": 1 } }))
149
+ .map_err(stringify)?;
150
+ if data.get("revision").and_then(Value::as_u64) != Some(1) {
151
+ return Err(format!("révision après action inattendue: {data}"));
152
+ }
153
+ Ok(())
154
+ });
155
+
156
+ checker.check("state-after-action", || {
157
+ let data = client.call("state", Value::Null).map_err(stringify)?;
158
+ let value = data
159
+ .get("values")
160
+ .and_then(|values| values.get("selftest"))
161
+ .and_then(|value| value.get("n"))
162
+ .and_then(Value::as_u64);
163
+ if value != Some(1) {
164
+ return Err(format!("valeur écrite absente de l'état: {data}"));
165
+ }
166
+ Ok(())
167
+ });
168
+
169
+ checker.check("custom-command", || {
170
+ let data = client.call("echo", json!({ "x": 1 })).map_err(stringify)?;
171
+ if data.get("echo") != Some(&json!({ "x": 1 })) {
172
+ return Err(format!("réponse de echo inattendue: {data}"));
173
+ }
174
+ Ok(())
175
+ });
176
+
177
+ checker.check("unknown-command", || {
178
+ match client.call("commande-qui-nexiste-pas", Value::Null) {
179
+ Err(ClientError::Remote(message)) if message.contains("inconnue") => Ok(()),
180
+ other => Err(format!("erreur inattendue: {other:?}")),
181
+ }
182
+ });
183
+
184
+ checker.check("invalid-params", || {
185
+ match client.call("action", json!({})) {
186
+ Err(ClientError::Remote(message)) if message.contains("key") => Ok(()),
187
+ other => Err(format!("erreur inattendue: {other:?}")),
188
+ }
189
+ });
190
+
191
+ checker.check("wait", || {
192
+ let started = Instant::now();
193
+ let data = client
194
+ .call("wait", json!({ "milliseconds": 5 }))
195
+ .map_err(stringify)?;
196
+ if data.get("waited_ms").and_then(Value::as_u64) != Some(5) {
197
+ return Err(format!("attente rapportée inattendue: {data}"));
198
+ }
199
+ let elapsed = started.elapsed();
200
+ if elapsed < Duration::from_millis(5) {
201
+ return Err(format!("wait a rendu trop tôt: {elapsed:?}"));
202
+ }
203
+ if elapsed > Duration::from_secs(1) {
204
+ return Err(format!("wait a dépassé son plafond: {elapsed:?}"));
205
+ }
206
+ Ok(())
207
+ });
208
+
209
+ checker.check("client-timeout", || {
210
+ let mut impatient =
211
+ Client::connect(&socket, Duration::from_millis(100)).map_err(stringify)?;
212
+ let started = Instant::now();
213
+ match impatient.call("wait", json!({ "milliseconds": 400 })) {
214
+ Err(ClientError::Timeout) => {
215
+ if started.elapsed() > Duration::from_secs(1) {
216
+ return Err("le timeout client n'a pas borné l'attente".to_owned());
217
+ }
218
+ Ok(())
219
+ }
220
+ other => Err(format!("l'attente n'a pas été interrompue: {other:?}")),
221
+ }
222
+ });
223
+
224
+ drop(client);
225
+ server.shutdown();
226
+ checker.check("socket-removed", || {
227
+ if socket.exists() {
228
+ Err(format!(
229
+ "le socket subsiste après arrêt: {}",
230
+ socket.display()
231
+ ))
232
+ } else {
233
+ Ok(())
234
+ }
235
+ });
236
+
237
+ checker.outcomes
238
+ }
239
+
240
+ /// Imprime `PASS nom` ou `FAIL nom — raison`, une ligne par assertion. Rend
241
+ /// `true` seulement si toutes les assertions passent.
242
+ pub fn report(outcomes: &[Outcome], out: &mut dyn io::Write) -> bool {
243
+ let mut all_passed = true;
244
+ for outcome in outcomes {
245
+ let line = match &outcome.result {
246
+ Ok(()) => format!("PASS {}", outcome.name),
247
+ Err(reason) => {
248
+ all_passed = false;
249
+ format!("FAIL {} — {reason}", outcome.name)
250
+ }
251
+ };
252
+ if writeln!(out, "{line}").is_err() {
253
+ return false;
254
+ }
255
+ }
256
+ all_passed
257
+ }
258
+
259
+ struct Checker {
260
+ outcomes: Vec<Outcome>,
261
+ broken: Option<String>,
262
+ }
263
+
264
+ impl Checker {
265
+ fn check(&mut self, name: &'static str, assertion: impl FnOnce() -> Result<(), String>) {
266
+ if self.broken.as_deref() == Some(name) {
267
+ self.fail(name, format!("échec injecté (--break {name})"));
268
+ return;
269
+ }
270
+ self.outcomes.push(Outcome {
271
+ name,
272
+ result: assertion(),
273
+ });
274
+ }
275
+
276
+ fn fail(&mut self, name: &'static str, reason: impl Into<String>) {
277
+ self.outcomes.push(Outcome {
278
+ name,
279
+ result: Err(reason.into()),
280
+ });
281
+ }
282
+ }
283
+
284
+ fn stringify(error: impl std::fmt::Display) -> String {
285
+ error.to_string()
286
+ }
287
+
288
+ struct TempDir {
289
+ path: PathBuf,
290
+ }
291
+
292
+ impl TempDir {
293
+ fn new(prefix: &str) -> io::Result<Self> {
294
+ let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
295
+ let nanos = SystemTime::now()
296
+ .duration_since(UNIX_EPOCH)
297
+ .map(|duration| duration.as_nanos())
298
+ .unwrap_or(0);
299
+ let path =
300
+ std::env::temp_dir().join(format!("{prefix}-{}-{counter}-{nanos}", std::process::id()));
301
+ std::fs::create_dir(&path)?;
302
+ Ok(Self { path })
303
+ }
304
+
305
+ fn path(&self) -> &std::path::Path {
306
+ &self.path
307
+ }
308
+ }
309
+
310
+ impl Drop for TempDir {
311
+ fn drop(&mut self) {
312
+ let _ = std::fs::remove_dir_all(&self.path);
313
+ }
314
+ }