create-lathe 0.4.0 → 0.4.1

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.
package/README.md CHANGED
@@ -107,6 +107,30 @@ python3 <package>/scripts/framework.py doctor --project .
107
107
 
108
108
  `<package>` is this delivery, unpacked. `setup.py` is those four commands with the refusals ordered.
109
109
 
110
+ ### Trust the three rules
111
+
112
+ `.pi/context/` holds three rules that inject themselves at the moment they apply. Until each one is
113
+ **trusted**, the `no-more-agents-dot-md` extension arms a command guard, and without a UI every
114
+ medium/high bash action is blocked — measured, `python3 .agents/scripts/gates.py fast` among them. In
115
+ a headless run the guard says nothing about being armed, so the failure looks like a tool refusing
116
+ your work.
117
+
118
+ ```bash
119
+ npx create-lathe --trust # approve the three rules this install wrote, through the extension
120
+ ```
121
+
122
+ Without `--trust`, the same thing in Pi, once per file:
123
+
124
+ ```text
125
+ /nma trust .pi/context/journal-de-lot.md --yes
126
+ /nma trust .pi/context/tech-skill.md --yes
127
+ /nma trust .pi/context/ticket-closed.md --yes
128
+ ```
129
+
130
+ Trust is a security decision, so nothing here writes a trust store by hand: `--trust` runs the
131
+ extension's own command, which scans the file and records path plus SHA-256. `doctor` reports
132
+ `context 3/3 rules trusted` and warns when it is less.
133
+
110
134
  ### After installing
111
135
 
112
136
  Two ways in, both measured: type `/skill:lathe` in Pi, or tell your agent "use Lathe". Either one reads
@@ -117,6 +141,15 @@ A `/lathe` prompt template was written for this package and dropped: measured in
117
141
  fresh project, it was not expanded into a command, and shipping a shortcut that does nothing is worse
118
142
  than shipping one fewer shortcut. The skill command is registered by Pi itself.
119
143
 
144
+ ### What else appears in the tree
145
+
146
+ `.claude/skills/` — 42 symlinks to `.agents/skills/`. They are written by the upstream `npx skills add`,
147
+ not by Lathe, so Claude Code sees the same skills. Pi reads `.agents/skills/`; the symlinks are
148
+ compatible furniture, safe to ignore and safe to delete if nothing else uses them.
149
+
150
+ `.lathe/` — the mutation campaign's output. Written by `gates.py mutants`, git-ignored, and the only
151
+ place a mutation verdict lives.
152
+
120
153
  ### Update, uninstall
121
154
 
122
155
  - **Update:** run `npx create-lathe@latest`; it moves to the newer lock and writes only the files that
