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
use clap::Parser;
use memstead_base::Entity;
use memstead_base::EntityId;
use memstead_base::Store;
use memstead_base::chunking::apply_chunking;
use memstead_base::render;
use crate::CliError;
use crate::output::{ExitKind, print_markdown};
use crate::setup::{CliContext, CliEngine};
/// Read one entity as markdown.
#[derive(Parser, Debug)]
pub struct Args {
/// Entity ID (e.g. `specs--my-entity`).
pub id: String,
/// Restrict output to specific section keys (repeatable).
#[arg(long = "section", value_name = "KEY")]
pub sections: Vec<String>,
/// Append relations as a trailing JSON code block.
#[arg(long)]
pub include_relations: bool,
/// Token budget for chunking. Omit for no chunking.
#[arg(long)]
pub token_budget: Option<usize>,
/// 1-based chunk index to return (requires `--token-budget`).
#[arg(long)]
pub chunk: Option<usize>,
/// Append the derived mutation-provenance block: created-by and
/// last-modified-by with actor, client, declared role (or
/// `unspecified`), and timestamp — read from the append-only
/// mutation record, which no verb can edit after the fact.
#[arg(long = "provenance")]
pub provenance: bool,
}
pub fn run(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
let id = EntityId::canonical(&args.id);
// The engine's `get_entity` returns `Option<&Entity>`, so the
// typed `ENTITY_NOT_FOUND` code lives on the CLI side here —
// pin it explicitly so the wire envelope matches what the engine
// would emit from a write-path miss.
let miss = |engine: &memstead_base::Engine| {
// A quarantined mem's entities are deliberately absent — the
// read names the quarantine (MEM_QUARANTINED with the boot
// reason), not a phantom ENTITY_NOT_FOUND.
if engine.quarantine_reason(id.mem()).is_some() {
return CliError::from_engine_op(engine.unknown_mem_error(id.mem()));
}
CliError::new(
ExitKind::NotFound,
"ENTITY_NOT_FOUND",
format!("Entity not found: {}", args.id),
)
.with_details(serde_json::json!({ "id": args.id }))
};
// Snapshot the store's outgoing edges alongside the entity so the
// JSON envelope can resolve each relationship's `source` label after
// the engine goes out of scope. The outgoing edges carry the
// authoritative `EdgeSource` discriminator (`Explicit` /
// `BodyLink` / `Hierarchy`); the entity's `relationships` vec
// doesn't encode it.
// Derived mutation-provenance block (agent-trust plan 13), only
// when `--provenance` asked for it — default output stays
// byte-unchanged. Unavailability (an archive seam with no
// history) is stated, never fabricated.
let provenance_block = |engine: &memstead_base::Engine| -> Option<serde_json::Value> {
if !args.provenance {
return None;
}
Some(match engine.entity_provenance(id.mem(), id.as_ref()) {
Ok(prov) => serde_json::to_value(&prov).unwrap_or(serde_json::Value::Null),
Err(e) => serde_json::json!({ "unavailable": e.to_string() }),
})
};
// Load scope: everything this command renders lives in the target
// mem's slice of the store — the entity, its sections, and its
// OUTGOING edges (carried by its own source record) — plus mount
// metadata. So a lazy workspace pays only the target mem's load,
// the cold-path cut the plan names. Three forms are cross-mem and
// take the full load, never a partial answer:
// `--include-relations` (INCOMING edges can originate in any mem),
// declared signals (an `in`-direction signal reads incoming edges,
// and a neighbour pair reads the counterpart record either side of
// the edge), and the labelling view (it counts the cross-mem edges
// it excludes, and the support walk may cross mems). The scoped
// cold path stays for every mem whose schema declares neither.
let declares_cross_mem_serving = |schema: Option<std::sync::Arc<memstead_schema::Schema>>| {
schema.is_some_and(|s| {
s.manifest.relationships.labelling.is_some()
|| s.types.values().any(|td| !td.signals.is_empty())
})
};
let engine_handle = if args.include_relations {
ctx.cli_engine()?
} else {
let scoped = ctx.cli_engine_scoped(id.mem())?;
let escalate = match &scoped {
#[cfg(feature = "mem-repo")]
CliEngine::MemRepo(engine) => declares_cross_mem_serving(engine.schema_for(id.mem())),
CliEngine::Filesystem(engine) => {
declares_cross_mem_serving(engine.schema_for(id.mem()))
}
};
if escalate { ctx.cli_engine()? } else { scoped }
};
let (
entity,
output,
outgoing_snapshot,
incoming_snapshot,
origin,
provenance,
signals,
labelling,
) = match engine_handle {
#[cfg(feature = "mem-repo")]
CliEngine::MemRepo(engine) => {
let entity = engine
.get_entity(&id)
.cloned()
.ok_or_else(|| miss(&engine))?;
let signals = engine.computed_signals(&entity);
let labelling = engine.computed_labelling(&entity);
let md = render_with_optional_relations(
&entity,
&id,
engine.store(),
&args,
signals.as_deref(),
labelling.as_ref(),
);
let outgoing = engine.store().outgoing(&id).to_vec();
let incoming = args
.include_relations
.then(|| engine.store().incoming(&id).to_vec());
let origin = engine.mem_origin_class(id.mem());
let prov = provenance_block(&engine);
(
entity, md, outgoing, incoming, origin, prov, signals, labelling,
)
}
CliEngine::Filesystem(engine) => {
let entity = engine
.get_entity(&id)
.cloned()
.ok_or_else(|| miss(&engine))?;
let signals = engine.computed_signals(&entity);
let labelling = engine.computed_labelling(&entity);
let md = render_with_optional_relations(
&entity,
&id,
engine.store(),
&args,
signals.as_deref(),
labelling.as_ref(),
);
let outgoing = engine.store().outgoing(&id).to_vec();
let incoming = args
.include_relations
.then(|| engine.store().incoming(&id).to_vec());
let origin = engine.mem_origin_class(id.mem());
let prov = provenance_block(&engine);
(
entity, md, outgoing, incoming, origin, prov, signals, labelling,
)
}
};
let chunked = match args.token_budget {
Some(budget) => apply_chunking(
&output,
budget,
args.chunk,
&[("_hash", &entity.content_hash)],
)
.map_err(|e| CliError::new(ExitKind::Generic, "CHUNK_OUT_OF_RANGE", e))?,
None => output.to_string(),
};
if ctx.json {
// The CLI `--json`
// shape mirrors the MCP `structured_content` envelope —
// typed fields (`_hash`, `id`, `mem`, `type`, sections,
// relationships) rather than a
// `{ markdown: "..." }` flat shape that would force agents to
// string-scrape frontmatter for `_hash`. Greenfield
// justifies the wire shape break.
let sections_filter = if args.sections.is_empty() {
None
} else {
Some(args.sections.as_slice())
};
let rendered_body_tokens = memstead_base::chunking::estimate_tokens(&output);
let full_tokens = if sections_filter.is_some() {
let full_body = render::render_entity_markdown(&entity, None);
Some(memstead_base::chunking::estimate_tokens(&full_body))
} else {
None
};
let mut envelope = render::build_entity_envelope(
&entity,
rendered_body_tokens,
full_tokens,
sections_filter,
None,
origin,
&outgoing_snapshot,
incoming_snapshot.as_deref(),
signals.as_deref(),
labelling.as_ref(),
);
if let (Some(prov), Some(obj)) = (&provenance, envelope.as_object_mut()) {
obj.insert("mutation_provenance".into(), prov.clone());
}
crate::output::print_json(&envelope)?;
} else {
let mut text = chunked.clone();
if let Some(prov) = &provenance {
let render_rec = |label: &str, key: &str| -> Option<String> {
let r = prov.get(key)?;
Some(format!(
"- {label}: {} ({}), role {}, at {}",
r["client"].as_str().unwrap_or("unknown client"),
r["actor"].as_str().unwrap_or("unknown actor"),
r["role"].as_str().unwrap_or("unspecified"),
r["timestamp"],
))
};
text.push_str(
"
## Mutation provenance
",
);
match prov.get("unavailable") {
Some(reason) => {
text.push_str(&format!(
"- unavailable: {}
",
reason.as_str().unwrap_or("")
));
}
None => {
if let Some(l) = render_rec("created by", "created_by") {
text.push_str(&l);
text.push('\n');
} else {
text.push_str(
"- created by: not recorded (story truncated)
",
);
}
if let Some(l) = render_rec("last modified by", "last_modified_by") {
text.push_str(&l);
text.push('\n');
}
if let Some(state) = prov.get("check_state").and_then(|v| v.as_str()) {
text.push_str(&format!("- check state: {state}\n"));
}
}
}
}
print_markdown(&text);
}
Ok(())
}
/// Render an entity's markdown body and, when `--include-relations` is
/// set, append the outgoing/incoming JSON block. Engine-agnostic: both
/// flavours expose a `&Store`.
fn render_with_optional_relations(
entity: &Entity,
id: &EntityId,
store: &Store,
args: &Args,
signals: Option<&[memstead_base::ops::signals::ComputedSignal]>,
labelling: Option<&memstead_base::ops::labelling::LabellingView>,
) -> String {
let sections_filter = if args.sections.is_empty() {
None
} else {
Some(args.sections.as_slice())
};
let mut md =
render::render_entity_markdown_with_signals(entity, sections_filter, signals, labelling);
if args.include_relations {
let outgoing = store.outgoing(id).to_vec();
let incoming = store.incoming(id).to_vec();
let rel_json = render::render_relations_json(id.as_ref(), &outgoing, &incoming);
md.push_str("\n## Relations (JSON)\n\n```json\n");
md.push_str(&serde_json::to_string_pretty(&rel_json).unwrap_or_else(|_| "{}".to_string()));
md.push_str("\n```\n");
}
md
}