1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! The mem schema pin and its migration: setting the pin, reading the stamped generation, persisting it, and bumping the backend's copy.
use super::reload::changed_config_fields;
use super::*;
impl Engine {
/// Set a mem's schema pin — the conformance-gated schema-migration
/// trigger. Behaviour per the pinned contract:
///
/// - requested == current pin → `Noop`, no state change.
/// - requested != pin, mem integral against the target →
/// atomic switch (`schema_pin = target`, migration state
/// cleared) in one workspace-store write → `Switched`.
/// - requested != pin, mem NOT integral → enter (or stay in)
/// dual-pin: `migration_target = target`, writes validate
/// against the target from this call on, `findings` carries
/// the non-integral entities → `MigrationStarted`
/// (first call) / `MigrationPending` (same target re-issued).
/// - re-issued with the in-flight target once every entity is
/// integral → atomic switch → `Switched`.
///
/// The trigger is a label change gated by the conformance check —
/// no content hashing. The response hands the agent findings and
/// nothing else (no migration scripts, no hints); each repair
/// write is validated strictly against the target.
pub fn set_mem_schema(
&mut self,
mem: &str,
target: &memstead_schema::SchemaRef,
) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
use crate::engine::{SetSchemaOutcome, SetSchemaResult};
// A mem mounted read-only refuses before any lock is taken, as
// an entity write into it does: the refusal lays nothing where
// the mem lives. (A quarantined mem is not mounted and goes on
// to its repair path below.)
let _ = self.settle_roster_before_locking();
if self.mounts.iter().any(|m| {
m.mount.mem == mem && m.mount.capability != crate::workspace::MountCapability::Write
}) {
return Err(EngineError::ReadOnlyMount(mem.to_string()));
}
// A pin switch waits for a write in progress in any mem; the
// subject may be unreadable (a repin is how it is repaired).
let (_write_lock, _) = self.lock_workspace_for_mem_operation(mem)?;
// A quarantined mem's set-schema IS the repair path (an
// unresolvable pin is the commonest quarantine cause): repin
// the retained mount, then re-attempt the attach — the same
// in-process recovery `reload` performs after an external
// repair. Ordinary mounts proceed below unchanged.
if self.quarantine_reason(mem).is_some() {
return self.set_schema_on_quarantined(mem, target);
}
// Capability gate, identical in shape and position to the six
// sibling setters (`set_mem_version` … `set_mem_sync_state`):
// a schema-pin change starts a migration — the one lifecycle
// mutation a read-only mount must be able to refuse like any
// other. Judged on the roster as it stands now.
let (mount_idx, _roster_notice) = self.writable_mount_on_current_roster(mem)?;
// The requested target must resolve before anything else —
// an unknown ref is an error, not a migration into nowhere.
let target_schema = self.resolve_schema_by_ref(target).ok_or_else(|| {
// The migration resolver consulted workspace-authored
// schemas layered over the built-ins (`resolve_schema_by_ref`).
let consulted: Vec<_> = self
.workspace_schemas
.iter()
.chain(self.builtin_schemas.iter())
.cloned()
.collect();
EngineError::SchemaNotFound {
mem: mem.to_string(),
pin: target.as_display(),
sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
&target.name,
&target.version,
&consulted,
),
install_hint: None,
}
.with_schema_install_probe(self.workspace_root())
})?;
// `Mount.schema` is now the optional assertion; for a mem the
// operator is actively re-pinning it is normally `Some` (and kept
// in sync with the config by the switch below). `<unset>` covers a
// mount that carried no assertion.
let current_pin = self.mounts[mount_idx].mount.schema.clone();
let current_pin_display = current_pin
.as_ref()
.map(|p| p.as_display())
.unwrap_or_else(|| "<unset>".to_string());
let in_flight = self.mounts[mount_idx].mount.migration_target.clone();
// The noop question is asked of the pin the engine actually
// serves (the loaded schema, resolved from the authoritative
// backend config at boot), never of the mount's expectation
// alone. With a `SCHEMA_PIN_MISMATCH` (mount says 0.4.0, config
// says 0.1.0) the old comparison against the mount answered
// "noop" for a target of 0.4.0 and the config stayed at 0.1.0
// forever: the one command meant to repair the mismatch could
// not. When the served pin already equals the target and only
// the mount expectation lags, the expectation is aligned in
// place and reported as switched.
let served_pin: Option<memstead_schema::SchemaRef> = self.schemas.get(mem).map(|s| {
let (name, version) = s.id();
memstead_schema::SchemaRef::new(name, version)
});
// During a dual-pin migration the served schema IS the target
// (writes validate against it) while the config still pins the
// old generation, so the shortcut applies only with no migration
// in flight; an in-flight target falls through to the
// conformance gate that completes it.
if served_pin.as_ref() == Some(target) && in_flight.is_none() {
if current_pin.as_ref() == Some(target) {
return Ok(SetSchemaOutcome {
mem: mem.to_string(),
schema_pin: current_pin_display,
migration_target: in_flight.map(|t| t.as_display()),
outcome: SetSchemaResult::Noop,
findings: Vec::new(),
stamped_schema: self.stamped_schema_of(mount_idx),
});
}
self.mounts[mount_idx].mount.schema = Some(target.clone());
self.mounts[mount_idx].mount.migration_target = None;
self.persist_state()?;
return Ok(SetSchemaOutcome {
mem: mem.to_string(),
schema_pin: target.as_display(),
migration_target: None,
outcome: SetSchemaResult::Switched,
findings: Vec::new(),
stamped_schema: self.stamped_schema_of(mount_idx),
});
}
// Conformance gate against the requested target. The full
// integrity definition includes the consistency axis, but the
// schema-switch gate is conformance: consistency breaks are
// schema-independent (they neither block nor are caused by a
// pin change) and keep their always-available repair paths.
let findings = crate::ops::integrity::conformance_findings(
&self.store,
mem,
target_schema.as_ref(),
&self.schemas,
);
if findings.is_empty() {
// Atomic switch. The pin's authoritative home is the backend
// config (boot resolution prefers it over `Mount.schema`), so
// persist there FIRST — if that write fails, every other piece
// of state stays untouched and the switch is a clean no-op.
// Without this the new pin landed only in `mounts.json` and was
// silently reverted on the next process boot for any
// config-present mem.
self.persist_mem_schema_pin(mount_idx, target)?;
self.mounts[mount_idx].mount.schema = Some(target.clone());
self.mounts[mount_idx].mount.migration_target = None;
self.schemas_insert(mem.to_string(), target_schema);
self.invalidate_communities();
// The index field set derives from the pinned schema — the
// schema-switch staleness the whole-map drop used to mask:
// this mem's index must be
// rebuilt against the new field set.
self.invalidate_search_indexes();
self.persist_state()?;
// The completed migration re-stamps the mutation stamp (the
// marker `ENGINE_VERSION_SKEW` reads) with the generation
// the mem now sits on. Without this the marker kept naming
// the old pin until the next entity write, and an agent
// reading it after the migration re-derived from a stale
// generation. The stamp
// writer's equality guard keeps a no-move write from
// happening; its warnings ride entity mutations and have no
// channel on this outcome, the same standing as the sweep.
let _stamp_warnings_have_no_channel_here = self.stamp_mutation_versions(mount_idx);
return Ok(SetSchemaOutcome {
mem: mem.to_string(),
schema_pin: target.as_display(),
migration_target: None,
outcome: SetSchemaResult::Switched,
findings: Vec::new(),
stamped_schema: self.stamped_schema_of(mount_idx),
});
}
let outcome = if in_flight.as_ref() == Some(target) {
SetSchemaResult::MigrationPending
} else {
SetSchemaResult::MigrationStarted
};
self.mounts[mount_idx].mount.migration_target = Some(target.clone());
// Writes validate against the target from this point on —
// the load-bearing dual-pin semantic.
self.schemas_insert(mem.to_string(), target_schema);
self.invalidate_communities();
// Same field-set dependency as the atomic-switch branch above.
self.invalidate_search_indexes();
self.persist_state()?;
// A dual-pin entry never moves the marker: the mem still sits
// on the old generation until every entity is integral, and
// the outcome says which generation the marker carries.
Ok(SetSchemaOutcome {
mem: mem.to_string(),
schema_pin: current_pin_display,
migration_target: Some(target.as_display()),
outcome,
findings,
stamped_schema: self.stamped_schema_of(mount_idx),
})
}
/// The resolved schema the mem's mutation stamp names, from the
/// engine's cached config (kept current by the shared config
/// writer), or `None` when the mem carries no stamp.
pub(super) fn stamped_schema_of(&self, mount_idx: usize) -> Option<String> {
self.mounts
.get(mount_idx)
.and_then(|m| m.mem_config.as_ref())
.and_then(|c| c.mutation_stamp.as_ref())
.map(|st| st.schema.clone())
}
/// Persist a mem's new schema pin into the authoritative backend
/// config (`.memstead/config.json` for folder, the `__MEMSTEAD`
/// mem-config blob for git-branch).
///
/// Boot resolution treats the backend config as the authoritative
/// settled pin and `Mount.schema` (the `mounts.json` copy) as a
/// cross-checked assertion. A schema switch that updated only
/// `mounts.json` would therefore be silently reverted on the next
/// process boot — the config still names the old pin. This keeps the
/// authoritative home in sync at switch time.
///
/// Value-level field bump: only the `"schema"` string is rewritten;
/// every other config field (`readMems`, write guidance, …) is
/// preserved verbatim. Config-absent mems (no `config.json`) keep
/// `Mount.schema` as their settled pin, so there is nothing to update
/// — a clean no-op.
/// **The one way this engine writes a mem config.** Every config-writing
/// operation goes through it; none serializes its cached struct.
///
/// The defect it removes: a long-lived MCP server reads each mem's config
/// once at boot and holds it for days. Eight operations used to clone that
/// cached struct, set one field, and write the whole thing back, so
/// anything a sibling process changed in between was gone. The
/// reload-before-operation invariant did not save them, because the
/// staleness probe watches the entity branch (git-branch) or the change
/// log (folder) and a config-only write advances neither.
///
/// What this does instead is what the schema-pin writer next door already
/// did: read the config the backend HAS, mutate the one field on that
/// JSON, write it back. A field this call did not set cannot be reverted,
/// because this call never had an opinion about it.
///
/// `apply` receives the freshly-read config, PARSED. It deliberately does
/// not receive raw JSON: an earlier draft handed out the `Value` and each
/// closure wrote its own key name, which put `review_mark` in the file
/// where the struct reads `reviewMark` and lost the field on the next
/// read. Serde owns the wire names; the closures must not restate them.
/// Unknown fields survive because `MemConfig` flattens them into `extra`.
///
/// `apply` runs again on a re-read if the file moved between the read and
/// the write, so it must be a pure function of the config it is handed,
/// never of the engine's cache.
///
/// Returns the parsed new config plus, when the stored config had moved on
/// from what this engine last observed, the fields the intervening writer
/// had changed. The caller rides that on its own response as
/// `CONFIG_WRITE_INTERVENED`.
pub(crate) fn write_mem_config_merged(
&mut self,
mount_idx: usize,
mem_name: &str,
tool: &'static str,
note: Option<&str>,
apply: &dyn Fn(&mut memstead_schema::config::MemConfig),
) -> Result<(memstead_schema::config::MemConfig, Vec<String>), EngineError> {
// The config-write commit carries the operation's provenance
// like every other commit: the tool that caused it, the
// session's actor, client, role and identity, and the note.
let ctx = self.session_commit_context(Some(tool), note.map(String::from));
let backend = self.mounts[mount_idx].backend.as_ref();
let read = |b: &dyn crate::backend::MemBackend| -> Result<Vec<u8>, EngineError> {
b.read_mem_config()
.map_err(|e| EngineError::Mem(format!("read mem config for update: {e}")))?
.ok_or_else(|| {
EngineError::InvalidInput(format!(
"mem '{mem_name}' has no stored MemConfig (initialize the mem via \
`memstead init` or `memstead mem create` first)"
))
})
};
let stored = read(backend)?;
// What the intervening writer changed, if anyone did. Compared against
// the engine's cached copy, never against a clock: the rule forbids
// reacting to cache age, and a single-writer workspace has an
// identical cache, so this is empty there.
let intervened = match self.mounts[mount_idx].mem_config.as_ref() {
Some(cached) => changed_config_fields(cached, &stored),
None => Vec::new(),
};
let render =
|raw: &[u8]| -> Result<(memstead_schema::config::MemConfig, Vec<u8>), EngineError> {
let value: serde_json::Value = serde_json::from_slice(raw)
.map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
let mut cfg = memstead_schema::config::parse_mem_config(&value)
.map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
apply(&mut cfg);
let mut bytes = serde_json::to_vec_pretty(&cfg)
.map_err(|e| EngineError::Mem(format!("serialize mem config: {e}")))?;
bytes.push(b'\n');
Ok((cfg, bytes))
};
let (mut parsed, mut bytes) = render(&stored)?;
// Compare-and-set, done by the backend so the check and the write are
// one step. An earlier draft re-read here and then wrote, which is
// check-then-write and leaves exactly the lost-update window
// open. On a mismatch the loop re-reads, re-applies onto what is
// there, and retries: the intervening writer's change is merged, never
// overwritten. Bounded, because an unbounded retry against a hot
// writer is a hang, and reaching the bound is a real contention
// problem the caller should hear about rather than a state to spin in.
let mut expected = stored;
for attempt in 0..8 {
let wrote = self.mounts[mount_idx].backend.write_mem_config_cas(
Some(&expected),
&bytes,
&ctx,
)?;
if wrote {
break;
}
if attempt == 7 {
return Err(EngineError::Mem(format!(
"mem '{mem_name}' config is being written concurrently: eight \
compare-and-set attempts all lost the race. Retry, or find the \
writer that is not backing off."
)));
}
expected = read(self.mounts[mount_idx].backend.as_ref())?;
let rendered = render(&expected)?;
parsed = rendered.0;
bytes = rendered.1;
}
let mounted = &mut self.mounts[mount_idx];
mounted.mem_config = Some(parsed.clone());
// Refresh the head cursor so the next drift probe does not surface
// MEM_RELOADED for the commit this call just produced.
if let Some(sha) = mounted.backend.current_head().ok().flatten() {
let before = mounted
.last_known_head
.replace(sha.clone())
.unwrap_or_default();
// The config write is the current caller's own.
self.caller_saw_own_write(mem_name, &before, &sha);
}
Ok((parsed, intervened))
}
fn persist_mem_schema_pin(
&mut self,
mount_idx: usize,
target: &memstead_schema::SchemaRef,
) -> Result<(), EngineError> {
let ctx = self.session_commit_context(Some("set_mem_schema"), None);
let value = bump_backend_schema_pin(self.mounts[mount_idx].backend.as_ref(), target, &ctx)?;
// Refresh the cached parsed config so in-session reads observe the
// new pin without a reload.
if let Some(value) = value
&& let Ok(cfg) = memstead_schema::config::parse_mem_config(&value)
{
self.mounts[mount_idx].mem_config = Some(cfg);
}
Ok(())
}
}
pub fn bump_backend_schema_pin(
backend: &dyn crate::backend::MemBackend,
target: &memstead_schema::SchemaRef,
ctx: &crate::vcs::CommitContext<'_>,
) -> Result<Option<serde_json::Value>, EngineError> {
// Compare-and-set against the bytes this call read, re-read and re-applied
// on a mismatch: a config field another writer changed in between
// survives, and the pin lands on top of it. Bounded like
// `write_mem_config_merged`.
for _ in 0..8 {
let Some(bytes) = backend
.read_mem_config()
.map_err(|e| EngineError::Mem(format!("read mem config for pin update: {e}")))?
else {
return Ok(None);
};
let mut value: serde_json::Value = serde_json::from_slice(&bytes)
.map_err(|e| EngineError::Mem(format!("parse mem config for pin update: {e}")))?;
value["schema"] = serde_json::Value::String(target.as_display());
let new_bytes = serde_json::to_vec_pretty(&value)
.map_err(|e| EngineError::Mem(format!("serialize mem config for pin update: {e}")))?;
if backend
.write_mem_config_cas(Some(&bytes), &new_bytes, ctx)
.map_err(|e| EngineError::Mem(format!("write mem config for pin update: {e}")))?
{
return Ok(Some(value));
}
}
Err(EngineError::Mem(format!(
"mem config is being written concurrently: eight compare-and-set attempts to \
pin {} all lost the race. Retry.",
target.as_display()
)))
}