@@ -35,9 +35,12 @@ const COMMANDS = {
35
35
  function usage() {
36
36
  console.log(`create-lathe ${manifest.version}
37
37
 
38
- npx create-lathe [dir] install Lathe into dir (default: .)
39
- npx create-lathe doctor [dir] verify an installation
40
- npx create-lathe update [dir] move an installation to this package's lock
38
+ npx create-lathe [dir] install Lathe into dir (default: .)
39
+ npx create-lathe --trust [dir] also approve the .pi/context rules it writes
40
+ npx create-lathe --force [dir] overwrite files that differ
41
+ npx create-lathe --offline [dir] never reach the network
42
+ npx create-lathe doctor [dir] verify an installation
43
+ npx create-lathe update [dir] move an installation to this package's lock
41
44
  npx create-lathe --version
42
45
 
43
46
  Environment: LATHE_PYTHON (default: python3)`);
@@ -55,7 +58,12 @@ function main(argv) {
55
58
  }
56
59
 
57
60
  const name = first && COMMANDS[first] ? first : "install";
58
- const target = first && COMMANDS[first] ? rest[0] || "." : first || ".";
61
+ // A flag is never a directory: `create-lathe --trust` used to install into a folder
62
+ // named `--trust`. Flags go to setup.py; the first bare argument is the target.
63
+ const given = first && COMMANDS[first] ? rest : argv;
64
+ const flags = given.filter((arg) => arg.startsWith("-"));
65
+ const bare = given.filter((arg) => !arg.startsWith("-"));
66
+ const target = bare[0] || ".";
59
67
  const command = COMMANDS[name];
60
68
  const script = path.join(dist, "package", "scripts", command.script);
61
69
  if (!fs.existsSync(script)) {
@@ -63,7 +71,7 @@ function main(argv) {
63
71
  return 1;
64
72
  }
65
73
 
66
- const args = [script, ...command.args, "--project", target];
74
+ const args = [script, ...command.args, ...flags, "--project", target];
67
75
  const done = spawnSync(python, args, { stdio: "inherit" });
68
76
  if (done.error) {
69
77
  if (done.error.code === "ENOENT") {
@@ -1,6 +1,6 @@
1
1
  {
2
- "commit": "99ebbdd",
3
- "digest": "9a5f38e1dd57a74e4486827e3b0849ba56f6e032a8b47568a8c226bdf6149e83",
2
+ "commit": "01bdcc6",
3
+ "digest": "fe404a5a2f7b87686aad49b6f2e1abf0f6921e4ec77a18378d0f68fb71f4456a",
4
4
  "framework": "lathe",
5
5
  "source": "unknown",
6
6
  "trees": {
@@ -13,13 +13,15 @@
13
13
  "instrument/src/logging.rs": "9fb97f59002c318f36bd072124e001086907fc7449fff70ae28922a2f6c0865e",
14
14
  "instrument/src/protocol.rs": "255ca485e4c8af1affb8def2d49c09e90506be7a20c678988c85124528d4ab5a",
15
15
  "instrument/src/registry.rs": "551f5ed2d51d16d280ebdfc1952275dbba6fa4cf2b7b50ed08e8438975426dba",
16
- "instrument/src/selftest.rs": "92c1f7aef6467682d9ad65f54fd9a6c274b234d1a11cd73ae07faea161292af8",
17
- "instrument/src/server.rs": "e668fc3a317aaed718554696488469905dbfa3f290e8e519a05d41de743ca26f",
16
+ "instrument/src/selftest.rs": "c1cd0eb8d2ff97fc14e976454feccc73543fc7937cca6c062c4e0c7a0299b809",
17
+ "instrument/src/server.rs": "b6ee8f99871ebe5c9a191e3e1c4e9ac0f1728da74ca15efe690a59c58d6bc9cf",
18
18
  "instrument/tests/command_log.rs": "3137034d4114efdf515608ecd0fc62a7e9efb661c09d1da6ffe42a741ddb3b4c",
19
- "instrument/tests/round_trip.rs": "bd246ccd8812a6449371693130628dfbeb394ad10714055dc75d7a631a9a58b1",
19
+ "instrument/tests/erreurs.rs": "c4e758ef02863831ddef3184769d4cda261f9095519b22b349cc9e3b67b65721",
20
+ "instrument/tests/round_trip.rs": "b565dfc8a5e6cdb774c7d3591da86180e7b26535b19044a8c4490b70a735c917",
20
21
  "instrument/tests/selftest_fail.rs": "6dd0f747227faf87deff97564f0b066ab573b80102f74621345358e0824b891e",
21
22
  "instrument/tests/selftest_pass.rs": "f37751c5bb6fd1579851ad2dc8ab9d0eed2ee855c8503bff000cee7f6b1bb769",
22
- "instrument/tests/support/mod.rs": "aee91e833bed4a46eb5c90d22a9c2121161c48ab67778a66b6986943f5c012cc"
23
+ "instrument/tests/selftest_temps.rs": "7b86e874533e8ead3c3c09e6415ee2e49850518e5c7748ad5f9dec066f30ac00",
24
+ "instrument/tests/support/mod.rs": "dc5172da8611ea3359300abd712241bc3e8c8cf4df2fcca1457a4edae3e38654"
23
25
  },
24
26
  "pi": {
25
27
  "context/journal-de-lot.md": "a3c0dba986f139ba710d794f39fe121b6f469f20369d30016f5e2e35ad0c6f58",
@@ -27,9 +29,9 @@
27
29
  "context/ticket-closed.md": "34a9f7955cf05618e24b3c98b8fbdcc27420f9ea4cc1a73ac38a5b482ecfadf8"
28
30
  },
29
31
  "scripts": {
30
- "framework.py": "d20838177b0c99782e705c0b9f9c0af4d0e6e372f3033bf4b8109e2fbebd3eab",
31
- "gates.py": "b80ed8b24e00bd834a67f321b6522c06d2e624964b8887fd9b36348e7952f2f7",
32
- "setup.py": "fdd396a062c06c54e3bbd2d19938132e0f3c34492e521fb19736b291778bb715"
32
+ "framework.py": "d6b98b3e4974ef484d636fc1a0eaa4d3c9cbb9cb294e45fa74a517dada76dc5b",
33
+ "gates.py": "dd438cc0bf8476060dddf8f68dfa8d167163dab0d925efba62f336245244093a",
34
+ "setup.py": "ccb63db1e40cd514eebac6a76aad3220a7447ef51863034f2de124fe2a103dba"
33
35
  },
34
36
  "skills": {
35
37
  "bootstrap/SKILL.md": "c96daf2705bc15ff06aaad0b9873e5f964b356fac97c28dc440585438e026e6a",
@@ -38,12 +40,12 @@
38
40
  "documentation/references/corpus.md": "a8f703b027c81005c548ba7025c748e70b8b290fea2014e2ce9deadf943438c4",
39
41
  "journal/SKILL.md": "9e2fe143a892a71b85a6785356b68a423840ce16afdb15bdda4ce706144e1b8c",
40
42
  "journal/references/entry.md": "db005d441373df0594a3f7f21739ed8edaefb871cfd9e39021032b67680fd121",
41
- "lathe/SKILL.md": "4ccade9b5e0e367473d072d157c0183eda814bc1eee64d8a5f90b3cae0499517",
42
- "lathe/evals/routing.md": "053c1c335097401b908be2ea9e894b579e2ccd9421f4ab28294e39b47a4d3c2e",
43
- "lathe/references/install.md": "576251bdfd2be787a4d795e6d66f0d37f0c67a935176d7a28bfcfda517fc35e2",
43
+ "lathe/SKILL.md": "949a92fde1077460dd8c150b6a30916ac5d0f6353e5ea87a161e3586b2e17b72",
44
+ "lathe/evals/routing.md": "ec71375e566655da49dbf8f7622b71a3809ccecefd90f5cdb6e6ec202965a12e",
45
+ "lathe/references/install.md": "3b1558ca003a2d9c47c4eace36c93895c1c2337a13885b750071d9e9e3fcb909",
44
46
  "lathe/references/invariants.md": "85999b2907d659cd71b379a39d8db0a6d1cf662624bd1c7c81b3ca3779703f86",
45
- "mutants/SKILL.md": "6df3b74314b5077f08ddb04e4a2470757f9f79379807cd236ac307edabd85ad3",
46
- "mutants/references/cargo-mutants.md": "c767804d4e79410fbefd0b51e4811b3fe59abf1df9d72c12654afa690ccaad07",
47
+ "mutants/SKILL.md": "c6a69291a8355a293c77603d7859cbe6ba4548226d62a679a7ca1fac5165d9ab",
48
+ "mutants/references/cargo-mutants.md": "118654b3220063d85590c45885c6e83cdf5352127721267dcd6f6b74b9b01775",
47
49
  "mutants/references/triage.md": "695bc911d844801b5a6527bacfa2e5c7d042c4bcdca0639a3b9703e0f53b7252",
48
50
  "optimize/SKILL.md": "a4f6bd4bb1fb865349c8c34c1dbf82bd6f2037d7da68bbdbd7d76748b69183c5",
49
51
  "optimize/references/codspeed.md": "180762de94b32eddf964d4bd80f1782f960670461eaec7f0d5756934a3295df5",
@@ -109,5 +111,5 @@
109
111
  "skills": 39
110
112
  }
111
113
  },
112
- "version": "0.4.0"
114
+ "version": "0.4.1"
113
115
  }
@@ -43,7 +43,12 @@ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
43
43
  let mut long = PathBuf::new();
44
44
  long.push("a".repeat(limit + 20));
45
45
  long.push("s");
46
- let bytes = long.as_os_str().as_encoded_bytes().len();
46
+ // The expected number is computed here, not read back from the path buffer: a
47
+ // `validate_socket_path` that reported the wrong length would then fail instead of
48
+ // agreeing with itself (review finding 2026-11-29). 120 bytes of "a", one separator
49
+ // that `push` inserts, one "s" — measured, and the previous value was wrong by exactly
50
+ // the separator.
51
+ let bytes = limit + 20 + 1 + 1;
47
52
  match validate_socket_path(&long) {
48
53
  Err(PathError::TooLong {
49
54
  bytes: seen,
@@ -115,21 +120,23 @@ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
115
120
  };
116
121
 
117
122
  checker.check("list", || {
118
- let data = client.call("list", Value::Null).map_err(stringify)?;
123
+ let data = client
124
+ .call("list", Value::Null)
125
+ .map_err(|error| error.to_string())?;
119
126
  let commands = data
120
127
  .get("commands")
121
128
  .and_then(Value::as_array)
122
129
  .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
- }
130
+ match missing_command(commands, &["list", "state", "action", "wait", "echo"]) {
131
+ Some(name) => Err(format!("commande absente de list: {name}")),
132
+ None => Ok(()),
127
133
  }
128
- Ok(())
129
134
  });
130
135
 
131
136
  checker.check("state-initial", || {
132
- let data = client.call("state", Value::Null).map_err(stringify)?;
137
+ let data = client
138
+ .call("state", Value::Null)
139
+ .map_err(|error| error.to_string())?;
133
140
  if data.get("revision").and_then(Value::as_u64) != Some(0) {
134
141
  return Err(format!("révision initiale inattendue: {data}"));
135
142
  }
@@ -146,7 +153,7 @@ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
146
153
  checker.check("action", || {
147
154
  let data = client
148
155
  .call("action", json!({ "key": "selftest", "value": { "n": 1 } }))
149
- .map_err(stringify)?;
156
+ .map_err(|error| error.to_string())?;
150
157
  if data.get("revision").and_then(Value::as_u64) != Some(1) {
151
158
  return Err(format!("révision après action inattendue: {data}"));
152
159
  }
@@ -154,7 +161,9 @@ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
154
161
  });
155
162
 
156
163
  checker.check("state-after-action", || {
157
- let data = client.call("state", Value::Null).map_err(stringify)?;
164
+ let data = client
165
+ .call("state", Value::Null)
166
+ .map_err(|error| error.to_string())?;
158
167
  let value = data
159
168
  .get("values")
160
169
  .and_then(|values| values.get("selftest"))
@@ -167,7 +176,9 @@ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
167
176
  });
168
177
 
169
178
  checker.check("custom-command", || {
170
- let data = client.call("echo", json!({ "x": 1 })).map_err(stringify)?;
179
+ let data = client
180
+ .call("echo", json!({ "x": 1 }))
181
+ .map_err(|error| error.to_string())?;
171
182
  if data.get("echo") != Some(&json!({ "x": 1 })) {
172
183
  return Err(format!("réponse de echo inattendue: {data}"));
173
184
  }
@@ -192,31 +203,19 @@ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
192
203
  let started = Instant::now();
193
204
  let data = client
194
205
  .call("wait", json!({ "milliseconds": 5 }))
195
- .map_err(stringify)?;
206
+ .map_err(|error| error.to_string())?;
196
207
  if data.get("waited_ms").and_then(Value::as_u64) != Some(5) {
197
208
  return Err(format!("attente rapportée inattendue: {data}"));
198
209
  }
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(())
210
+ waited_within_bounds(started.elapsed())
207
211
  });
208
212
 
209
213
  checker.check("client-timeout", || {
210
- let mut impatient =
211
- Client::connect(&socket, Duration::from_millis(100)).map_err(stringify)?;
214
+ let mut impatient = Client::connect(&socket, Duration::from_millis(100))
215
+ .map_err(|error| error.to_string())?;
212
216
  let started = Instant::now();
213
217
  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
- }
218
+ Err(ClientError::Timeout) => client_timeout_within_bound(started.elapsed()),
220
219
  other => Err(format!("l'attente n'a pas été interrompue: {other:?}")),
221
220
  }
222
221
  });
@@ -237,6 +236,42 @@ pub fn run(options: &SelftestOptions) -> Vec<Outcome> {
237
236
  checker.outcomes
238
237
  }
239
238
 
239
+ /// La première commande attendue qui manque à `list`, s'il y en a une : la
240
+ /// recherche est isolée pour qu'un test la vérifie sans serveur.
241
+ fn missing_command<'a>(commands: &[Value], expected: &[&'a str]) -> Option<&'a str> {
242
+ expected.iter().copied().find(|name| {
243
+ !commands
244
+ .iter()
245
+ .any(|command| command.as_str() == Some(*name))
246
+ })
247
+ }
248
+
249
+ /// Borne basse de l'attente mesurée : `wait` a été appelé pour 5 ms, donc en
250
+ /// dessous la commande a menti sur sa durée.
251
+ const MIN_WAITED: Duration = Duration::from_millis(5);
252
+
253
+ /// Plafond de l'attente mesurée, côté serveur comme côté client.
254
+ const MAX_WAITED: Duration = Duration::from_secs(1);
255
+
256
+ fn waited_within_bounds(elapsed: Duration) -> Result<(), String> {
257
+ if elapsed < MIN_WAITED {
258
+ return Err(format!("wait a rendu trop tôt: {elapsed:?}"));
259
+ }
260
+ if elapsed > MAX_WAITED {
261
+ return Err(format!("wait a dépassé son plafond: {elapsed:?}"));
262
+ }
263
+ Ok(())
264
+ }
265
+
266
+ /// Le client devait couper l'attente bien avant son plafond : au-delà, c'est le
267
+ /// serveur qui a borné l'attente, pas le timeout du client.
268
+ fn client_timeout_within_bound(elapsed: Duration) -> Result<(), String> {
269
+ if elapsed > MAX_WAITED {
270
+ return Err("le timeout client n'a pas borné l'attente".to_owned());
271
+ }
272
+ Ok(())
273
+ }
274
+
240
275
  /// Imprime `PASS nom` ou `FAIL nom — raison`, une ligne par assertion. Rend
241
276
  /// `true` seulement si toutes les assertions passent.
242
277
  pub fn report(outcomes: &[Outcome], out: &mut dyn io::Write) -> bool {
@@ -281,10 +316,6 @@ impl Checker {
281
316
  }
282
317
  }
283
318
 
284
- fn stringify(error: impl std::fmt::Display) -> String {
285
- error.to_string()
286
- }
287
-
288
319
  struct TempDir {
289
320
  path: PathBuf,
290
321
  }
@@ -312,3 +343,33 @@ impl Drop for TempDir {
312
343
  let _ = std::fs::remove_dir_all(&self.path);
313
344
  }
314
345
  }
346
+
347
+ #[cfg(test)]
348
+ mod tests {
349
+ use super::*;
350
+
351
+ #[test]
352
+ fn une_commande_absente_de_list_est_nommee() {
353
+ let commands = [json!("list"), json!("echo")];
354
+ assert_eq!(missing_command(&commands, &["list"]), None);
355
+ assert_eq!(missing_command(&commands, &["absent"]), Some("absent"));
356
+ }
357
+
358
+ #[test]
359
+ fn une_attente_trop_courte_ou_trop_longue_est_refusee() {
360
+ let too_early = MIN_WAITED - Duration::from_millis(1);
361
+ assert!(waited_within_bounds(too_early).is_err());
362
+ assert!(waited_within_bounds(MIN_WAITED).is_ok());
363
+ assert!(waited_within_bounds(MAX_WAITED).is_ok());
364
+ let too_late = MAX_WAITED + Duration::from_millis(1);
365
+ assert!(waited_within_bounds(too_late).is_err());
366
+ }
367
+
368
+ #[test]
369
+ fn un_timeout_client_au_dela_du_plafond_est_refuse() {
370
+ assert!(client_timeout_within_bound(Duration::from_millis(100)).is_ok());
371
+ assert!(client_timeout_within_bound(MAX_WAITED).is_ok());
372
+ let too_late = MAX_WAITED + Duration::from_nanos(1);
373
+ assert!(client_timeout_within_bound(too_late).is_err());
374
+ }
375
+ }
@@ -222,6 +222,23 @@ fn set_socket_permissions(path: &Path) -> Result<(), ServerError> {
222
222
  })
