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
//! ONT-4: the world doors, in one implementation.
//!
//! `harness.v1.world.load|save|compile|decompile|import|export` and
//! `supercode world <verb>` are two transports over the functions here, which
//! are themselves a thin wrapper over the ONT-3 codecs
//! (`supercode_interchange::world::codec`). Nothing in this module decides
//! anything a codec does not: it picks the codec the caller named, keeps the
//! io bookkeeping a decompile needs, and shapes the answer for the wire.
//!
//! One rule the wire adds: a vault VALUE never leaves. A load or a compile
//! answers with the vault's KEY NAMES only — the caller that needs a value
//! reads the home's own `.env`. That rule is why `import` and `export` exist
//! as verbs of their own: a migration moves credentials between homes, and
//! composed from the value-level verbs by a client it could not — the
//! credential would have to cross the wire. Here it stays in this process.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use supercode_interchange::ontology::ArtifactFidelity;
use supercode_interchange::world::codec::folder::OWNED_FILES;
use supercode_interchange::world::codec::{
carry_unmodeled, from_hermes, from_openclaw, load_home, save_home, to_hermes, to_openclaw,
Flavor, LoadedHome, Refusal,
};
use supercode_interchange::world::World;
use crate::Result;
/// Which layout a folder is read as (`harness.v1.world.load`'s `flavor`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HomeFlavor {
/// Our own folder.
#[default]
Orchestrator,
/// A Hermes home read in place.
Hermes,
}
impl From<HomeFlavor> for Flavor {
fn from(flavor: HomeFlavor) -> Self {
match flavor {
HomeFlavor::Orchestrator => Flavor::Orchestrator,
HomeFlavor::Hermes => Flavor::Hermes,
}
}
}
/// What kind of home `decompile`'s `source` is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceFlavor {
/// The target harness's own home, the one the world was compiled from.
#[default]
Native,
/// Our own folder: refs where the harness reads values, and no session store of the target's.
Orchestrator,
}
/// Which source harness a world is compiled from or decompiled back to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorldHarness {
/// A Hermes home.
Hermes,
/// An OpenClaw state directory.
Openclaw,
}
/// A refused write, on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefusalRow {
/// The file, relative to the destination home.
pub file: String,
/// Why, naming the gate.
pub reason: String,
}
impl From<&Refusal> for RefusalRow {
fn from(refusal: &Refusal) -> Self {
Self {
file: refusal.file.clone(),
reason: refusal.reason.clone(),
}
}
}
/// What a load or a compile answers: the world, and the vault's key names.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorldRead {
/// The world value.
pub world: World,
/// The `.env` names the world's secret refs point at — names only.
pub vault_keys: Vec<String>,
}
/// What a save answers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorldSaved {
/// Always true; a failure is an error, never a `false`.
pub written: bool,
/// The folder the world was written to.
pub root: PathBuf,
}
/// What a decompile did.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorldDecompiled {
/// Every artifact written, with its tier.
pub written: Vec<ArtifactFidelity>,
/// Every write refused, with the gate named.
pub refused: Vec<RefusalRow>,
/// What a semantic write gave up (OpenClaw only).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
/// Store rows written back column for column (OpenClaw only).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rows_byte: Option<usize>,
/// Store rows re-encoded (OpenClaw only).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rows_emitted: Option<usize>,
}
/// What an import did: the world as saved, the vault's key names, and the
/// unmodeled files carried by path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorldImported {
/// The world value, as written into `root`.
pub world: World,
/// The `.env` names the world's secret refs point at — names only.
pub vault_keys: Vec<String>,
/// Our folder.
pub root: PathBuf,
/// Files the world does not model, copied byte for byte (relative to `root`).
pub carried: Vec<String>,
}
fn keys(vault: &BTreeMap<String, String>) -> Vec<String> {
vault.keys().cloned().collect()
}
/// Point a world at the folder it is about to be written to, so the record and
/// the disk agree afterwards. `dir` is bookkeeping, not part of any artifact's
/// record, so this never forces a re-emit.
fn repoint(world: &mut World, root: &Path) {
world.root = root.to_path_buf();
for (name, profile) in world.profiles.iter_mut() {
profile.dir = if name == "default" {
root.to_path_buf()
} else {
root.join("profiles").join(name)
};
}
}
/// `harness.v1.world.load`: read a home folder as one world value.
pub fn load(root: &Path, flavor: HomeFlavor) -> Result<WorldRead> {
let loaded = load_home(root, flavor.into())?;
Ok(WorldRead {
vault_keys: keys(&loaded.vault),
world: loaded.world,
})
}
/// `harness.v1.world.save`: write a world into our own folder.
///
/// An existing root is loaded first: its `io` bookkeeping is what tells the
/// encoder which artifacts are unchanged, so a save of an unmodified world
/// leaves every byte alone. `vault` is merged into the loaded one — a caller
/// that sends no secrets keeps the home's own `.env`.
pub fn save(root: &Path, world: World, vault: BTreeMap<String, String>) -> Result<WorldSaved> {
let mut loaded = if root.is_dir() {
load_home(root, Flavor::Orchestrator)?
} else {
LoadedHome {
world: world.clone(),
vault: BTreeMap::new(),
io: BTreeMap::new(),
}
};
loaded.world = world;
repoint(&mut loaded.world, root);
loaded.vault.extend(vault);
save_home(&mut loaded, Some(root))?;
Ok(WorldSaved {
written: true,
root: root.to_path_buf(),
})
}
/// `harness.v1.world.compile`: read another harness's home as one world value.
pub fn compile(from: WorldHarness, home: &Path) -> Result<WorldRead> {
Ok(match from {
WorldHarness::Hermes => {
let loaded = from_hermes(home)?;
WorldRead {
vault_keys: keys(&loaded.vault),
world: loaded.world,
}
}
WorldHarness::Openclaw => {
let loaded = from_openclaw(home)?;
WorldRead {
vault_keys: keys(&loaded.vault),
world: loaded.world,
}
}
})
}
/// `harness.v1.world.decompile`: write a world back as the source harness's home.
///
/// `source` is the home the world was compiled from. It is re-compiled here
/// for one reason: the io bookkeeping. That is what lets an artifact whose
/// record has not changed be reused byte for byte, and what lets the UNI-22
/// gate refuse a live `state.db` instead of guessing at one.
pub fn decompile(
to: WorldHarness,
world: World,
source: &Path,
source_flavor: SourceFlavor,
dest: &Path,
vault: BTreeMap<String, String>,
) -> Result<WorldDecompiled> {
Ok(match (to, source_flavor) {
// our own folder on its way out: its bytes are ours (refs, not values),
// so the codec re-emits credentials from the vault and refuses the
// session half by construction
(WorldHarness::Hermes, SourceFlavor::Orchestrator) => {
let mut loaded = load_home(source, HomeFlavor::Orchestrator.into())?;
loaded.world = world;
loaded.vault.extend(vault);
let report = to_hermes(&loaded, dest, None)?;
WorldDecompiled {
written: report.written,
refused: report.refused.iter().map(RefusalRow::from).collect(),
..WorldDecompiled::default()
}
}
(WorldHarness::Openclaw, SourceFlavor::Orchestrator) => {
let loaded = supercode_interchange::world::codec::OpenclawLoaded::from_world(world, {
let mut v = load_home(source, HomeFlavor::Orchestrator.into())?.vault;
v.extend(vault);
v
});
let report = to_openclaw(&loaded, dest)?;
WorldDecompiled {
written: report.written,
refused: report.refused.iter().map(RefusalRow::from).collect(),
notes: report.notes,
rows_byte: Some(report.rows_byte),
rows_emitted: Some(report.rows_emitted),
}
}
(WorldHarness::Hermes, SourceFlavor::Native) => {
let mut loaded = from_hermes(source)?;
loaded.world = world;
loaded.vault.extend(vault);
let report = to_hermes(&loaded, dest, None)?;
WorldDecompiled {
written: report.written,
refused: report.refused.iter().map(RefusalRow::from).collect(),
..WorldDecompiled::default()
}
}
(WorldHarness::Openclaw, SourceFlavor::Native) => {
let mut loaded = from_openclaw(source)?;
loaded.world = world;
loaded.vault.extend(vault);
let report = to_openclaw(&loaded, dest)?;
WorldDecompiled {
written: report.written,
refused: report.refused.iter().map(RefusalRow::from).collect(),
notes: report.notes,
rows_byte: Some(report.rows_byte),
rows_emitted: Some(report.rows_emitted),
}
}
})
}
/// `harness.v1.world.import`: another harness's home becomes our folder.
///
/// A compile followed by a save, with the credentials along: the source's
/// secret values land in our `.env` and every other file carries a ref. Every
/// artifact is emitted canonically — the source's bytes are another
/// harness's, never reused as ours — and the files the world does not model
/// (`MEMORY.md`, `skills/`, an agent's transcripts) are carried by path.
pub fn import(from: WorldHarness, home: &Path, into: &Path) -> Result<WorldImported> {
let (world, vault, sources): (World, BTreeMap<String, String>, BTreeMap<String, PathBuf>) =
match from {
WorldHarness::Hermes => {
let loaded = from_hermes(home)?;
let sources = loaded
.io
.iter()
.filter_map(|(name, io)| Some((name.clone(), io.source_dir.clone()?)))
.collect();
(loaded.world, loaded.vault, sources)
}
WorldHarness::Openclaw => {
let loaded = from_openclaw(home)?;
// the root profile's unmodeled files are listed from the state
// dir; a named agent's from `agents/<id>/`
let sources = loaded
.profiles
.iter()
.map(|(name, io)| {
let src = if name == "default" {
loaded.root.state_dir.clone()
} else {
io.source_dir.clone()
};
(name.clone(), src)
})
.collect();
(loaded.world, loaded.vault, sources)
}
};
let mut loaded = LoadedHome {
world,
vault,
io: BTreeMap::new(),
};
repoint(&mut loaded.world, into);
save_home(&mut loaded, Some(into))?;
let mut carried = Vec::new();
for (name, profile) in &loaded.world.profiles {
let Some(src) = sources.get(name) else {
continue;
};
// a file the SOURCE does not model may share its name with an
// artifact we own (OpenClaw's legacy `cron/jobs.json` is a store key
// to it and a jobs file to us); a carried byte never overwrites an
// owned artifact, and a re-import refreshes every other carried file
let files: Vec<String> = profile
.residue
.files
.iter()
.filter(|rel| !OWNED_FILES.contains(&rel.as_str()))
.cloned()
.collect();
for rel in carry_unmodeled(&files, src, &profile.dir)? {
carried.push(if name == "default" {
rel
} else {
format!("profiles/{name}/{rel}")
});
}
}
Ok(WorldImported {
vault_keys: keys(&loaded.vault),
world: loaded.world,
root: into.to_path_buf(),
carried,
})
}
/// `harness.v1.world.export`: our folder becomes another harness's home.
///
/// A load followed by a decompile from our flavor, with the credentials
/// along: the values our `.env` holds are written where the harness reads
/// them. The session half is the codec's to refuse (UNI-22).
pub fn export(to: WorldHarness, root: &Path, dest: &Path) -> Result<WorldDecompiled> {
let loaded = load_home(root, Flavor::Orchestrator)?;
decompile(
to,
loaded.world,
root,
SourceFlavor::Orchestrator,
dest,
loaded.vault,
)
}