223
223
  }
224
224
 
225
+ /// Ce qu'une erreur d'acceptation signifie pour la boucle : une file vide se
226
+ /// repolle, toute autre erreur arrête le serveur. La décision est une fonction
227
+ /// pure, pour qu'un test la vérifie sans socket ni horloge.
228
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
229
+ enum AcceptAction {
230
+ Wait,
231
+ Stop,
232
+ }
233
+
234
+ fn accept_action(kind: io::ErrorKind) -> AcceptAction {
235
+ if kind == io::ErrorKind::WouldBlock {
236
+ AcceptAction::Wait
237
+ } else {
238
+ AcceptAction::Stop
239
+ }
240
+ }
241
+
225
242
  // Les connexions sont traitées l'une après l'autre : c'est un canal de
226
243
  // diagnostic, pas un serveur généraliste, et l'inactivité d'un client est
227
244
  // bornée par `CONNECTION_IDLE_TIMEOUT`.
@@ -233,11 +250,13 @@ fn accept_loop(listener: &LocalSocketListener, instrument: &Instrument, shutdown
233
250
  tracing::warn!(%error, "connexion interrompue");
234
251
  }
235
252
  }
236
- Err(error) if error.kind() == io::ErrorKind::WouldBlock => thread::sleep(ACCEPT_POLL),
237
- Err(error) => {
238
- tracing::error!(%error, "accept impossible, serveur arrêté");
239
- break;
240
- }
253
+ Err(error) => match accept_action(error.kind()) {
254
+ AcceptAction::Wait => thread::sleep(ACCEPT_POLL),
255
+ AcceptAction::Stop => {
256
+ tracing::error!(%error, "accept impossible, serveur arrêté");
257
+ break;
258
+ }
259
+ },
241
260
  }
242
261
  }
243
262
  }
@@ -256,8 +275,7 @@ fn serve_connection(stream: LocalSocketStream, instrument: &Instrument) -> io::R
256
275
  match stream.read_line(&mut line) {
257
276
  Ok(0) => return Ok(()),
258
277
  Ok(_) => {}
259
- Err(error) if is_timeout(&error) => return Ok(()),
260
- Err(error) => return Err(error),
278
+ Err(error) => return on_read_error(error),
261
279
  }
262
280
 
263
281
  let request = match serde_json::from_str::<Request>(&line) {
@@ -301,3 +319,45 @@ fn is_timeout(error: &io::Error) -> bool {
301
319
  io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
302
320
  )
303
321
  }
322
+
323
+ /// Une lecture qui expire ferme la connexion sans bruit : le client s'est tu et
324
+ /// son inactivité est déjà bornée. Toute autre erreur de transport remonte, pour
325
+ /// être journalisée par la boucle d'acceptation.
326
+ fn on_read_error(error: io::Error) -> io::Result<()> {
327
+ if is_timeout(&error) {
328
+ Ok(())
329
+ } else {
330
+ Err(error)
331
+ }
332
+ }
333
+
334
+ #[cfg(test)]
335
+ mod tests {
336
+ use super::*;
337
+
338
+ #[test]
339
+ fn une_file_vide_se_polle_et_une_erreur_arrete_le_serveur() {
340
+ assert_eq!(accept_action(io::ErrorKind::WouldBlock), AcceptAction::Wait);
341
+ assert_eq!(
342
+ accept_action(io::ErrorKind::ConnectionReset),
343
+ AcceptAction::Stop
344
+ );
345
+ assert_eq!(
346
+ accept_action(io::ErrorKind::PermissionDenied),
347
+ AcceptAction::Stop
348
+ );
349
+ }
350
+
351
+ #[test]
352
+ fn une_erreur_de_delai_ferme_la_connexion() {
353
+ assert!(on_read_error(io::Error::from(io::ErrorKind::WouldBlock)).is_ok());
354
+ assert!(on_read_error(io::Error::from(io::ErrorKind::TimedOut)).is_ok());
355
+ }
356
+
357
+ #[test]
358
+ fn une_erreur_de_transport_remonte() {
359
+ let error = on_read_error(io::Error::from(io::ErrorKind::ConnectionReset))
360
+ .expect_err("une erreur de transport ne doit pas être avalée");
361
+ assert_eq!(error.kind(), io::ErrorKind::ConnectionReset);
362
+ }
363
+ }
@@ -0,0 +1,167 @@
1
+ //! Les erreurs publiques expliquent leur cause : un message vide ou une chaîne
2
+ //! de cause absente rendent un refus indébogable pour l'appelant.
3
+
4
+ use std::{error::Error, io, path::PathBuf};
5
+
6
+ use instrument::{
7
+ ClientError, Instrument, RegistryError, ServerError, logging::LoggingError, server::PathError,
8
+ };
9
+ use serde_json::Value;
10
+
11
+ #[test]
12
+ fn les_messages_du_client_nomment_la_cause() {
13
+ let cases = [
14
+ (ClientError::Timeout, "délai"),
15
+ (
16
+ ClientError::Remote("refus explicite".to_owned()),
17
+ "refus explicite",
18
+ ),
19
+ (ClientError::Protocol("json cassé".to_owned()), "json cassé"),
20
+ (
21
+ ClientError::Connect(io::Error::other("socket absent")),
22
+ "socket absent",
23
+ ),
24
+ (
25
+ ClientError::Io(io::Error::other("tuyau cassé")),
26
+ "tuyau cassé",
27
+ ),
28
+ (ClientError::Path(PathError::Empty), "vide"),
29
+ ];
30
+
31
+ for (error, expected) in cases {
32
+ let message = error.to_string();
33
+ assert!(
34
+ message.contains(expected),
35
+ "message « {message} » sans « {expected} »"
36
+ );
37
+ }
38
+ }
39
+
40
+ #[test]
41
+ fn une_erreur_client_expose_sa_cause() {
42
+ assert!(
43
+ ClientError::Connect(io::Error::other("socket absent"))
44
+ .source()
45
+ .is_some(),
46
+ "une erreur de connexion doit garder sa cause"
47
+ );
48
+ assert!(
49
+ ClientError::Io(io::Error::other("tuyau cassé"))
50
+ .source()
51
+ .is_some(),
52
+ "une erreur d'échange doit garder sa cause"
53
+ );
54
+ assert!(
55
+ ClientError::Path(PathError::Empty).source().is_some(),
56
+ "un chemin refusé doit garder sa cause"
57
+ );
58
+ assert!(
59
+ ClientError::Timeout.source().is_none(),
60
+ "un délai n'a pas de cause système"
61
+ );
62
+ }
63
+
64
+ #[test]
65
+ fn les_messages_de_journalisation_nomment_la_cause() {
66
+ let cases = [
67
+ (LoggingError::MissingPath, "APP_LOG"),
68
+ (
69
+ LoggingError::Open {
70
+ path: PathBuf::from("/tmp/absent/app.log"),
71
+ source: io::Error::other("refus"),
72
+ },
73
+ "/tmp/absent/app.log",
74
+ ),
75
+ (LoggingError::InvalidLevel("bavard".to_owned()), "bavard"),
76
+ (
77
+ LoggingError::Install("abonné déjà posé".to_owned()),
78
+ "abonné déjà posé",
79
+ ),
80
+ ];
81
+
82
+ for (error, expected) in cases {
83
+ let message = error.to_string();
84
+ assert!(
85
+ message.contains(expected),
86
+ "message « {message} » sans « {expected} »"
87
+ );
88
+ }
89
+ }
90
+
91
+ #[test]
92
+ fn une_erreur_de_journalisation_expose_sa_cause() {
93
+ let open = LoggingError::Open {
94
+ path: PathBuf::from("/tmp/absent/app.log"),
95
+ source: io::Error::other("refus"),
96
+ };
97
+ assert!(
98
+ open.source().is_some(),
99
+ "une ouverture impossible doit garder sa cause"
100
+ );
101
+ assert!(
102
+ LoggingError::MissingPath.source().is_none(),
103
+ "une variable absente n'a pas de cause système"
104
+ );
105
+ }
106
+
107
+ #[test]
108
+ fn les_refus_d_enregistrement_nomment_la_commande() {
109
+ let mut instrument = Instrument::new();
110
+
111
+ match instrument.command("", |_| Ok(Value::Null)) {
112
+ Err(error) => {
113
+ assert_eq!(error, RegistryError::EmptyName);
114
+ assert!(error.to_string().contains("vide"), "message: {error}");
115
+ }
116
+ Ok(_) => panic!("un nom vide doit être refusé"),
117
+ }
118
+
119
+ match instrument.command("list", |_| Ok(Value::Null)) {
120
+ Err(error) => {
121
+ assert_eq!(error, RegistryError::Reserved("list".to_owned()));
122
+ assert!(error.to_string().contains("list"), "message: {error}");
123
+ }
124
+ Ok(_) => panic!("un nom du protocole doit être refusé"),
125
+ }
126
+
127
+ instrument
128
+ .command("echo", |_| Ok(Value::Null))
129
+ .expect("premier enregistrement de echo");
130
+
131
+ match instrument.command("echo", |_| Ok(Value::Null)) {
132
+ Err(error) => {
133
+ assert_eq!(error, RegistryError::Duplicate("echo".to_owned()));
134
+ assert!(error.to_string().contains("echo"), "message: {error}");
135
+ }
136
+ Ok(_) => panic!("un doublon doit être refusé"),
137
+ }
138
+ }
139
+
140
+ #[test]
141
+ fn un_refus_de_serveur_expose_sa_cause() {
142
+ let bind = ServerError::Bind {
143
+ path: PathBuf::from("/tmp/in-bind/s"),
144
+ source: io::Error::other("adresse déjà utilisée"),
145
+ };
146
+ assert!(
147
+ bind.source().is_some(),
148
+ "une liaison impossible doit garder sa cause"
149
+ );
150
+ assert!(
151
+ bind.to_string().contains("/tmp/in-bind/s"),
152
+ "message: {bind}"
153
+ );
154
+
155
+ let spawn = ServerError::Spawn {
156
+ source: io::Error::other("thread refusé"),
157
+ };
158
+ assert!(
159
+ spawn.source().is_some(),
160
+ "un démarrage impossible doit garder sa cause"
161
+ );
162
+
163
+ assert!(
164
+ ServerError::Path(PathError::Empty).source().is_some(),
165
+ "un chemin refusé doit garder sa cause"
166
+ );
167
+ }
@@ -1,10 +1,15 @@
1
1
  mod support;
2
2
 
3
- use std::{fs, path::PathBuf, time::Duration};
3
+ use std::{
4
+ fs,
5
+ path::PathBuf,
6
+ thread,
7
+ time::{Duration, Instant},
8
+ };
4
9
 
5
10
  use instrument::{
6
11
  Client, ClientError, Instrument, Server, ServerError,
7
- server::{MAX_SOCKET_PATH_BYTES, PathError},
12
+ server::{MAX_SOCKET_PATH_BYTES, PathError, validate_socket_path},
8
13
  };
9
14
  use serde_json::{Value, json};
10
15
  use support::TempDir;
@@ -87,15 +92,39 @@ fn aller_retour_de_commande_sur_le_socket() {
87
92
  assert!(!socket.exists(), "le socket doit disparaître à l'arrêt");
88
93
  }
89
94
 
95
+ #[test]
96
+ fn des_parametres_incomplets_nomment_le_champ_manquant() {
97
+ let temp = TempDir::new("in-params").expect("répertoire temporaire");
98
+ let socket = temp.socket();
99
+ let mut server = Server::start(Instrument::new(), &socket).expect("démarrage du serveur");
100
+
101
+ let mut client = Client::connect(&socket, Duration::from_secs(1)).expect("connexion");
102
+ match client.call("action", json!({})) {
103
+ Err(ClientError::Remote(message)) => assert!(
104
+ message.contains("key"),
105
+ "le refus doit nommer le champ manquant: {message}"
106
+ ),
107
+ other => panic!("refus de paramètres incomplets attendu, reçu {other:?}"),
108
+ }
109
+
110
+ drop(client);
111
+ server.shutdown();
112
+ }
113
+
90
114
  #[test]
91
115
  fn un_client_impatient_ne_bloque_pas_indefiniment() {
92
116
  let temp = TempDir::new("in-timeout").expect("répertoire temporaire");
93
117
  let socket = temp.socket();
94
118
  let mut server = Server::start(Instrument::new(), &socket).expect("démarrage du serveur");
95
119
 
96
- let mut impatient =
97
- Client::connect(&socket, Duration::from_millis(100)).expect("connexion impatiente");
98
- let started = std::time::Instant::now();
120
+ // 100 ms pour l'échange, mais une échéance de connexion : le serveur peut
121
+ // n'avoir encore rien accepté au moment où le client se présente.
122
+ let mut impatient = support::connect_avant_echeance(
123
+ &socket,
124
+ Duration::from_secs(5),
125
+ Duration::from_millis(100),
126
+ );
127
+ let started = Instant::now();
99
128
  match impatient.call("wait", json!({ "milliseconds": 400 })) {
100
129
  Err(ClientError::Timeout) => {}
101
130
  other => panic!("timeout attendu, reçu {other:?}"),
@@ -109,6 +138,73 @@ fn un_client_impatient_ne_bloque_pas_indefiniment() {
109
138
  server.shutdown();
110
139
  }
111
140
 
141
+ #[test]
142
+ fn un_serveur_en_attente_sert_toujours() {
143
+ let temp = TempDir::new("in-waiting").expect("répertoire temporaire");
144
+ let socket = temp.socket();
145
+ let server = Server::start(Instrument::new(), &socket).expect("démarrage du serveur");
146
+
147
+ let waiting = thread::spawn(move || server.wait());
148
+ thread::sleep(Duration::from_millis(100));
149
+ assert!(
150
+ !waiting.is_finished(),
151
+ "wait a rendu la main alors que le serveur n'a pas été arrêté"
152
+ );
153
+
154
+ let mut client =
155
+ support::connect_avant_echeance(&socket, Duration::from_secs(5), Duration::from_secs(1));
156
+ client.call("state", Value::Null).expect("état servi");
157
+ }
158
+
159
+ #[test]
160
+ fn un_serveur_inactif_accepte_une_connexion_tardive() {
161
+ let temp = TempDir::new("in-late").expect("répertoire temporaire");
162
+ let socket = temp.socket();
163
+ let mut server = Server::start(Instrument::new(), &socket).expect("démarrage du serveur");
164
+
165
+ // Cinq tours de sondage d'acceptation passent avant que quiconque se
166
+ // présente : une file vide ne doit pas arrêter le serveur.
167
+ thread::sleep(Duration::from_millis(50));
168
+
169
+ let mut client =
170
+ support::connect_avant_echeance(&socket, Duration::from_secs(5), Duration::from_secs(1));
171
+ client.call("state", Value::Null).expect("état servi");
172
+
173
+ drop(client);
174
+ server.shutdown();
175
+ }
176
+
177
+ #[test]
178
+ fn un_serveur_detruit_libere_son_socket() {
179
+ let temp = TempDir::new("in-drop").expect("répertoire temporaire");
180
+ let socket = temp.socket();
181
+ {
182
+ let _server = Server::start(Instrument::new(), &socket).expect("démarrage du serveur");
183
+ assert!(socket.exists(), "le serveur doit avoir lié son socket");
184
+ }
185
+
186
+ for _ in 0..100 {
187
+ if !socket.exists() {
188
+ return;
189
+ }
190
+ thread::sleep(Duration::from_millis(10));
191
+ }
192
+ panic!("le socket subsiste après destruction du serveur");
193
+ }
194
+
195
+ #[test]
196
+ fn un_chemin_de_socket_a_la_limite_est_accepte() {
197
+ let at_limit = PathBuf::from("a".repeat(MAX_SOCKET_PATH_BYTES));
198
+ assert_eq!(
199
+ at_limit.as_os_str().as_encoded_bytes().len(),
200
+ MAX_SOCKET_PATH_BYTES
201
+ );
202
+ assert!(
203
+ validate_socket_path(&at_limit).is_ok(),
204
+ "un chemin de exactement {MAX_SOCKET_PATH_BYTES} octets doit être accepté"
205
+ );
206
+ }
207
+
112
208
  #[test]
113
209
  fn un_chemin_de_socket_trop_long_est_refuse_explicitement() {
114
210
  let mut too_long = PathBuf::new();
@@ -0,0 +1,43 @@
1
+ //! Le selftest travaille sur un état temporaire : il ne doit rien laisser
2
+ //! derrière lui. Un binaire de test à lui seul, pour qu'aucun autre test ne
3
+ //! crée de répertoire pendant l'observation.
4
+
5
+ use std::{fs, path::PathBuf};
6
+
7
+ use instrument::selftest::{self, SelftestOptions};
8
+
9
+ /// Les répertoires que `selftest` crée dans le répertoire temporaire du système.
10
+ /// Eux seuls portent le préfixe `in-` suivi du pid de ce processus.
11
+ fn leftovers() -> Vec<PathBuf> {
12
+ let prefix = format!("in-{}-", std::process::id());
13
+ let Ok(entries) = fs::read_dir(std::env::temp_dir()) else {
14
+ return Vec::new();
15
+ };
16
+ let mut paths = entries
17
+ .filter_map(Result::ok)
18
+ .filter(|entry| entry.file_name().to_string_lossy().starts_with(&prefix))
19
+ .map(|entry| entry.path())
20
+ .collect::<Vec<_>>();
21
+ paths.sort();
22
+ paths
23
+ }
24
+
25
+ #[test]
26
+ fn le_selftest_ne_laisse_pas_de_repertoire_temporaire() {
27
+ let before = leftovers();
28
+
29
+ let outcomes = selftest::run(&SelftestOptions::default());
30
+ let mut output = Vec::new();
31
+ let passed = selftest::report(&outcomes, &mut output);
32
+ assert!(
33
+ passed,
34
+ "le selftest doit passer:\n{}",
35
+ String::from_utf8_lossy(&output)
36
+ );
37
+
38
+ let after = leftovers();
39
+ assert_eq!(
40
+ after, before,
41
+ "le selftest a laissé un répertoire temporaire derrière lui"
42
+ );
43
+ }
@@ -4,8 +4,11 @@ use std::{
4
4
  fs, io,
5
5
  path::{Path, PathBuf},
6
6
  sync::atomic::{AtomicU64, Ordering},
7
+ time::{Duration, Instant},
7
8
  };
8
9
 
10
+ use instrument::Client;
11
+
9
12
  static COUNTER: AtomicU64 = AtomicU64::new(0);
10
13
 
11
14
  /// Répertoire temporaire propre à ce test, supprimé au Drop. Les noms restent
@@ -36,3 +39,20 @@ impl Drop for TempDir {
36
39
  let _ = fs::remove_dir_all(&self.path);
37
40
  }
38
41
  }
42
+
43
+ /// Se connecte en réessayant jusqu'à l'échéance `window` : un serveur vivant
44
+ /// répond, un serveur arrêté ne répond jamais. Le client rendu garde `timeout`
45
+ /// comme délai de connexion et d'échange, donc un refus transitoire — celui d'un
46
+ /// serveur qui n'a pas encore appelé `accept` — n'est plus un verdict.
47
+ pub fn connect_avant_echeance(socket: &Path, window: Duration, timeout: Duration) -> Client {
48
+ let deadline = Instant::now() + window;
49
+ loop {
50
+ match Client::connect(socket, timeout) {
51
+ Ok(client) => return client,
52
+ Err(error) if Instant::now() >= deadline => {
53
+ panic!("connexion impossible au socket après {window:?}: {error}")
54
+ }
55
+ Err(_) => std::thread::sleep(Duration::from_millis(5)),
56
+ }
57
+ }
58
+ }
@@ -142,6 +142,8 @@ UPSTREAMS: tuple[dict[str, Any], ...] = (
142
142
  )
143
143
  # A declared dependency, not a bonus: the extension injects `.pi/context/*.md`, which
144
144
  # is how this framework states a rule at the moment it applies (BACKLOG I-03).
145
+ CONTEXT_DIR = Path(".pi") / "context"
146
+ TRUST_STORE = Path(".pi") / "agent" / "nma-trust.json"
145
147
  PI_DEPENDENCY = "no-more-agents-dot-md"
146
148
  PI_DEPENDENCY_HINT = "pi install git:github.com/TheophileBaudouin/No-More-Agents-Dot-MD"
147
149
  # Technology -> the official skill a project needs before using it. One entry today:
@@ -166,6 +168,37 @@ def fail(message: str, code: int = 1) -> int:
166
168
  return code
167
169
 
168
170
 
171
+ def trust_store() -> Path:
172
+ """`~/.pi/agent/nma-trust.json`, or the file `NMA_TRUST_FILE` names."""
173
+ override = os.environ.get("NMA_TRUST_FILE")
174
+ return Path(override) if override else Path.home() / TRUST_STORE
175
+
176
+
177
+ def context_trust(project: Path) -> tuple[list[str], list[str]]:
178
+ """The project's rule files, split into trusted and untrusted by content hash.
179
+
180
+ `no-more-agents-dot-md` arms its command guard as long as an untrusted rule file is
181
+ loaded, and without a UI every medium/high bash action is then blocked — including
182
+ `gates.py`. Trust is a security decision the user owns, so this only reports it
183
+ (E-55); `doctor` never grants it.
184
+ """
185
+ rules_dir = project / CONTEXT_DIR
186
+ if not rules_dir.is_dir():
187
+ return [], []
188
+ try:
189
+ store = json.loads(trust_store().read_text(encoding="utf-8"))
190
+ except (OSError, json.JSONDecodeError):
191
+ store = {}
192
+ if not isinstance(store, dict):
193
+ store = {}
194
+ trusted, untrusted = [], []
195
+ for path in sorted(rules_dir.glob("*.md")):
196
+ record = store.get(str(path.resolve()))
197
+ expected = record.get("sha256") if isinstance(record, dict) else None
198
+ (trusted if expected and expected == digest(path) else untrusted).append(path.name)
199
+ return trusted, untrusted
200
+
201
+
169
202
  def digest(path: Path) -> str:
170
203
  return hashlib.sha256(path.read_bytes()).hexdigest()
171
204
 
@@ -227,7 +260,7 @@ def build_lock() -> dict:
227
260
 
228
261
 
229
262
  def read_version() -> str:
230
- return "0.4.0"
263
+ return "0.4.1"
231
264
 
232
265
 
233
266
  def read_commit(root: Path) -> str:
@@ -572,6 +605,20 @@ def project_upstream_commits(project: Path) -> dict[str, str]:
572
605
  return {}
573
606
 
574
607
 
608
+ def upstream_pin_note(recorded: str, pinned: str) -> str:
609
+ """`""` when the project holds the pinned commit, else the sentence that says so.
610
+
611
+ `npx skills add` has no ref option (measured 2026-11-29, skills 1.9.1): it installs the remote
612
+ HEAD, so a fresh install legitimately receives a newer upstream than the delivery pinned. The
613
+ lock still has to tell the truth about the difference, because two installs of the same version
614
+ are otherwise indistinguishable (E-59).
615
+ """
616
+ # Short prefixes on purpose: one side is a full sha, the other may be abbreviated.
617
+ if not recorded or recorded[:7] == pinned[:7]:
618
+ return ""
619
+ return f" pinned {pinned[:7]} in this delivery, {recorded[:7]} here"
620
+
621
+
575
622
  def cmd_doctor(argv: list[str]) -> int:
576
623
  parser = argparse.ArgumentParser(prog="framework.py doctor")
577
624
  parser.add_argument("--project", default=".", type=Path)
@@ -630,6 +677,10 @@ def cmd_doctor(argv: list[str]) -> int:
630
677
  print(f"installed {identity(recorded)}")
631
678
  print(f"global {global_skills()} — no Lathe skill installed globally")
632
679
  print(f"pi {PI_DEPENDENCY} present in {pi_modules()}")
680
+ trusted, untrusted = context_trust(project)
681
+ if trusted or untrusted:
682
+ total = len(trusted) + len(untrusted)
683
+ print(f"context {len(trusted)}/{total} rules trusted in {trust_store()}")
633
684
  print(f" ok {ok}")
634
685
  print(f" missing {len(missing)}")
635
686
  print(f" modified {len(modified)}")
@@ -640,6 +691,9 @@ def cmd_doctor(argv: list[str]) -> int:
640
691
  absent = [name for name in names if name not in set(held)]
641
692
  recorded = held_commits.get(str(source["name"])) or f"not recorded in {SKILLS_LOCK}"
642
693
  print(f"upstream {source['name']} @ {recorded}: present {len(held)}/{len(names)}")
694
+ pin = upstream_pin_note(recorded, str(source["commit"]))
695
+ if pin:
696
+ print(pin)
643
697
  if absent:
644
698
  absent_by_source.append((source, absent))
645
699
 
@@ -647,6 +701,22 @@ def cmd_doctor(argv: list[str]) -> int:
647
701
  for item in items:
648
702
  print(f" {label}: {item}")
649
703
 
704
+ if untrusted:
705
+ # Not drift: the user may prefer to approve on demand, with a UI. But a headless
706
+ # run then loses every command the guard rates medium, and the guard says nothing
707
+ # without a UI — so the reason and the fix are printed here (E-55).
708
+ print(
709
+ f"\nWARNING — {len(untrusted)} of {len(untrusted) + len(trusted)} "
710
+ f"{CONTEXT_DIR.as_posix()} rules are not trusted: {', '.join(untrusted)}",
711
+ file=sys.stderr,
712
+ )
713
+ print(
714
+ "the command guard is armed while they are untrusted, and without a UI every "
715
+ "medium/high bash action is blocked — `gates.py` included.",
716
+ file=sys.stderr,
717
+ )
718
+ print("approve them once, per file:\n python3 setup.py --trust", file=sys.stderr)
719
+
650
720
  drifted = False
651
721
  if missing or modified:
652
722
  print("\nDRIFT — an agent reading a modified skill is not running this framework.", file=sys.stderr)
@@ -110,8 +110,20 @@ FAST = (
110
110
  ),
111
111
  )
112
112
 
113
+ def tests_check() -> Check:
114
+ """`cargo nextest` when it is installed, `cargo test` otherwise.
115
+
116
+ Without this fallback, a machine with no nextest has no test runner in `verify` at all:
117
+ doctests skip on a binary crate, `deny` and `semver-checks` are library-only, so the
118
+ level executes one check (`doc`) and calls itself green (E-54).
119
+ """
120
+ if shutil.which("cargo-nextest"):
121
+ return Check("tests", ("cargo", "nextest", "run", "--all-features"), "cargo-nextest", 150)
122
+ return Check("tests", ("cargo", "test", "--all-features"), "cargo", 150)
123
+
124
+
113
125
  VERIFY = (
114
- Check("nextest", ("cargo", "nextest", "run", "--all-features"), "cargo-nextest", 150),
126
+ tests_check(),
115
127
  Check(
116
128
  "doctests",
117
129
  ("cargo", "test", "--doc"),
@@ -220,6 +232,22 @@ def install_hint(tool: str) -> str:
220
232
  return f"cargo install {tool}" if tool.startswith("cargo-") else f"installer {tool}"
221
233
 
222
234
 
235
+ def with_tool_tail(note: str, output: str) -> str:
236
+ """Append the last three lines of the real output to the gate's own advice.
237
+
238
+ The contract promises them (`docs/execution/GATE-CONTRACT.md` §5): the exit code alone
239
+ does not say what broke, and a gate an agent must re-run to understand is a gate twice
240
+ paid. A branch that names its cause keeps it first, then the tool speaks. One line stays
241
+ one line: lines are shortened individually, because joining first and cutting at 300
242
+ characters ends mid-sentence and no longer repeats three lines (review, 2026-11-29).
243
+ """
244
+ tail = output.strip().splitlines()[-3:]
245
+ if not tail:
246
+ return note
247
+ kept = [line if len(line) <= 90 else line[:89] + "…" for line in tail]
248
+ return f"{note} — {' | '.join(kept)}"
249
+
250
+
223
251
  def execute(check: Check, project: Path, offline: bool, reason: str, remaining: float) -> Result:
224
252
  if reason:
225
253
  return Result(check, SKIP, None, 0.0, reason)
@@ -278,11 +306,8 @@ def execute(check: Check, project: Path, offline: bool, reason: str, remaining:
278
306
  return Result(check, SKIP, None, duration, f"rien à vérifier — {fragment} (cargo a rendu {proc.returncode})")
279
307
  # The exit code alone does not say what broke, and a gate an agent must re-run
280
308
  # to understand is a gate twice paid. Keep the tail of the real output.
281
- tail = (err or out or "").strip().splitlines()
282
- note = f"code {proc.returncode}"
283
- if tail:
284
- note += " — " + " | ".join(tail[-3:])[:300]
285
- return Result(check, FAIL, proc.returncode, duration, note)
309
+ return Result(check, FAIL, proc.returncode, duration,
310
+ with_tool_tail(f"code {proc.returncode}", err or out or ""))
286
311
 
287
312
 
288
313
  def run_level(level: Level, project: Path, profile: str) -> list[Result]:
@@ -909,19 +934,21 @@ def run_campaign(project: Path) -> Result:
909
934
  detail = ", ".join(f"{count} {name}" for name, count in counts.items() if count)
910
935
 
911
936
  if proc.returncode == 3:
912
- return Result(inspected("campaign", subject), FAIL, 3, duration,
913
- f"{counts['timeout']} mutant(s) ont dépassé {MUTANT_OPTIONS.timeout}s — "
914
- "un mutant qui pend n'est ni tué ni survivant: augmente --mutant-timeout, "
915
- "ou marque le code lent #[mutants::skip]")
937
+ return Result(inspected("campaign", subject), FAIL, 3, duration, with_tool_tail(
938
+ f"{counts['timeout']} mutant(s) ont dépassé {MUTANT_OPTIONS.timeout}s — "
939
+ "un mutant qui pend n'est ni tué ni survivant: augmente --mutant-timeout, "
940
+ "ou marque le code lent #[mutants::skip]", output))
916
941
  if proc.returncode == 4:
917
- return Result(inspected("campaign", subject), FAIL, 4, duration,
918
- "les tests échouent sur l'arbre non muté — la suite est rouge avant toute mutation")
942
+ return Result(inspected("campaign", subject), FAIL, 4, duration, with_tool_tail(
943
+ "les tests échouent sur l'arbre non muté — la suite est rouge avant toute mutation",
944
+ output))
919
945
  if proc.returncode == 5:
920
- return Result(inspected("campaign", subject), FAIL, 5, duration,
921
- "le diff ne correspond plus à l'arbre — relance depuis un arbre propre")
946
+ return Result(inspected("campaign", subject), FAIL, 5, duration, with_tool_tail(
947
+ "le diff ne correspond plus à l'arbre — relance depuis un arbre propre", output))
922
948
  if proc.returncode == 6:
923
- return Result(inspected("campaign", subject), FAIL, 6, duration,
924
- "le fichier de diff n'est pas un diff valide")
949
+ return Result(inspected("campaign", subject), FAIL, 6, duration, with_tool_tail(
950
+ "le fichier de diff est illisible (introuvable ou refusé) — un fichier lisible qui "
951
+ "n'est pas un diff sort 0, donc 6 est un échec de lecture", output))
925
952
 
926
953
  if tested == 0:
927
954
  # Measured: a diff whose paths do not match the manifest makes cargo-mutants
@@ -946,11 +973,8 @@ def run_campaign(project: Path) -> Result:
946
973
  return Result(inspected("campaign", subject), FAIL, 2, duration,
947
974
  defect_note([f"{line}" for line in open_survivors]))
948
975
 
949
- tail = output.strip().splitlines()
950
- note = f"code {proc.returncode}"
951
- if tail:
952
- note += " — " + " | ".join(tail[-3:])[:300]
953
- return Result(inspected("campaign", subject), FAIL, proc.returncode, duration, note)
976
+ return Result(inspected("campaign", subject), FAIL, proc.returncode, duration,
977
+ with_tool_tail(f"code {proc.returncode}", output))
954
978
 
955
979
 
956
980
  def record_base(project: Path) -> int:
@@ -32,6 +32,9 @@ from pathlib import Path
32
32
  import framework
33
33
 
34
34
  UPSTREAM_TIMEOUT = 600
35
+ # One `pi --print "/nma trust …"` per rule: the extension scans the file, so the wait is
36
+ # its scan, not a model call.
37
+ TRUST_TIMEOUT = 120
35
38
  MINIMUM_PYTHON = (3, 9)
36
39
  PI_PROMPT_HINT = "/skill:lathe"
37
40
 
@@ -139,6 +142,47 @@ def ensure_target_ignored(project: Path) -> None:
139
142
  print(f" added target/ to {ignore.name}")
140
143
 
141
144
 
145
+ def trust_rules(project: Path) -> int:
146
+ """Approve the rules this install wrote, through the extension's own command.
147
+
148
+ Measured 2026-11-29 (E-55): while a `.pi/context/` file is untrusted, the extension
149
+ arms a command guard that blocks every medium/high bash action, and without a UI it
150
+ says nothing. `python3 .agents/scripts/gates.py fast` is one of those actions, so an
151
+ untrusted install cannot run its own gates headless. The fix is one command per rule,
152
+ never a hand-written trust store: `pi --print "/nma trust <file> --yes"`.
153
+ """
154
+ trusted, untrusted = framework.context_trust(project)
155
+ if not untrusted:
156
+ said(f"{len(trusted)} rule(s) already trusted")
157
+ return 0
158
+ pi = shutil.which("pi")
159
+ if pi is None:
160
+ return refuse(
161
+ "--trust needs `pi` on PATH: the trust store belongs to the extension, and "
162
+ "writing it by hand would approve content nobody scanned"
163
+ )
164
+ for name in untrusted:
165
+ relative = (framework.CONTEXT_DIR / name).as_posix()
166
+ said(f"trusting {relative}")
167
+ done = subprocess.run(
168
+ [pi, "--print", "--approve", f"/nma trust {relative} --yes"],
169
+ cwd=project,
170
+ capture_output=True,
171
+ text=True,
172
+ timeout=TRUST_TIMEOUT,
173
+ check=False,
174
+ )
175
+ # Measured 2026-11-29: the extension prints `trusted <file>` on stderr, so a check
176
+ # on stdout alone refuses an approval that worked.
177
+ if done.returncode != 0 or "trusted" not in (done.stdout + done.stderr):
178
+ return refuse(f"could not trust {relative}: {(done.stdout + done.stderr).strip()[:200]}")
179
+ trusted, untrusted = framework.context_trust(project)
180
+ if untrusted:
181
+ return refuse(f"still untrusted after the command: {', '.join(untrusted)}")
182
+ said(f"{len(trusted)} rule(s) trusted")
183
+ return 0
184
+
185
+
142
186
  def main(argv: list[str]) -> int:
143
187
  parser = argparse.ArgumentParser(prog="lathe", description="Install Lathe into one project.")
144
188
  parser.add_argument("--project", type=Path, default=Path("."), help="the project root")
@@ -148,6 +192,12 @@ def main(argv: list[str]) -> int:
148
192
  help="never reach the network: refuse if an upstream is missing instead of installing it",
149
193
  )
150
194
  parser.add_argument("--force", action="store_true", help="overwrite files that differ")
195
+ parser.add_argument(
196
+ "--trust",
197
+ action="store_true",
198
+ help="approve the .pi/context rules this install wrote (needs pi; disarms the "
199
+ "extension's command guard, which otherwise blocks gates.py without a UI)",
200
+ )
151
201
  args = parser.parse_args(argv)
152
202
 
153
203
  project = args.project.resolve()
@@ -180,14 +230,20 @@ def main(argv: list[str]) -> int:
180
230
 
181
231
  ensure_target_ignored(project)
182
232
 
183
- step(4, "verdict")
233
+ if args.trust:
234
+ step(4, "rules")
235
+ code = trust_rules(project)
236
+ if code != 0:
237
+ return code
238
+
239
+ step(5, "verdict")
184
240
  code = framework.cmd_doctor(["--project", str(project)])
185
241
  if code != 0:
186
242
  print("\ninstalled, but doctor is red: fix what it named before using the framework.", file=sys.stderr)
187
243
  return code
188
244
 
189
245
  print(f"\nnext: in Pi, type {PI_PROMPT_HINT} — or just tell your agent \"use Lathe\"")
190
- print(f"the same two ways in, and nothing else to remember")
246
+ print("the same two ways in, and nothing else to remember")
191
247
  return 0
192
248
 
193
249
 
@@ -79,6 +79,7 @@ Choose a row only when the user is *asking* for it. Silence is not intent.
79
79
  | the code made faster, or where the time goes | `optimize` |
80
80
  | a choice that needs evidence before coding | `prototype` |
81
81
  | a screen to rebuild from captures of another app | `replicate-ui` |
82
+ | what the running app did, not what it looks like ("did it actually save?", a label, a bounds) | `probe` (desktop only) |
82
83
  | a lesson to capture after a release or a bad week | `retro` |
83
84
  | a small bounded change to existing code | `implement` |
84
85
  | the delivered lot written down, with the review green and the tree clean | `journal` |
@@ -156,6 +157,16 @@ hand off in text, in this exact shape:
156
157
  Nothing after that line. Naming the step in prose does not count: the line is the route. A run that
157
158
  ends without it has not routed.
158
159
 
160
+ **When no one will answer.** A scripted run — `pi --print`, a subagent, a CI job — has no one to type
161
+ `/skill:<step>`. The step is still a file: read `.agents/skills/<step>/SKILL.md` and follow that file
162
+ only. Do not replace the step with your own version of it, and do not read the step after it — the next
163
+ route is computed once the artifact exists.
164
+
165
+ Some steps still ask a human something: a grill, a spec review, a choice only the owner can make. With
166
+ nobody there, neither stop nor invent silently — write the questions and the answer you would take into
167
+ the artifact that step produces, each marked `Assumption (> why)`, then go on down the ladder. A run that
168
+ ends with no artifact has stalled, not routed.
169
+
159
170
  **When the route depends on the user.** If two rows could match and only the user can tell which —
160
171
  `implement` versus `visual-loop` on a desktop project, `optimize` versus `implement` on a slow path —
161
172
  ask inside sentence 1 and route the default you would take. Never spend a turn asking alone: the
@@ -166,3 +177,9 @@ question and the route go out together, so a user who says nothing still has a s
166
177
  The reply carries the three parts of the hand-off, and the step it names is the first match of intent,
167
178
  then ladder. A question about Lathe itself is answered from `references/invariants.md` and is not a
168
179
  route.
180
+
181
+ When no one is at the keyboard — a scripted run, a subagent, a CI job — a route is not a result. The run
182
+ ends with the artifact the first step produces, or with the reason it cannot: read that step's file, and
183
+ if it needs a human answer, decide and mark it `Assumption (> why)`. Measured twice on the same model:
184
+ one run read the step and delivered the whole chain, the other printed the route and stopped, so the
185
+ obligation is stated here as well as in the hand-off.
@@ -192,5 +192,40 @@ Every case runs in a fresh temp directory with the installed skills linked in, o
192
192
  - expect: retro
193
193
  - disqualify: code-review, journal
194
194
 
195
+ ### 26. Batch's last ticket closed, the campaign verdict names an older commit
196
+
197
+ - state: AGENTS.md=Profile: rust-library | Cargo.toml=[lib];name="claim" | src/lib.rs=pub fn claim() {} | .scratch/claim/spec.md=# Spec | .scratch/claim/issues/02-claim.md=Blocked by: none;;- [x] claim is idempotent | .lathe/mutants/verdict=1111111 2222222
198
+ - prompt: "All the tickets are closed. Send this batch to review."
199
+ - expect: mutants
200
+ - disqualify: code-review, implement, journal
201
+
202
+ ### 27. Nothing installed yet in a real project
203
+
204
+ - state: AGENTS.md=Profile: rust-library | Cargo.toml=[lib];name="claim" | src/lib.rs=pub fn claim() {}
205
+ - prompt: "Install Lathe in this project."
206
+ - expect: bootstrap
207
+ - disqualify: update, scaffold, grill-with-docs
208
+
209
+ ### 28. Installed, carrying an older version
210
+
211
+ - state: AGENTS.md=Profile: rust-library | Cargo.toml=[lib];name="claim" | src/lib.rs=pub fn claim() {} | .agents/workflows/new-rust-library.md=# New Rust library | .framework/installed.json={"framework": "lathe", "version": "0.3.0", "commit": "5c7835c", "source": "unknown", "trees": {}}
212
+ - prompt: "Bring Lathe up to date in this project."
213
+ - expect: update
214
+ - disqualify: bootstrap, scaffold, grill-with-docs
215
+
216
+ ### 29. A slow path while a ticket is still open
217
+
218
+ - state: AGENTS.md=Profile: rust-library | Cargo.toml=[lib];name="claim" | src/lib.rs=pub fn claim() {} | .scratch/claim/spec.md=# Spec | .scratch/claim/issues/02-claim.md=Blocked by: none;;- [ ] claim is idempotent
219
+ - prompt: "claim() takes 400 ms on a 10k-row store. Where does the time actually go?"
220
+ - expect: optimize
221
+ - disqualify: implement, prototype, research
222
+
223
+ ### 30. A live interaction to prove on a desktop app
224
+
225
+ - state: AGENTS.md=Profile: rust-native-desktop | Cargo.toml=[package];name="keeper";[dependencies];gpui-kit="0.11" | src/main.rs=fn main() {} | .scratch/keeper/spec.md=# Spec | .scratch/keeper/issues/03-pin.md=Blocked by: none;;- [ ] pinning survives a restart
226
+ - prompt: "The app is running. I click Pin and the row does not change. Did the click actually reach the store?"
227
+ - expect: probe
228
+ - disqualify: verify-visual, diagnosing-bugs, visual-loop
229
+
195
230
  The harness commits every declared file, so the entry arrives committed; a tree whose only uncommitted
196
231
  change is that same entry reads the same way — rung 8 does not match, rung 11 does.
@@ -99,6 +99,30 @@ python3 <package>/scripts/framework.py doctor --project .
99
99
 
100
100
  `<package>` is this delivery, unpacked. `setup.py` is those four commands with the refusals ordered.
101
101
 
102
+ ## Trust the three rules
103
+
104
+ `.pi/context/` holds three rules that inject themselves at the moment they apply. Until each one is
105
+ **trusted**, the `no-more-agents-dot-md` extension arms a command guard, and without a UI every
106
+ medium/high bash action is blocked — measured, `python3 .agents/scripts/gates.py fast` among them. In
107
+ a headless run the guard says nothing about being armed, so the failure looks like a tool refusing
108
+ your work.
109
+
110
+ ```bash
111
+ npx create-lathe --trust # approve the three rules this install wrote, through the extension
112
+ ```
113
+
114
+ Without `--trust`, the same thing in Pi, once per file:
115
+
116
+ ```text
117
+ /nma trust .pi/context/journal-de-lot.md --yes
118
+ /nma trust .pi/context/tech-skill.md --yes
119
+ /nma trust .pi/context/ticket-closed.md --yes
120
+ ```
121
+
122
+ Trust is a security decision, so nothing here writes a trust store by hand: `--trust` runs the
123
+ extension's own command, which scans the file and records path plus SHA-256. `doctor` reports
124
+ `context 3/3 rules trusted` and warns when it is less.
125
+
102
126
  ## After installing
103
127
 
104
128
  Two ways in, both measured: type `/skill:lathe` in Pi, or tell your agent "use Lathe". Either one reads
@@ -109,6 +133,15 @@ A `/lathe` prompt template was written for this package and dropped: measured in
109
133
  fresh project, it was not expanded into a command, and shipping a shortcut that does nothing is worse
110
134
  than shipping one fewer shortcut. The skill command is registered by Pi itself.
111
135
 
136
+ ## What else appears in the tree
137
+
138
+ `.claude/skills/` — 42 symlinks to `.agents/skills/`. They are written by the upstream `npx skills add`,
139
+ not by Lathe, so Claude Code sees the same skills. Pi reads `.agents/skills/`; the symlinks are
140
+ compatible furniture, safe to ignore and safe to delete if nothing else uses them.
141
+
142
+ `.lathe/` — the mutation campaign's output. Written by `gates.py mutants`, git-ignored, and the only
143
+ place a mutation verdict lives.
144
+
112
145
  ## Update, uninstall
113
146
 
114
147
  - **Update:** run `npx create-lathe@latest`; it moves to the newer lock and writes only the files that
@@ -18,6 +18,9 @@ Run it after the last ticket and before the review. Per ticket it costs more tha
18
18
  is open and the verdict is about a tree nobody reviewed.
19
19
  - **Three refusals before the first mutant.** Output git does not see, a dirty tree, a missing base.
20
20
  Fix the precondition; never the flag.
21
+ - **A red baseline voids the run.** Exit 4 means the tests fail on the unmutated tree: the survivor list
22
+ is then the run's opinion, not the tests'. Fix the baseline and re-run in a **fresh** build directory —
23
+ measured, a reused one after a red baseline reported six survivors that a clean run killed (E-58).
21
24
  - **A survivor is killed or justified in writing.** `.lathe/justified.txt`, with a reason a reader can
22
25
  check. An equivalent mutant is a documented exception, not a majority.
23
26
  - **The verdict is the file, not the memory.** `.lathe/mutants/verdict` names the commit it certified:
@@ -51,7 +51,7 @@ The book says `logs/`; the directory is `log/`. Formats are explicitly unstable
51
51
  | `3` | some tests timed out |
52
52
  | `4` | the unmutated baseline is already failing or hanging — nothing was tested |
53
53
  | `5` | `--in-diff`: the new side of the diff does not match the text in the tree |
54
- | `6` | `--in-diff`: the file is not a valid diff |
54
+ | `6` | `--in-diff`: the diff file cannot be read (missing or refused). Measured 2026-11-29: a readable file that is not a diff prints `Diff file is empty` and exits `0`, so 6 is a read failure, not a syntax one |
55
55
  | `70` | internal error |
56
56
 
57
57
  For a completed campaign the codes aggregate `4` > `3` > `2` > `0`, so a run with both a hang and a
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "create-lathe",
3
- "version": "0.4.0",
4
- "description": "Install Lathe — an agent-first engineering workflow for Rust — into one project, in one command.",
3
+ "version": "0.4.1",
4
+ "description": "Install Lathe \u2014 an agent-first engineering workflow for Rust \u2014 into one project, in one command.",
5
5
  "bin": {
6
6
  "create-lathe": "bin/create-lathe.js"
7
7
  },