Skip to main content

rightkit_context/
modes.rs

1//! What each command does: ask the resident first, then run in process (A3, C4).
2//!
3//! The resident is `membrane serve`, started and owned by the host app. A command tries its endpoint
4//! with a 100 ms connect budget; when nothing answers (`ClientError::NotRunning`) it runs the
5//! same request in this process against the stores, which never loads the embedding model.
6//! A query also falls back when the resident was reached but could not answer it. A write does
7//! not: once a resident was reached the write may have run, so replaying it here could do it
8//! twice.
9
10use crate::cli::{
11    AdaptAdjudicateTasteArgs, AdaptApplyArgs, AdaptMineSessionArgs, AdaptObserveArgs,
12    AdaptRecallArgs, AdaptStatusArgs, AdaptTasteReviewArgs, BlueprintArgs, ConfirmArgs, DeleteArgs,
13    HookArgs, InitArgs, MarkArgs, PullArgs, PushArgs, ReceiptsListArgs, SearchArgs, StatusArgs,
14    TierArg, TranscriptAppendArgs, TranscriptTipArgs, WhereArgs, WireArg,
15};
16use crate::{
17    SCHEMA_ADAPT_ADJUDICATE_TASTE, SCHEMA_ADAPT_APPLY, SCHEMA_ADAPT_MINE_SESSION,
18    SCHEMA_ADAPT_OBSERVE, SCHEMA_ADAPT_RECALL, SCHEMA_ADAPT_STATUS, SCHEMA_ADAPT_TASTE_REVIEW,
19    SCHEMA_BLUEPRINT, SCHEMA_BLUEPRINT_SEARCH, SCHEMA_CONTEXT_PULL, SCHEMA_MEMORY_DELETE,
20    SCHEMA_MEMORY_GET, SCHEMA_MEMORY_INFO, SCHEMA_MEMORY_LIST, SCHEMA_MEMORY_PUSH,
21    SCHEMA_MEMORY_SCOPES, SCHEMA_MEMORY_SEARCH, SCHEMA_RECEIPTS_MARK, SCHEMA_STATUS,
22    SCHEMA_TRANSCRIPT_APPEND, SCHEMA_TRANSCRIPT_TIP, SCHEMA_WHERE,
23};
24use rightkit_context_client::{ClientError, ResidentClient};
25use rightkit_context_protocol::session_transcript::{
26    SessionTranscriptAppendV1, SessionTranscriptEventV1, SESSION_TRANSCRIPT_SCHEMA_VERSION,
27};
28use rightkit_context_protocol::ResidentOp;
29use rightkit_context_runtime::cli::MEMORY_SEARCH_MAX_LIMIT;
30use rightkit_context_runtime::hook::{self, Wire};
31use rightkit_context_runtime::receipt::{self, HookReceiptState};
32use serde_json::{json, Map, Value};
33use std::io::{self, IsTerminal, Read};
34use std::path::{Path, PathBuf};
35use std::time::Duration;
36
37/// Wall budget for a resident answer, per command. A hook shares its host's timeout, so it gets
38/// only what a warm pull needs; the in-process run then has the rest.
39const PULL_DEADLINE: Duration = Duration::from_secs(10);
40const PUSH_DEADLINE: Duration = Duration::from_secs(5);
41const BLUEPRINT_DEADLINE: Duration = Duration::from_secs(5);
42/// How long `blueprint build` and `refresh` wait for the resident: the build's own limit
43/// (`MAX_BUILD_DEADLINE_MS`, 300 s) plus a margin, so a normal build is not reported unavailable
44/// while the resident is still writing it.
45const BLUEPRINT_WRITE_DEADLINE: Duration = Duration::from_secs(330);
46const STATUS_DEADLINE: Duration = Duration::from_secs(1);
47const SEARCH_DEADLINE: Duration = Duration::from_secs(5);
48const DELETE_DEADLINE: Duration = Duration::from_secs(5);
49const HOOK_DEADLINE: Duration = Duration::from_millis(1_500);
50
51/// The text a push may carry; the same bound the resident enforces.
52const MAX_PUSH_BYTES: usize = 1024 * 1024;
53
54/// A hook payload is a small JSON object. A host may keep stdin open for the life of its
55/// session, so the read is bounded in time as well as size: the first bytes must arrive within
56/// the grace, and the payload ends at EOF or after a short quiet interval once bytes flowed.
57const MAX_HOOK_PAYLOAD_BYTES: usize = 8 * 1024 * 1024;
58const STDIN_FIRST_BYTES_GRACE: Duration = Duration::from_secs(2);
59const STDIN_QUIET: Duration = Duration::from_millis(400);
60
61#[derive(Debug)]
62pub enum DispatchOutcome {
63    Ok,
64    UserError(String),
65    /// The answer asked for cannot be produced (no store, no context, no graph): exit 3.
66    NotAvailable(String),
67    InternalError(String),
68    /// The command already reported itself and decided the exit code (`serve`).
69    Exit(i32),
70}
71
72/// How the resident answered.
73enum Resident {
74    Answered(Value),
75    /// Nothing answered and nothing was sent.
76    Absent,
77    /// The resident was reached but did not produce an answer.
78    Failed(ClientError),
79}
80
81fn ask(op: ResidentOp, args: Value, deadline: Duration) -> Resident {
82    let state_root = rightkit_context_runtime::cli::state_root();
83    let client = match ResidentClient::connect(&state_root) {
84        Ok(client) => client,
85        Err(ClientError::NotRunning { .. }) => return Resident::Absent,
86        Err(error) => return Resident::Failed(error),
87    };
88    client.set_deadline(Some(deadline));
89    match client.call(op, args) {
90        Ok(data) => Resident::Answered(data),
91        Err(ClientError::NotRunning { .. }) => Resident::Absent,
92        Err(error) => Resident::Failed(error),
93    }
94}
95
96fn current_dir() -> Result<PathBuf, String> {
97    std::env::current_dir().map_err(|error| format!("resolve current directory: {error}"))
98}
99
100fn print_json(value: &Value) -> Result<(), String> {
101    println!(
102        "{}",
103        serde_json::to_string(value).map_err(|error| format!("encode answer: {error}"))?
104    );
105    Ok(())
106}
107
108/// `membrane context pull`: print the context for a task, or nothing when there is none. With
109/// `--wire` and `--request-id` the context is also recorded as a receipt the caller can later mark
110/// delivered.
111///
112/// What is printed is the one projection `hook::project_pull_answer` makes of the answer in its
113/// delivery mode (the bare context and a newline, or with `--json` the whole
114/// `membrane.context.pull.v1` document, `receipt` included). The resident or the in-process pull
115/// selected a representation whose complete projection fits the declared budget; here the answer
116/// is re-projected and proved to be that response (`hook::verify_pull_projection`) before
117/// anything is recorded or printed, and the approved bytes are printed as they are.
118pub fn context_pull(args: &PullArgs) -> DispatchOutcome {
119    if SCHEMA_CONTEXT_PULL != hook::PULL_DOCUMENT_SCHEMA {
120        return DispatchOutcome::InternalError(format!(
121            "context pull schema {SCHEMA_CONTEXT_PULL} is not the projected {}",
122            hook::PULL_DOCUMENT_SCHEMA
123        ));
124    }
125    let receipt_id = match (args.wire, args.request_id.as_deref()) {
126        (None, Some(_)) => {
127            return DispatchOutcome::UserError(
128                "context pull: --request-id needs --wire coderight".into(),
129            );
130        }
131        (Some(_), Some(id)) if !receipt::valid_receipt_id(id) => {
132            return DispatchOutcome::UserError(
133                "context pull: --request-id takes 1 to 128 letters, digits, '-' or '_'".into(),
134            );
135        }
136        (Some(_), Some(id)) => Some(id.to_owned()),
137        _ => None,
138    };
139    // `--cwd` and `--repo` name the same thing; both are accepted only when they are the same path.
140    if let (Some(repo), Some(cwd)) = (&args.repo, &args.cwd) {
141        let same = match (repo.canonicalize(), cwd.canonicalize()) {
142            (Ok(repo), Ok(cwd)) => repo == cwd,
143            _ => repo == cwd,
144        };
145        if !same {
146            return DispatchOutcome::UserError(
147                "context pull: --cwd and --repo name different paths; give one".into(),
148            );
149        }
150    }
151    let cwd = match args
152        .repo
153        .clone()
154        .or_else(|| args.cwd.clone())
155        .map(Ok)
156        .unwrap_or_else(current_dir)
157    {
158        Ok(cwd) => cwd,
159        Err(error) => return DispatchOutcome::UserError(error),
160    };
161    let spec = hook::PullProjectionSpec {
162        delivery: if args.json {
163            hook::PullDelivery::Json
164        } else {
165            hook::PullDelivery::Text
166        },
167        receipt_id,
168    };
169    let budget = hook::effective_pull_budget(args.budget.map(|budget| budget as u64));
170    let request = json!({
171        "cwd": cwd,
172        "prompt": args.prompt,
173        "budget": args.budget,
174        "client": "cli",
175        "session": format!("cli-{}", std::process::id()),
176        "delivery": spec.delivery.as_str(),
177        "receiptId": spec.receipt_id,
178    });
179    let from_resident = match ask(ResidentOp::Pull, request.clone(), PULL_DEADLINE) {
180        Resident::Answered(data) => hook::context_text(&data).map(|_| data),
181        // An answered refusal is final: the in-process path never runs behind it, whether the
182        // caller was denied or no response fits the declared budget.
183        Resident::Failed(ClientError::Refused { code, message, .. })
184            if code == rightkit_context_runtime::authorization::PULL_REFUSAL_CODE
185                || message.starts_with(SELECTION_REFUSAL_PREFIX) =>
186        {
187            return DispatchOutcome::NotAvailable(message);
188        }
189        _ => None,
190    };
191    let data = match from_resident {
192        Some(data) => data,
193        None => match rightkit_context_runtime::cli::op_pull(&request) {
194            Ok(data) => data,
195            Err(error) => return DispatchOutcome::NotAvailable(error),
196        },
197    };
198    let approved = match hook::verify_pull_projection(&data, &spec, budget) {
199        Ok(approved) => approved,
200        Err(error) => return DispatchOutcome::NotAvailable(error),
201    };
202    if let Some(id) = &spec.receipt_id {
203        let emitted = hook::context_text(&data).flatten().is_some();
204        if let Err(error) = record_pull_receipt(id, emitted) {
205            return DispatchOutcome::InternalError(error);
206        }
207    }
208    // The age of the graph travels beside the approved bytes, never inside them: the projection
209    // above is proved token-exact against its budget, so a line added to it would break that
210    // proof. stderr is what a calling agent's shell shows next to the context (#555).
211    if let Some(line) = rightkit_context_runtime::graph_health::staleness_line(
212        graph_status(&cwd).as_ref(),
213        rightkit_context_runtime::graph_health::is_enrolled(&cwd),
214    ) {
215        use std::io::Write as _;
216        let _ = writeln!(io::stderr(), "{line}");
217    }
218    print!("{approved}");
219    DispatchOutcome::Ok
220}
221
222/// How long a pull waits for the Blueprint status that decides its staleness line: the resident's
223/// answer, or the in-process read bounded by `--deadline-ms` below.
224const GRAPH_STATUS_DEADLINE: Duration = Duration::from_millis(2_500);
225const GRAPH_STATUS_READ_MS: &str = "1500";
226
227/// The Blueprint `status` answer for `cwd`: from the resident; a bounded in-process read only when
228/// no resident is running. `None` when the resident timed out or the read failed, which callers report as "not checked", never as fresh.
229fn graph_status(cwd: &Path) -> Option<Value> {
230    let query = vec![
231        "status".to_owned(),
232        "--deadline-ms".to_owned(),
233        GRAPH_STATUS_READ_MS.to_owned(),
234    ];
235    match ask(
236        ResidentOp::Blueprint,
237        json!({"query": query, "cwd": cwd}),
238        GRAPH_STATUS_DEADLINE,
239    ) {
240        Resident::Answered(data) => Some(data),
241        // A resident that is running but did not answer in time is reported as "not checked":
242        // a second, in-process read behind it would add its own 1.5 s plus SQLite's busy wait.
243        Resident::Failed(_) => None,
244        // No resident is running: the bounded in-process read is the only reader.
245        Resident::Absent => {
246            rightkit_context_runtime::cli::blueprint_query_value(&query, Some(cwd)).ok()
247        }
248    }
249}
250
251/// `membrane blueprint status --all`: one entry per enrolled root with its last build, freshness
252/// state and its own watcher state, so one degraded root no longer hides the healthy ones behind
253/// the aggregate `watcherReady` (#555).
254fn blueprint_status_all() -> DispatchOutcome {
255    let roots = match rightkit_context_runtime::graph_health::enrolled_roots() {
256        Ok(roots) => roots,
257        Err(error) => return DispatchOutcome::NotAvailable(error),
258    };
259    let resident = match ask(ResidentOp::Status, json!({}), STATUS_DEADLINE) {
260        Resident::Answered(status) => Some(status),
261        Resident::Absent | Resident::Failed(_) => None,
262    };
263    let entries: Vec<Value> = roots
264        .iter()
265        .map(|root| {
266            let graph = graph_status(Path::new(root));
267            rightkit_context_runtime::graph_health::root_status(
268                root,
269                graph.as_ref(),
270                resident.as_ref(),
271            )
272        })
273        .collect();
274    let mut fields = Map::new();
275    fields.insert("roots".into(), Value::Array(entries));
276    fields.insert(
277        "residentWatcher".into(),
278        resident
279            .as_ref()
280            .and_then(|status| status.get("blueprint").cloned())
281            .unwrap_or(Value::Null),
282    );
283    print_document(SCHEMA_BLUEPRINT, fields)
284}
285
286/// The reason prefix of a typed request-time refusal (no response fits the declared budget, a
287/// stale or mismatched projection): an answered refusal, final like an authorization denial.
288const SELECTION_REFUSAL_PREFIX: &str = "request_time_selection_refused:";
289
290/// Record the context a caller will inject: `emitted` when there was context to deliver, which
291/// writes the receipt, and `empty` when there was none, which writes nothing. The receipt the
292/// document reports is part of the approved projection (`hook::pull_receipt_projection`).
293fn record_pull_receipt(id: &str, emitted: bool) -> Result<(), String> {
294    if emitted {
295        let record =
296            receipt::ContextReceipt::emitted(id, hook::PULL_RECEIPT_SESSION, "coderight", "pull");
297        receipt::write_context_receipt(&rightkit_context_runtime::cli::state_root(), &record)
298            .map_err(|error| format!("record receipt {id}: {error}"))?;
299    }
300    Ok(())
301}
302
303/// Print `fields` as one JSON object whose top-level `schema` is `schema`. A `schema` field the
304/// answer already carried moves to `payload_schema` rather than being lost.
305fn print_document(schema: &str, mut fields: Map<String, Value>) -> DispatchOutcome {
306    if let Some(inner) = fields.remove("schema") {
307        if inner != Value::String(schema.to_owned()) {
308            fields.insert("payload_schema".into(), inner);
309        }
310    }
311    let mut document = Map::new();
312    document.insert("schema".into(), Value::String(schema.to_owned()));
313    document.extend(fields);
314    match print_json(&Value::Object(document)) {
315        Ok(()) => DispatchOutcome::Ok,
316        Err(error) => DispatchOutcome::InternalError(error),
317    }
318}
319
320/// `membrane memory push`: store text as a durable memory.
321pub fn memory_push(args: &PushArgs) -> DispatchOutcome {
322    let text = match (&args.text, args.stdin) {
323        (Some(text), false) => text.clone(),
324        _ => {
325            let mut bytes = Vec::new();
326            if let Err(error) = io::stdin()
327                .take((MAX_PUSH_BYTES + 1) as u64)
328                .read_to_end(&mut bytes)
329            {
330                return DispatchOutcome::UserError(format!("read stdin: {error}"));
331            }
332            if bytes.len() > MAX_PUSH_BYTES {
333                return DispatchOutcome::UserError("text exceeds 1 MiB".into());
334            }
335            match String::from_utf8(bytes) {
336                Ok(text) => text,
337                Err(_) => return DispatchOutcome::UserError("stdin is not UTF-8 text".into()),
338            }
339        }
340    };
341    if text.trim().is_empty() {
342        return DispatchOutcome::UserError("refusing to push empty text".into());
343    }
344    // The placement is checked here, before anything is sent: the scope is made canonical and the
345    // name checked, so the resident and the in-process path store exactly what is answered.
346    let scope = match args
347        .scope
348        .as_deref()
349        .map(rightkit_context_runtime::cli::canonical_write_scope)
350    {
351        Some(Ok(scope)) => Some(scope),
352        Some(Err(error)) => return DispatchOutcome::UserError(format!("memory push: {error}")),
353        None => None,
354    };
355    let name = args.name.as_deref().map(str::trim);
356    if let Some(name) = name {
357        if let Err(error) = rightkit_context_runtime::cli::validate_memory_name(name) {
358            return DispatchOutcome::UserError(format!("memory push: {error}"));
359        }
360    }
361    let tier = args.tier.map(tier_name);
362    let mut request = json!({"content": text});
363    if let Some(name) = name {
364        request["name"] = json!(name);
365    }
366    if let Some(scope) = &scope {
367        request["scope"] = json!(scope);
368    }
369    if let Some(tier) = tier {
370        request["tier"] = json!(tier);
371    }
372    if !args.keywords.is_empty() {
373        request["keywords"] = json!(args.keywords);
374    }
375    let result = match ask(ResidentOp::Push, request.clone(), PUSH_DEADLINE) {
376        Resident::Answered(data) => Ok(data),
377        Resident::Absent => rightkit_context_runtime::cli::push_memory_request(&request),
378        Resident::Failed(error) => Err(error.to_string()),
379    };
380    let data = match result {
381        Ok(data) => data,
382        Err(error) => return DispatchOutcome::UserError(error),
383    };
384    // A resident started before this build stores `content` and ignores the placement. The write
385    // has happened and is not repeated, so say what was stored instead of printing a false id.
386    let stored_scope = data
387        .get("scope_id")
388        .or_else(|| data.get("scope"))
389        .and_then(Value::as_str)
390        .unwrap_or("");
391    let stored_tier = data
392        .get("tier")
393        .and_then(Value::as_str)
394        .unwrap_or("")
395        .to_lowercase();
396    let id = data.get("id").and_then(Value::as_str).unwrap_or("");
397    let expected_id = name.map(|name| format!("{}/{name}", scope.as_deref().unwrap_or("global")));
398    let placed = scope.as_deref().is_none_or(|scope| scope == stored_scope)
399        && tier.is_none_or(|tier| tier == stored_tier)
400        && expected_id.as_deref().is_none_or(|expected| expected == id);
401    if !placed {
402        return DispatchOutcome::InternalError(format!(
403            "memory push: the resident stored memory {id} in scope {stored_scope} without the requested name, scope or tier (it predates this option; restart the host app); remove it with `membrane memory delete {id}` and push again"
404        ));
405    }
406    if !args.json {
407        return match print_json(&data) {
408            Ok(()) => DispatchOutcome::Ok,
409            Err(error) => DispatchOutcome::UserError(error),
410        };
411    }
412    let mut fields = Map::new();
413    fields.insert("id".into(), json!(id));
414    fields.insert("scope".into(), json!(stored_scope));
415    fields.insert("tier".into(), json!(stored_tier));
416    fields.insert("name".into(), name.map_or(Value::Null, |name| json!(name)));
417    fields.insert(
418        "keywords".into(),
419        data.get("keywords").cloned().unwrap_or(json!([])),
420    );
421    print_document(SCHEMA_MEMORY_PUSH, fields)
422}
423
424/// `membrane memory <command>`: the durable-memory maintenance commands, in process.
425/// `memory list --json` is answered here as one `membrane.memory.list.v1` document.
426pub fn memory_durable(rest: &[String]) -> DispatchOutcome {
427    if rest.first().map(String::as_str) == Some("list") {
428        let names_repository = rest.iter().any(|arg| {
429            matches!(
430                arg.split('=').next(),
431                Some("--repo" | "--repo-root" | "--cwd")
432            )
433        });
434        let json = rest.iter().any(|arg| arg == "--json");
435        if names_repository && !json {
436            return DispatchOutcome::UserError(
437                "memory list: --repo and --cwd print JSON; add --json".into(),
438            );
439        }
440        let scope_flags = rest
441            .iter()
442            .filter(|arg| arg.split('=').next() == Some("--scope"))
443            .count();
444        if scope_flags > 1 && !json {
445            return DispatchOutcome::UserError(
446                "memory list: a scope chain (--scope more than once) prints JSON; add --json"
447                    .into(),
448            );
449        }
450        if json {
451            return memory_list_json(&rest[1..]);
452        }
453    }
454    let json = rest.iter().any(|arg| arg == "--json");
455    match rest.first().map(String::as_str) {
456        Some("get") if json => return memory_get_json(&rest[1..]),
457        Some("scopes") => return memory_scopes(&rest[1..]),
458        Some("info") => return memory_info(&rest[1..]),
459        // `host memory history ...` reaches here as `memory history ...`.
460        Some("history") => return history(&rest[1..]),
461        _ => {}
462    }
463    let mut argv = vec!["membrane".to_owned()];
464    argv.extend(rest.iter().cloned());
465    let refs = argv.iter().map(String::as_str).collect::<Vec<_>>();
466    match rightkit_context_runtime::cli::run_cortex_durable_cli_from(&refs) {
467        Ok(()) => DispatchOutcome::Ok,
468        Err(error) => DispatchOutcome::UserError(error),
469    }
470}
471
472/// `membrane history search|status|erase`: the ChatGPT and Codex history lane (Ledger transcripts).
473/// Runs in process against the stores; nothing is searched while the manifest is absent or off.
474pub fn history(words: &[String]) -> DispatchOutcome {
475    use rightkit_context_runtime::ledger::limits::WorkBudget;
476    use rightkit_context_runtime::ledger::transcripts as tx;
477    let value_of = |flag: &str| -> Result<Option<String>, String> {
478        let inline = format!("{flag}=");
479        let mut found = None;
480        let mut iter = words.iter();
481        while let Some(word) = iter.next() {
482            if let Some(value) = word.strip_prefix(&inline) {
483                found = Some(value.to_owned());
484            } else if word == flag {
485                let value = iter
486                    .next()
487                    .ok_or_else(|| format!("history: {flag} needs a value"))?;
488                found = Some(value.clone());
489            }
490        }
491        Ok(found)
492    };
493    let to_user = |error: String| DispatchOutcome::NotAvailable(format!("history: {error}"));
494    match words.first().map(String::as_str) {
495        Some("search") => {
496            // The text is every word that is not a flag or a flag's value.
497            let mut text = Vec::new();
498            let mut skip = false;
499            for word in &words[1..] {
500                if skip {
501                    skip = false;
502                } else if matches!(word.as_str(), "--scope" | "--limit") {
503                    skip = true;
504                } else if !word.starts_with("--") {
505                    text.push(word.as_str());
506                }
507            }
508            if text.is_empty() {
509                return DispatchOutcome::UserError("history search requires text".into());
510            }
511            let limit = match value_of("--limit") {
512                Ok(Some(raw)) => match raw.parse::<usize>() {
513                    Ok(limit) if limit >= 1 => limit,
514                    _ => {
515                        return DispatchOutcome::UserError(
516                            "history: --limit must be a positive number".into(),
517                        )
518                    }
519                },
520                Ok(None) => 10,
521                Err(error) => return DispatchOutcome::UserError(error),
522            };
523            let scopes = match value_of("--scope") {
524                // An explicit scope is only a narrowing of what the manifest enrols: the search
525                // owner checks it against the current manifest and refuses one outside it.
526                Ok(Some(scope)) => vec![scope],
527                Ok(None) => match tx::load_manifest(&tx::manifest_path()) {
528                    Ok(Some(manifest)) if manifest.enabled => {
529                        let mut scopes: Vec<String> =
530                            manifest.sources.iter().map(|s| s.scope.clone()).collect();
531                        scopes.sort();
532                        scopes.dedup();
533                        scopes
534                    }
535                    Ok(_) => {
536                        return DispatchOutcome::NotAvailable(
537                            "history: off; turn on \"Search ChatGPT and Codex history\" in the host app settings".into(),
538                        )
539                    }
540                    Err(error) => return to_user(error),
541                },
542                Err(error) => return DispatchOutcome::UserError(error),
543            };
544            let query = tx::TxQuery {
545                scopes,
546                text: text.join(" "),
547                limit,
548                provider: None,
549                role: None,
550                since_ms: None,
551                until_ms: None,
552                current_path_only: true,
553            };
554            match tx::search_default(&query, &WorkBudget::bounded(Duration::from_secs(10))) {
555                Ok(result) => match serde_json::to_value(&result) {
556                    Ok(Value::Object(fields)) => print_document("membrane.history.search.v1", fields),
557                    Ok(_) => DispatchOutcome::InternalError("history: unexpected result shape".into()),
558                    Err(error) => DispatchOutcome::InternalError(error.to_string()),
559                },
560                Err(error) => to_user(error),
561            }
562        }
563        Some("status") => match tx::status_default() {
564            Ok(Value::Object(fields)) => print_document("membrane.history.status.v1", fields),
565            Ok(other) => {
566                let mut fields = Map::new();
567                fields.insert("status".into(), other);
568                print_document("membrane.history.status.v1", fields)
569            }
570            Err(error) => to_user(error),
571        },
572        Some("erase") => {
573            let conversation = value_of("--conversation");
574            let source = value_of("--source");
575            match (conversation, source) {
576                (Ok(Some(id)), Ok(None)) => match tx::erase_conversation_default(&id) {
577                    Ok(removed) => {
578                        let mut fields = Map::new();
579                        fields.insert("conversation".into(), Value::String(id));
580                        fields.insert("removed".into(), json!(removed));
581                        print_document("membrane.history.erase.v1", fields)
582                    }
583                    Err(error) => to_user(error),
584                },
585                (Ok(None), Ok(Some(id))) => match tx::erase_source_default(&id) {
586                    Ok(()) => {
587                        let mut fields = Map::new();
588                        fields.insert("source".into(), Value::String(id));
589                        fields.insert("erased".into(), Value::Bool(true));
590                        print_document("membrane.history.erase.v1", fields)
591                    }
592                    Err(error) => to_user(error),
593                },
594                (Err(error), _) | (_, Err(error)) => DispatchOutcome::UserError(error),
595                _ => DispatchOutcome::UserError(
596                    "history erase needs exactly one of --conversation ID or --source ID".into(),
597                ),
598            }
599        }
600        _ => DispatchOutcome::UserError(
601            "history: use search <text> [--scope S] [--limit N], status, or erase --conversation ID | --source ID".into(),
602        ),
603    }
604}
605
606/// Take `--repo <path>` (or `--repo-root <path>`, or either joined with `=`) out of a blueprint
607/// query. What is left is the query. The flag may stand anywhere in the words.
608fn split_repo_flag(words: &[String]) -> Result<(Option<PathBuf>, Vec<String>), String> {
609    let mut repo = None;
610    let mut rest = Vec::new();
611    let mut iter = words.iter();
612    while let Some(word) = iter.next() {
613        let inline = word
614            .strip_prefix("--repo=")
615            .or_else(|| word.strip_prefix("--repo-root="));
616        if let Some(value) = inline {
617            repo = Some(PathBuf::from(value));
618        } else if word == "--repo" || word == "--repo-root" {
619            let value = iter
620                .next()
621                .ok_or_else(|| format!("blueprint: {word} needs a path"))?;
622            repo = Some(PathBuf::from(value));
623        } else {
624            rest.push(word.clone());
625        }
626    }
627    if rest.is_empty() {
628        return Err("blueprint requires a query".into());
629    }
630    Ok((repo, rest))
631}
632
633/// `membrane blueprint <query…> [--repo <path>]`: read verbs answer from the resident, else in
634/// process. `build` and `refresh` write: resident answers, or with no resident the CLI builds under
635/// the owner lock, or a typed unavailable error. `--repo` names the repository without a chdir; without it, the current directory.
636pub fn blueprint(args: &BlueprintArgs) -> DispatchOutcome {
637    let (repo, query) = match split_repo_flag(&args.query) {
638        Ok(split) => split,
639        Err(error) => return DispatchOutcome::UserError(error),
640    };
641    if query == ["status", "--all"] {
642        return blueprint_status_all();
643    }
644    let cwd = match repo.map(Ok).unwrap_or_else(current_dir) {
645        Ok(cwd) => cwd,
646        Err(error) => return DispatchOutcome::UserError(error),
647    };
648    // `blueprint search <text>` has its own schema id; the other verbs keep the Blueprint id.
649    let schema = if query.first().map(String::as_str) == Some("search") {
650        SCHEMA_BLUEPRINT_SEARCH
651    } else {
652        SCHEMA_BLUEPRINT
653    };
654    let request = json!({"query": query, "cwd": cwd});
655    let deadline = if rightkit_context_runtime::cli::blueprint_verb_writes(&query) {
656        BLUEPRINT_WRITE_DEADLINE
657    } else {
658        BLUEPRINT_DEADLINE
659    };
660    let data = match ask(ResidentOp::Blueprint, request, deadline) {
661        Resident::Answered(data) => Ok(data),
662        // `build` and `refresh` write the graph. Only an absent resident lets the CLI write, and
663        // then under the owner lock; a resident that timed out or failed may still be writing, so
664        // a second writer is never started (INV-008).
665        Resident::Absent if rightkit_context_runtime::cli::blueprint_verb_writes(&query) => {
666            rightkit_context_runtime::cli::blueprint_write_one_shot(&query, Some(&cwd))
667        }
668        Resident::Failed(error) if rightkit_context_runtime::cli::blueprint_verb_writes(&query) => Err(
669            format!("membrane_resident_unavailable: the resident did not answer ({error}); not writing a second graph"),
670        ),
671        Resident::Absent | Resident::Failed(_) => {
672            rightkit_context_runtime::cli::blueprint_query_value(&query, Some(&cwd))
673        }
674    };
675    match data {
676        Ok(Value::Object(fields)) => print_document(schema, fields),
677        Ok(other) => {
678            let mut fields = Map::new();
679            fields.insert("result".into(), other);
680            print_document(schema, fields)
681        }
682        Err(error) => {
683            let usage = error.starts_with("unsupported")
684                || error.starts_with("--")
685                || error.contains(" requires ");
686            if usage {
687                DispatchOutcome::UserError(error)
688            } else {
689                DispatchOutcome::NotAvailable(error)
690            }
691        }
692    }
693}
694
695/// `membrane memory list [--scope <id>]... [--limit <n>] [--db <path>] --json`. Repeating
696/// `--scope` lists a scope chain, in the order given.
697fn memory_list_json(flags: &[String]) -> DispatchOutcome {
698    let mut scopes: Vec<String> = Vec::new();
699    let mut limit: usize = 1_000;
700    let mut db: Option<String> = None;
701    let mut repo: Option<PathBuf> = None;
702    let mut index = 0;
703    while index < flags.len() {
704        let flag = flags[index].as_str();
705        let (name, inline) = match flag.split_once('=') {
706            Some((name, value)) => (name, Some(value.to_owned())),
707            None => (flag, None),
708        };
709        if name == "--json" && inline.is_none() {
710            index += 1;
711            continue;
712        }
713        if !matches!(
714            name,
715            "--scope" | "--limit" | "--db" | "--repo" | "--repo-root" | "--cwd"
716        ) {
717            return DispatchOutcome::UserError(format!("memory list: unknown argument `{flag}`"));
718        }
719        let value = match inline {
720            Some(value) => value,
721            None => {
722                index += 1;
723                match flags.get(index) {
724                    Some(value) => value.clone(),
725                    None => {
726                        return DispatchOutcome::UserError(format!(
727                            "memory list: {name} needs a value"
728                        ));
729                    }
730                }
731            }
732        };
733        match name {
734            "--scope" => scopes.push(value),
735            "--db" => db = Some(value),
736            "--repo" | "--repo-root" | "--cwd" => {
737                if repo.is_some() {
738                    return DispatchOutcome::UserError(
739                        "memory list: give the repository once".into(),
740                    );
741                }
742                repo = Some(PathBuf::from(value));
743            }
744            _ => match value.parse::<usize>() {
745                Ok(parsed) if parsed > 0 => limit = parsed,
746                _ => {
747                    return DispatchOutcome::UserError(
748                        "memory list: --limit must be a positive integer".into(),
749                    );
750                }
751            },
752        }
753        index += 1;
754    }
755    if repo.is_some() && !scopes.is_empty() {
756        return DispatchOutcome::UserError(
757            "memory list: --scope and --repo both name the scope; give one".into(),
758        );
759    }
760    if repo.is_some() {
761        scopes = repository_scope(repo.as_deref(), None)
762            .into_iter()
763            .collect();
764    }
765    let path = memory_db_path(db.as_deref().map(Path::new));
766    if !path.is_file() {
767        return DispatchOutcome::NotAvailable(no_store_message(&path));
768    }
769    let answer =
770        match rightkit_context_runtime::cli::list_memories_in_process(&path, &scopes, limit) {
771            Ok(answer) => answer,
772            Err(error) => return DispatchOutcome::InternalError(format!("list memories: {error}")),
773        };
774    let Value::Object(mut document) = answer else {
775        return DispatchOutcome::InternalError("list memories: the answer is not an object".into());
776    };
777    // `scope` is kept for callers of the single-scope form: the scope listed, else null.
778    let single = match document
779        .get("scopes")
780        .and_then(Value::as_array)
781        .map(Vec::as_slice)
782    {
783        Some([only]) => only.clone(),
784        _ => Value::Null,
785    };
786    document.insert("scope".into(), single);
787    print_document(SCHEMA_MEMORY_LIST, document)
788}
789
790/// The flags of a `memory get|scopes|info` command line: its positional words, whether `--json`
791/// was given, and the value of each flag in `valued` (`--flag value` or `--flag=value`).
792type MemoryFlags = (Vec<String>, bool, Vec<(String, String)>);
793
794fn memory_flags(command: &str, flags: &[String], valued: &[&str]) -> Result<MemoryFlags, String> {
795    let mut positional = Vec::new();
796    let mut json = false;
797    let mut values: Vec<(String, String)> = Vec::new();
798    let mut index = 0;
799    while index < flags.len() {
800        let flag = flags[index].as_str();
801        index += 1;
802        if flag == "--json" {
803            json = true;
804            continue;
805        }
806        if !flag.starts_with("--") {
807            positional.push(flag.to_owned());
808            continue;
809        }
810        let (name, inline) = match flag.split_once('=') {
811            Some((name, value)) => (name, Some(value.to_owned())),
812            None => (flag, None),
813        };
814        if !valued.contains(&name) {
815            return Err(format!("memory {command}: unknown argument `{flag}`"));
816        }
817        let value = match inline {
818            Some(value) => value,
819            None => match flags.get(index) {
820                Some(value) => {
821                    index += 1;
822                    value.clone()
823                }
824                None => return Err(format!("memory {command}: {name} needs a value")),
825            },
826        };
827        values.push((name.to_owned(), value));
828    }
829    Ok((positional, json, values))
830}
831
832fn flag_value<'a>(values: &'a [(String, String)], name: &str) -> Option<&'a str> {
833    values
834        .iter()
835        .rev()
836        .find(|(flag, _)| flag == name)
837        .map(|(_, value)| value.as_str())
838}
839
840/// The memory store a read command opens, or the outcome that says why it cannot.
841fn memory_read_store(values: &[(String, String)]) -> Result<PathBuf, DispatchOutcome> {
842    let path = memory_db_path(flag_value(values, "--db").map(Path::new));
843    if path.is_file() {
844        Ok(path)
845    } else {
846        Err(DispatchOutcome::NotAvailable(no_store_message(&path)))
847    }
848}
849
850/// `membrane memory get <id> --json [--db <path>]`: one memory with its full content as a
851/// `membrane.memory.get.v1` document. A read that records no use. A missing id is exit 3.
852fn memory_get_json(flags: &[String]) -> DispatchOutcome {
853    let (positional, _, values) = match memory_flags("get", flags, &["--db"]) {
854        Ok(parsed) => parsed,
855        Err(error) => return DispatchOutcome::UserError(error),
856    };
857    let [id] = positional.as_slice() else {
858        return DispatchOutcome::UserError("memory get: give exactly one memory id".into());
859    };
860    let path = match memory_read_store(&values) {
861        Ok(path) => path,
862        Err(outcome) => return outcome,
863    };
864    match rightkit_context_runtime::cli::get_memory_in_process(&path, id) {
865        Ok(Some(Value::Object(mut fields))) => {
866            fields.insert("found".into(), Value::Bool(true));
867            print_document(SCHEMA_MEMORY_GET, fields)
868        }
869        Ok(_) => {
870            let mut fields = Map::new();
871            fields.insert("id".into(), json!(id));
872            fields.insert("found".into(), Value::Bool(false));
873            if let DispatchOutcome::InternalError(error) = print_document(SCHEMA_MEMORY_GET, fields)
874            {
875                return DispatchOutcome::InternalError(error);
876            }
877            eprintln!("membrane: no memory has id {id}");
878            DispatchOutcome::Exit(crate::EXIT_NOT_AVAILABLE)
879        }
880        Err(error) => DispatchOutcome::InternalError(format!("memory get: {error}")),
881    }
882}
883
884/// `membrane memory scopes [--json] [--db <path>]`: every scope that holds a memory, with its
885/// count.
886fn memory_scopes(flags: &[String]) -> DispatchOutcome {
887    let (positional, json, values) = match memory_flags("scopes", flags, &["--db"]) {
888        Ok(parsed) => parsed,
889        Err(error) => return DispatchOutcome::UserError(error),
890    };
891    if !positional.is_empty() {
892        return DispatchOutcome::UserError("memory scopes: takes no arguments".into());
893    }
894    let path = match memory_read_store(&values) {
895        Ok(path) => path,
896        Err(outcome) => return outcome,
897    };
898    let answer = match rightkit_context_runtime::cli::memory_scopes_in_process(&path) {
899        Ok(answer) => answer,
900        Err(error) => return DispatchOutcome::InternalError(format!("memory scopes: {error}")),
901    };
902    if json {
903        let Value::Object(fields) = answer else {
904            return DispatchOutcome::InternalError(
905                "memory scopes: the answer is not an object".into(),
906            );
907        };
908        return print_document(SCHEMA_MEMORY_SCOPES, fields);
909    }
910    for entry in answer
911        .get("scopes")
912        .and_then(Value::as_array)
913        .into_iter()
914        .flatten()
915    {
916        println!(
917            "{} {}",
918            entry.get("count").and_then(Value::as_i64).unwrap_or(0),
919            str_field(entry, "scope")
920        );
921    }
922    DispatchOutcome::Ok
923}
924
925/// `membrane memory info [--limit <n>] [--json] [--db <path>]`: what the store holds, the recent
926/// recall activity, and the embedder the resident runs (`embedder.dim`, null while no resident
927/// answers).
928fn memory_info(flags: &[String]) -> DispatchOutcome {
929    let (positional, json, values) = match memory_flags("info", flags, &["--db", "--limit"]) {
930        Ok(parsed) => parsed,
931        Err(error) => return DispatchOutcome::UserError(error),
932    };
933    if !positional.is_empty() {
934        return DispatchOutcome::UserError("memory info: takes no arguments".into());
935    }
936    let limit = match flag_value(&values, "--limit").map(str::parse::<usize>) {
937        None => 20,
938        Some(Ok(parsed)) if (1..=1_000).contains(&parsed) => parsed,
939        Some(_) => {
940            return DispatchOutcome::UserError("memory info: --limit must be 1 to 1000".into());
941        }
942    };
943    let path = match memory_read_store(&values) {
944        Ok(path) => path,
945        Err(outcome) => return outcome,
946    };
947    let answer = match rightkit_context_runtime::cli::memory_info_in_process(&path, limit) {
948        Ok(answer) => answer,
949        Err(error) => return DispatchOutcome::InternalError(format!("memory info: {error}")),
950    };
951    let Value::Object(mut fields) = answer else {
952        return DispatchOutcome::InternalError("memory info: the answer is not an object".into());
953    };
954    // The live embedder belongs to the resident; a named store is not the resident's.
955    let resident = if flag_value(&values, "--db").is_none() {
956        ask(ResidentOp::Status, json!({}), STATUS_DEADLINE)
957    } else {
958        Resident::Absent
959    };
960    let embedder = match resident {
961        Resident::Answered(status) => json!({
962            "source": "resident",
963            "dim": status.get("embedderDim").cloned().unwrap_or(Value::Null),
964            "model": status.get("model").cloned().unwrap_or(Value::Null),
965        }),
966        _ => json!({"source": "unavailable", "dim": null, "model": null}),
967    };
968    fields.insert("embedder".into(), embedder);
969    if json {
970        return print_document(SCHEMA_MEMORY_INFO, fields);
971    }
972    let info = Value::Object(fields);
973    println!(
974        "memories: {} in {} scope(s)",
975        info.get("total").and_then(Value::as_i64).unwrap_or(0),
976        info.get("scopeCount").and_then(Value::as_u64).unwrap_or(0)
977    );
978    println!(
979        "embedder dim: {}",
980        info.pointer("/embedder/dim")
981            .filter(|dim| !dim.is_null())
982            .map_or_else(|| "unknown (no resident)".to_owned(), Value::to_string)
983    );
984    DispatchOutcome::Ok
985}
986
987/// The Cortex store a memory command reads: `--db`, else the one Cortex store path (the state root's store; debug builds also honor `CORTEX_DB`).
988fn memory_db_path(flag: Option<&Path>) -> PathBuf {
989    flag.map(Path::to_path_buf)
990        .unwrap_or_else(rightkit_context_runtime::cli::cortex_db_path)
991}
992
993fn no_store_message(path: &Path) -> String {
994    format!(
995        "no memory store at {} (it is created by the first `memory push`)",
996        path.display()
997    )
998}
999
1000/// The memory scope of the repository named by `--repo` or `--cwd`: the path slug of its root,
1001/// which is the scope a context pull for that root reads. `None` when neither is given.
1002fn repository_scope(repo: Option<&Path>, cwd: Option<&Path>) -> Option<String> {
1003    let path = repo.or(cwd)?;
1004    let root = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
1005    Some(rightkit_context_runtime::path_to_scope(
1006        &root.to_string_lossy(),
1007    ))
1008}
1009
1010fn str_field<'a>(item: &'a Value, key: &str) -> &'a str {
1011    item.get(key).and_then(Value::as_str).unwrap_or("")
1012}
1013
1014fn tier_name(tier: TierArg) -> &'static str {
1015    match tier {
1016        TierArg::Working => "working",
1017        TierArg::Episodic => "episodic",
1018        TierArg::Semantic => "semantic",
1019    }
1020}
1021
1022/// `membrane memory search <query> [--tier T…] [--limit N] [--cwd|--repo] [--json]`. The resident
1023/// answers when one runs, else the store is read in process with the lexical arm, so the model is
1024/// never loaded.
1025pub fn memory_search(args: &SearchArgs) -> DispatchOutcome {
1026    if args.query.trim().is_empty() {
1027        return DispatchOutcome::UserError("memory search: the query is empty".into());
1028    }
1029    if args.limit == 0 || args.limit > MEMORY_SEARCH_MAX_LIMIT {
1030        return DispatchOutcome::UserError(format!(
1031            "memory search: --limit must be 1 to {MEMORY_SEARCH_MAX_LIMIT}"
1032        ));
1033    }
1034    let request = json!({
1035        "query": args.query,
1036        "tiers": args.tiers.iter().map(|tier| tier_name(*tier)).collect::<Vec<_>>(),
1037        "scope": repository_scope(args.repo.as_deref(), args.cwd.as_deref()),
1038        "scopes": args.scopes,
1039        "limit": args.limit,
1040    });
1041    // A named store is not the resident's, so only the default store asks the resident.
1042    let resident = if args.db.is_none() {
1043        ask(ResidentOp::MemorySearch, request.clone(), SEARCH_DEADLINE)
1044    } else {
1045        Resident::Absent
1046    };
1047    let answer = match resident {
1048        // A resident started before scope chains ignores `scopes` and would search every scope;
1049        // its answer lacks the `scopes` echo, so it is not used.
1050        Resident::Answered(data) if args.scopes.is_empty() || data.get("scopes").is_some() => data,
1051        // A read has no side effect, so a resident that failed is simply asked again in process.
1052        Resident::Answered(_) | Resident::Absent | Resident::Failed(_) => {
1053            let path = memory_db_path(args.db.as_deref());
1054            if !path.is_file() {
1055                return DispatchOutcome::NotAvailable(no_store_message(&path));
1056            }
1057            match rightkit_context_runtime::cli::search_memory_in_process(&path, &request) {
1058                Ok(answer) => answer,
1059                Err(error) => {
1060                    return DispatchOutcome::InternalError(format!("memory search: {error}"));
1061                }
1062            }
1063        }
1064    };
1065    let Value::Object(fields) = answer else {
1066        return DispatchOutcome::InternalError("memory search: the answer is not an object".into());
1067    };
1068    if args.json {
1069        return print_document(SCHEMA_MEMORY_SEARCH, fields);
1070    }
1071    let more = fields.get("more").and_then(Value::as_bool).unwrap_or(false);
1072    for item in fields
1073        .get("items")
1074        .and_then(Value::as_array)
1075        .into_iter()
1076        .flatten()
1077    {
1078        println!(
1079            "{} {} {}",
1080            str_field(item, "id"),
1081            str_field(item, "tier"),
1082            str_field(item, "scope")
1083        );
1084        println!("{}", str_field(item, "content"));
1085        println!();
1086    }
1087    if more {
1088        eprintln!(
1089            "membrane: more memories match; raise --limit (at most {MEMORY_SEARCH_MAX_LIMIT})"
1090        );
1091    }
1092    DispatchOutcome::Ok
1093}
1094
1095/// `membrane memory delete <id> [--json]`. The resident deletes when one runs, so the store is
1096/// never written under it. A missing id is exit 3, with the document saying `deleted: false`.
1097pub fn memory_delete(args: &DeleteArgs) -> DispatchOutcome {
1098    if args.id.trim().is_empty() {
1099        return DispatchOutcome::UserError("memory delete: the id is empty".into());
1100    }
1101    let request = json!({"id": args.id});
1102    let resident = if args.db.is_none() {
1103        ask(ResidentOp::MemoryDelete, request.clone(), DELETE_DEADLINE)
1104    } else {
1105        Resident::Absent
1106    };
1107    let answer = match resident {
1108        Resident::Answered(data) => data,
1109        // A write the resident may have run is never replayed here, as with `memory push`.
1110        Resident::Failed(error) => {
1111            return DispatchOutcome::InternalError(format!(
1112                "memory delete {}: the resident failed ({error}), so the memory may still exist; check with `membrane memory search`",
1113                args.id
1114            ));
1115        }
1116        Resident::Absent => {
1117            let path = memory_db_path(args.db.as_deref());
1118            if !path.is_file() {
1119                return DispatchOutcome::NotAvailable(no_store_message(&path));
1120            }
1121            match rightkit_context_runtime::cli::delete_memory_in_process(&path, &request) {
1122                Ok(answer) => answer,
1123                Err(error) if error.starts_with("membrane is serving") => {
1124                    return DispatchOutcome::NotAvailable(error);
1125                }
1126                Err(error) => {
1127                    return DispatchOutcome::InternalError(format!("memory delete: {error}"));
1128                }
1129            }
1130        }
1131    };
1132    let deleted = answer
1133        .get("deleted")
1134        .and_then(Value::as_bool)
1135        .unwrap_or(false);
1136    if args.json {
1137        let Value::Object(fields) = answer else {
1138            return DispatchOutcome::InternalError(
1139                "memory delete: the answer is not an object".into(),
1140            );
1141        };
1142        if let DispatchOutcome::InternalError(error) = print_document(SCHEMA_MEMORY_DELETE, fields)
1143        {
1144            return DispatchOutcome::InternalError(error);
1145        }
1146    } else if deleted {
1147        println!("deleted {}", args.id);
1148    }
1149    if deleted {
1150        DispatchOutcome::Ok
1151    } else {
1152        eprintln!("membrane: no memory has id {}", args.id);
1153        DispatchOutcome::Exit(crate::EXIT_NOT_AVAILABLE)
1154    }
1155}
1156
1157/// Deadline for an Adapt or transcript answer: a mine or an admission can take a while.
1158const ADAPT_DEADLINE: Duration = Duration::from_secs(30);
1159/// The bound on a JSON document an Adapt or transcript command reads, the same as the route's.
1160const MAX_ADAPT_BYTES: usize = 1024 * 1024;
1161
1162/// An absolute path. The resident runs in another working directory, so a path it must read is
1163/// made absolute here first.
1164fn absolute_path(path: &Path) -> Result<PathBuf, String> {
1165    if path.is_absolute() {
1166        return Ok(path.to_path_buf());
1167    }
1168    Ok(current_dir()?.join(path))
1169}
1170
1171/// The text of a JSON document named by `--stdin` or `--input`, which is exactly one of the two.
1172fn read_document(stdin: bool, input: Option<&Path>) -> Result<String, String> {
1173    let mut bytes = Vec::new();
1174    match (stdin, input) {
1175        (true, None) => {
1176            io::stdin()
1177                .take((MAX_ADAPT_BYTES + 1) as u64)
1178                .read_to_end(&mut bytes)
1179                .map_err(|error| format!("read stdin: {error}"))?;
1180        }
1181        (false, Some(path)) => {
1182            let file = std::fs::File::open(path)
1183                .map_err(|error| format!("open {}: {error}", path.display()))?;
1184            file.take((MAX_ADAPT_BYTES + 1) as u64)
1185                .read_to_end(&mut bytes)
1186                .map_err(|error| format!("read {}: {error}", path.display()))?;
1187        }
1188        _ => return Err("give exactly one of --stdin or --input".into()),
1189    }
1190    if bytes.len() > MAX_ADAPT_BYTES {
1191        return Err("document exceeds 1 MiB".into());
1192    }
1193    String::from_utf8(bytes).map_err(|_| "document is not UTF-8 text".to_owned())
1194}
1195
1196/// A route body that was text as a JSON value; text that is not JSON stays a string.
1197fn body_value(text: String) -> Value {
1198    match serde_json::from_str::<Value>(&text) {
1199        Ok(value) => value,
1200        Err(_) => Value::String(text),
1201    }
1202}
1203
1204/// The resident's `{status, body}` answer as a status and a body.
1205fn envelope(data: Value) -> Result<(u16, Value), String> {
1206    let status = data
1207        .get("status")
1208        .and_then(Value::as_u64)
1209        .ok_or_else(|| "the resident's answer has no status".to_owned())?;
1210    let status =
1211        u16::try_from(status).map_err(|_| "the resident's status is out of range".to_owned())?;
1212    Ok((status, data.get("body").cloned().unwrap_or(Value::Null)))
1213}
1214
1215/// Answer one Adapt or transcript body. The resident answers when one runs and the db is the
1216/// default. Otherwise the store is opened here: a read lexically, a write under the owner lock. A
1217/// write the resident was reached for is never replayed here, as with `memory push`.
1218fn adapt_answer(
1219    op: ResidentOp,
1220    body: Value,
1221    write: bool,
1222    db: Option<&Path>,
1223) -> Result<(u16, Value), DispatchOutcome> {
1224    let resident = if db.is_none() {
1225        ask(op, body.clone(), ADAPT_DEADLINE)
1226    } else {
1227        Resident::Absent
1228    };
1229    match resident {
1230        Resident::Answered(data) => {
1231            return envelope(data).map_err(DispatchOutcome::InternalError);
1232        }
1233        Resident::Failed(error) if write => {
1234            return Err(DispatchOutcome::InternalError(format!(
1235                "the resident failed ({error}); the write may have run, so it is not repeated here"
1236            )));
1237        }
1238        Resident::Failed(_) | Resident::Absent => {}
1239    }
1240    let path = memory_db_path(db);
1241    if !path.is_file() {
1242        return Err(DispatchOutcome::NotAvailable(no_store_message(&path)));
1243    }
1244    let text = body.to_string();
1245    let answered = match op {
1246        ResidentOp::AdaptObservation => {
1247            rightkit_context_runtime::cli::adapt_observation_in_process(&path, write, &text)
1248        }
1249        ResidentOp::TranscriptTip => {
1250            rightkit_context_runtime::cli::transcript_tip_in_process(&path, &text)
1251        }
1252        _ => rightkit_context_runtime::cli::adapt_operator_in_process(&path, write, &text),
1253    };
1254    match answered {
1255        Ok((status, text)) => Ok((status, body_value(text))),
1256        Err(error) if error.starts_with("membrane is serving") => {
1257            Err(DispatchOutcome::NotAvailable(error))
1258        }
1259        Err(error) => Err(DispatchOutcome::InternalError(error)),
1260    }
1261}
1262
1263/// Print an Adapt answer: the `result` under the verb's schema with `--json`, else the result
1264/// alone. A refusal (any status but 200) is exit 2 with its reason on stderr.
1265fn adapt_outcome(
1266    schema: &str,
1267    status: u16,
1268    result: Value,
1269    json: bool,
1270    verb: &str,
1271) -> DispatchOutcome {
1272    if status == 200 {
1273        if !json {
1274            return match print_json(&result) {
1275                Ok(()) => DispatchOutcome::Ok,
1276                Err(error) => DispatchOutcome::InternalError(error),
1277            };
1278        }
1279        let mut fields = Map::new();
1280        fields.insert("result".into(), result);
1281        return print_document(schema, fields);
1282    }
1283    let detail = result
1284        .get("detail")
1285        .or_else(|| result.get("error"))
1286        .and_then(Value::as_str)
1287        .map(str::to_owned)
1288        .unwrap_or_else(|| format!("refused with status {status}"));
1289    DispatchOutcome::UserError(format!("{verb}: {detail}"))
1290}
1291
1292/// `membrane adapt observe --stdin|--input <file> [--json]`: one observation document. The
1293/// transcript and observation routes answer it; it is a write.
1294pub fn adapt_observe(args: &AdaptObserveArgs) -> DispatchOutcome {
1295    let text = match read_document(args.stdin, args.input.as_deref()) {
1296        Ok(text) => text,
1297        Err(error) => return DispatchOutcome::UserError(format!("adapt observe: {error}")),
1298    };
1299    let body = match serde_json::from_str::<Value>(&text) {
1300        Ok(body) => body,
1301        Err(error) => {
1302            return DispatchOutcome::UserError(format!("adapt observe: not JSON: {error}"));
1303        }
1304    };
1305    match adapt_answer(ResidentOp::AdaptObservation, body, true, args.db.as_deref()) {
1306        Ok((status, result)) => adapt_outcome(
1307            SCHEMA_ADAPT_OBSERVE,
1308            status,
1309            result,
1310            args.json,
1311            "adapt observe",
1312        ),
1313        Err(outcome) => outcome,
1314    }
1315}
1316
1317/// `membrane adapt recall <query> [-k n] [--scope s] [--dimension K=V]… [--json]`: the Taste
1318/// records that apply. A read.
1319pub fn adapt_recall(args: &AdaptRecallArgs) -> DispatchOutcome {
1320    if args.query.trim().is_empty() {
1321        return DispatchOutcome::UserError("adapt recall: the query is empty".into());
1322    }
1323    let body = json!({
1324        "command": "recall",
1325        "query": args.query,
1326        "k": args.k,
1327        "scope": args.scope,
1328        "dimensions": args.dimensions,
1329    });
1330    match adapt_answer(ResidentOp::AdaptOperator, body, false, args.db.as_deref()) {
1331        Ok((status, result)) => adapt_outcome(
1332            SCHEMA_ADAPT_RECALL,
1333            status,
1334            result,
1335            args.json,
1336            "adapt recall",
1337        ),
1338        Err(outcome) => outcome,
1339    }
1340}
1341
1342/// `membrane adapt apply (--manifest <file> | --insights <file> --installation-id <id>)
1343/// [--dry-run] [--json]`: admit a reviewed manifest, or sealed Insight issues. A write.
1344pub fn adapt_apply(args: &AdaptApplyArgs) -> DispatchOutcome {
1345    let body = match (&args.manifest, &args.insights) {
1346        (Some(manifest), None) => {
1347            let manifest = match absolute_path(manifest) {
1348                Ok(path) => path,
1349                Err(error) => return DispatchOutcome::UserError(format!("adapt apply: {error}")),
1350            };
1351            json!({"command": "apply", "manifest": manifest, "dry_run": args.dry_run})
1352        }
1353        (None, Some(insights)) => {
1354            let Some(installation_id) = args.installation_id.as_deref() else {
1355                return DispatchOutcome::UserError(
1356                    "adapt apply: --insights needs --installation-id".into(),
1357                );
1358            };
1359            let input = match absolute_path(insights) {
1360                Ok(path) => path,
1361                Err(error) => return DispatchOutcome::UserError(format!("adapt apply: {error}")),
1362            };
1363            json!({
1364                "command": "apply_insights",
1365                "input": input,
1366                "installation_id": installation_id,
1367                "dry_run": args.dry_run,
1368            })
1369        }
1370        _ => {
1371            return DispatchOutcome::UserError(
1372                "adapt apply: give exactly one of --manifest or --insights".into(),
1373            );
1374        }
1375    };
1376    match adapt_answer(ResidentOp::AdaptOperator, body, true, args.db.as_deref()) {
1377        Ok((status, result)) => {
1378            adapt_outcome(SCHEMA_ADAPT_APPLY, status, result, args.json, "adapt apply")
1379        }
1380        Err(outcome) => outcome,
1381    }
1382}
1383
1384/// `membrane adapt taste-review --input <file> --installation-id <id> --created-at <t> [--json]`:
1385/// build a pending Taste manifest from native mine output. It opens the store for reading in
1386/// full, so it runs under the owner lock when no resident answers.
1387pub fn adapt_taste_review(args: &AdaptTasteReviewArgs) -> DispatchOutcome {
1388    let input = match absolute_path(&args.input) {
1389        Ok(path) => path,
1390        Err(error) => return DispatchOutcome::UserError(format!("adapt taste-review: {error}")),
1391    };
1392    let body = json!({
1393        "command": "review_taste",
1394        "input": input,
1395        "installation_id": args.installation_id,
1396        "canonical_pool_sha256": args.canonical_pool_sha256,
1397        "created_at": args.created_at,
1398    });
1399    match adapt_answer(ResidentOp::AdaptOperator, body, true, args.db.as_deref()) {
1400        Ok((status, result)) => adapt_outcome(
1401            SCHEMA_ADAPT_TASTE_REVIEW,
1402            status,
1403            result,
1404            args.json,
1405            "adapt taste-review",
1406        ),
1407        Err(outcome) => outcome,
1408    }
1409}
1410
1411/// `membrane adapt status [--scope s] [--json]`: live Adapt progress for a scope. A read.
1412pub fn adapt_status(args: &AdaptStatusArgs) -> DispatchOutcome {
1413    if args.scope.trim().is_empty() {
1414        return DispatchOutcome::UserError("adapt status: --scope is empty".into());
1415    }
1416    let body = json!({"command": "status", "scope": args.scope});
1417    match adapt_answer(ResidentOp::AdaptOperator, body, false, args.db.as_deref()) {
1418        Ok((status, result)) => adapt_outcome(
1419            SCHEMA_ADAPT_STATUS,
1420            status,
1421            result,
1422            args.json,
1423            "adapt status",
1424        ),
1425        Err(outcome) => outcome,
1426    }
1427}
1428
1429/// `membrane adapt adjudicate-taste --manifest <file> --decisions <file> --validated-at <t>
1430/// [--json]`: bind semantic decisions to a pending Taste manifest and print the adjudicated
1431/// manifest. It reads the two files and writes nothing; `adapt apply` admits the result.
1432pub fn adapt_adjudicate_taste(args: &AdaptAdjudicateTasteArgs) -> DispatchOutcome {
1433    let manifest = match absolute_path(&args.manifest) {
1434        Ok(path) => path,
1435        Err(error) => {
1436            return DispatchOutcome::UserError(format!("adapt adjudicate-taste: {error}"));
1437        }
1438    };
1439    let decisions = match absolute_path(&args.decisions) {
1440        Ok(path) => path,
1441        Err(error) => {
1442            return DispatchOutcome::UserError(format!("adapt adjudicate-taste: {error}"));
1443        }
1444    };
1445    let body = json!({
1446        "command": "adjudicate_taste",
1447        "manifest": manifest,
1448        "decisions": decisions,
1449        "validated_at": args.validated_at,
1450    });
1451    match adapt_answer(ResidentOp::AdaptOperator, body, false, args.db.as_deref()) {
1452        Ok((status, result)) => adapt_outcome(
1453            SCHEMA_ADAPT_ADJUDICATE_TASTE,
1454            status,
1455            result,
1456            args.json,
1457            "adapt adjudicate-taste",
1458        ),
1459        Err(outcome) => outcome,
1460    }
1461}
1462
1463/// `membrane adapt mine-session --session <id>... [--scope s] [--min-recurrence n] [--json]`:
1464/// mine the committed events of the named sessions (`transcript append` rows) for Taste and
1465/// Insight evidence. Report only: nothing is admitted. A read.
1466pub fn adapt_mine_session(args: &AdaptMineSessionArgs) -> DispatchOutcome {
1467    if args.session_ids.iter().any(|id| id.trim().is_empty()) {
1468        return DispatchOutcome::UserError("adapt mine-session: a --session is empty".into());
1469    }
1470    let body = json!({
1471        "command": "mine_session",
1472        "session_ids": args.session_ids,
1473        "scope": args.scope,
1474        "min_recurrence": args.min_recurrence,
1475    });
1476    match adapt_answer(ResidentOp::AdaptOperator, body, false, args.db.as_deref()) {
1477        Ok((status, result)) => adapt_outcome(
1478            SCHEMA_ADAPT_MINE_SESSION,
1479            status,
1480            result,
1481            args.json,
1482            "adapt mine-session",
1483        ),
1484        Err(outcome) => outcome,
1485    }
1486}
1487
1488/// The stream's committed end, from the tip op. `None` when the tip cannot be read.
1489fn transcript_end(session: &str, db: Option<&Path>) -> Option<u64> {
1490    let body = json!({"session_id": session});
1491    match adapt_answer(ResidentOp::TranscriptTip, body, false, db) {
1492        Ok((200, answer)) => answer
1493            .get("sessionTranscriptTip")
1494            .and_then(|tip| tip.get("lastSeq"))
1495            .and_then(Value::as_u64),
1496        _ => None,
1497    }
1498}
1499
1500/// A refused transcript append: exit 2, with the conflict receipt on stdout under `--json` (else
1501/// one line on stderr). `current_cursor` is the stream's committed end from the tip op, or null
1502/// when it could not be read.
1503fn transcript_refused(
1504    args: &TranscriptAppendArgs,
1505    status: u16,
1506    code: &str,
1507    current: Option<u64>,
1508    detail: Value,
1509) -> DispatchOutcome {
1510    let current_text = current.map_or_else(|| "unknown".to_owned(), |end| end.to_string());
1511    let mut fields = Map::new();
1512    fields.insert("session".into(), Value::String(args.session.clone()));
1513    fields.insert("cursor".into(), json!(args.cursor));
1514    fields.insert("conflict".into(), Value::Bool(true));
1515    fields.insert("replayed".into(), Value::Bool(false));
1516    fields.insert("status".into(), json!(status));
1517    fields.insert("code".into(), Value::String(code.to_owned()));
1518    fields.insert("current_cursor".into(), json!(current));
1519    fields.insert("detail".into(), detail);
1520    if args.json {
1521        if let DispatchOutcome::InternalError(error) =
1522            print_document(SCHEMA_TRANSCRIPT_APPEND, fields)
1523        {
1524            return DispatchOutcome::InternalError(error);
1525        }
1526    }
1527    eprintln!(
1528        "membrane: transcript append refused ({code}); cursor {} is not the end; current cursor {current_text}",
1529        args.cursor
1530    );
1531    DispatchOutcome::Exit(crate::EXIT_USER_ERROR)
1532}
1533
1534/// `membrane transcript append --session <id> --cursor <n> (--stdin | --text <json>) [--scope s]
1535/// [--json]`. The events are a JSON array of `SessionTranscriptEventV1` rows that extend the
1536/// stream at `--cursor`.
1537///
1538/// The tip op is read first. Outcomes:
1539/// - `--cursor` is the current end: the batch is appended. Success is `{conflict: false,
1540///   replayed: false, receipt}`.
1541/// - `--cursor` is behind the end and the batch lies wholly within the stream: the rows can
1542///   only be exact replays, so the store is asked, which writes nothing. Identical rows are
1543///   success with `{conflict: false, replayed: true}`. Different rows are a conflict.
1544/// - Otherwise (ahead of the end, or the batch would reach past it): refused with
1545///   `{conflict: true, current_cursor}`, without any write. Exit 2.
1546///
1547/// A 409 from the store is also a conflict, with `current_cursor` read from the tip op again.
1548pub fn transcript_append(args: &TranscriptAppendArgs) -> DispatchOutcome {
1549    if args.session.trim().is_empty() {
1550        return DispatchOutcome::UserError("transcript append: --session is empty".into());
1551    }
1552    let text = match &args.text {
1553        Some(text) => text.clone(),
1554        None => match read_document(args.stdin, None) {
1555            Ok(text) => text,
1556            Err(error) => {
1557                return DispatchOutcome::UserError(format!("transcript append: {error}"));
1558            }
1559        },
1560    };
1561    let events: Vec<SessionTranscriptEventV1> = match serde_json::from_str(&text) {
1562        Ok(events) => events,
1563        Err(error) => {
1564            return DispatchOutcome::UserError(format!(
1565                "transcript append: the events are not a JSON array of rows: {error}"
1566            ));
1567        }
1568    };
1569    let batch = events.len() as u64;
1570    let append = SessionTranscriptAppendV1 {
1571        schema_version: SESSION_TRANSCRIPT_SCHEMA_VERSION,
1572        session_id: args.session.clone(),
1573        scope_id: args.scope.clone(),
1574        expected_stream_seq: args.cursor,
1575        events,
1576    };
1577    // The runtime's own contract for the batch: non-empty scope and session ids, at most 512
1578    // bytes each, and sequence positions that follow the cursor.
1579    if let Err(error) = append.validate() {
1580        return DispatchOutcome::UserError(format!("transcript append: {error}"));
1581    }
1582    let db = args.db.as_deref();
1583    let end = match transcript_end(&args.session, db) {
1584        Some(end) => end,
1585        None => {
1586            return transcript_refused(args, 409, "transcript_tip_unavailable", None, Value::Null);
1587        }
1588    };
1589    let behind_within = args
1590        .cursor
1591        .checked_add(batch)
1592        .is_some_and(|last| args.cursor < end && last <= end);
1593    if args.cursor != end && !behind_within {
1594        return transcript_refused(
1595            args,
1596            409,
1597            "transcript_cursor_mismatch",
1598            Some(end),
1599            json!({"reason": "cursor is not the stream's current end"}),
1600        );
1601    }
1602    let body = json!({"operation": "session_transcript", "append": append});
1603    let (status, result) = match adapt_answer(ResidentOp::AdaptObservation, body, true, db) {
1604        Ok(answer) => answer,
1605        Err(outcome) => return outcome,
1606    };
1607    if status != 200 {
1608        let code = result
1609            .get("code")
1610            .or_else(|| result.get("error"))
1611            .and_then(Value::as_str)
1612            .unwrap_or("refused")
1613            .to_owned();
1614        return transcript_refused(
1615            args,
1616            status,
1617            &code,
1618            transcript_end(&args.session, db),
1619            result,
1620        );
1621    }
1622    let receipt = result
1623        .get("sessionTranscript")
1624        .cloned()
1625        .unwrap_or(Value::Null);
1626    let inserted = receipt.get("inserted").and_then(Value::as_u64).unwrap_or(0);
1627    let already = receipt
1628        .get("alreadyPresent")
1629        .and_then(Value::as_u64)
1630        .unwrap_or(0);
1631    let replayed = inserted == 0 && already > 0;
1632    if !args.json {
1633        let last_seq = receipt.get("lastSeq").cloned().unwrap_or(Value::Null);
1634        let verb = if replayed { "replayed" } else { "appended" };
1635        println!("{} {verb} {last_seq}", args.session);
1636        return DispatchOutcome::Ok;
1637    }
1638    let mut fields = Map::new();
1639    fields.insert("session".into(), Value::String(args.session.clone()));
1640    fields.insert("cursor".into(), json!(args.cursor));
1641    fields.insert("conflict".into(), Value::Bool(false));
1642    fields.insert("replayed".into(), Value::Bool(replayed));
1643    fields.insert("receipt".into(), receipt);
1644    print_document(SCHEMA_TRANSCRIPT_APPEND, fields)
1645}
1646
1647/// `membrane transcript tip --session <id> [--json]`: the committed end of the session's stream.
1648/// A read. A forgotten session is exit 2.
1649pub fn transcript_tip(args: &TranscriptTipArgs) -> DispatchOutcome {
1650    if args.session.trim().is_empty() {
1651        return DispatchOutcome::UserError("transcript tip: --session is empty".into());
1652    }
1653    let body = json!({"session_id": args.session});
1654    let (status, result) =
1655        match adapt_answer(ResidentOp::TranscriptTip, body, false, args.db.as_deref()) {
1656            Ok(answer) => answer,
1657            Err(outcome) => return outcome,
1658        };
1659    if status != 200 {
1660        return adapt_outcome(
1661            SCHEMA_TRANSCRIPT_TIP,
1662            status,
1663            result,
1664            args.json,
1665            "transcript tip",
1666        );
1667    }
1668    let tip = result
1669        .get("sessionTranscriptTip")
1670        .cloned()
1671        .unwrap_or(Value::Null);
1672    let current = tip.get("lastSeq").cloned().unwrap_or(Value::Null);
1673    if !args.json {
1674        println!("{current}");
1675        return DispatchOutcome::Ok;
1676    }
1677    let mut fields = Map::new();
1678    fields.insert("session".into(), Value::String(args.session.clone()));
1679    fields.insert("current_cursor".into(), current);
1680    fields.insert(
1681        "prefix_digest".into(),
1682        tip.get("prefixDigest").cloned().unwrap_or(Value::Null),
1683    );
1684    print_document(SCHEMA_TRANSCRIPT_TIP, fields)
1685}
1686
1687/// `membrane receipts mark <id> --delivered [--json]`: an `emitted` receipt with this id becomes
1688/// `delivered`. Any other state stays. Exit 3 when no receipt has the id.
1689pub fn receipts_mark(args: &MarkArgs) -> DispatchOutcome {
1690    if !receipt::valid_receipt_id(&args.id) {
1691        return DispatchOutcome::UserError(
1692            "receipts mark: the id takes 1 to 128 letters, digits, '-' or '_'".into(),
1693        );
1694    }
1695    let found =
1696        match receipt::mark_delivered(&rightkit_context_runtime::cli::state_root(), &args.id) {
1697            Ok(found) => found,
1698            Err(error) => {
1699                return DispatchOutcome::InternalError(format!(
1700                    "receipts mark {}: {error}",
1701                    args.id
1702                ));
1703            }
1704        };
1705    if args.json {
1706        let receipts: Vec<Value> = found
1707            .iter()
1708            .map(|record| {
1709                json!({"session": record.session, "state": record.state.as_str(), "ts": record.ts})
1710            })
1711            .collect();
1712        let mut fields = Map::new();
1713        fields.insert("id".into(), Value::String(args.id.clone()));
1714        fields.insert("receipts".into(), Value::Array(receipts));
1715        if let DispatchOutcome::InternalError(error) = print_document(SCHEMA_RECEIPTS_MARK, fields)
1716        {
1717            return DispatchOutcome::InternalError(error);
1718        }
1719    } else {
1720        for record in &found {
1721            println!("{} {}", record.state.as_str(), record.session);
1722        }
1723    }
1724    if found.is_empty() {
1725        eprintln!("membrane: no receipt has id {}", args.id);
1726        return DispatchOutcome::Exit(crate::EXIT_NOT_AVAILABLE);
1727    }
1728    DispatchOutcome::Ok
1729}
1730
1731/// `membrane where [--json]`: the absolute path of the running binary, with its version, so a
1732/// caller holding a candidate path can confirm it is Membrane and which build it is. Read-only;
1733/// it never contacts the resident.
1734pub fn where_binary(args: &WhereArgs) -> DispatchOutcome {
1735    let binary = match std::env::current_exe() {
1736        Ok(path) => path.to_string_lossy().into_owned(),
1737        Err(error) => {
1738            return DispatchOutcome::NotAvailable(format!("resolve the membrane binary: {error}"));
1739        }
1740    };
1741    if !args.json {
1742        println!("{binary}");
1743        return DispatchOutcome::Ok;
1744    }
1745    let status = rightkit_context_runtime::cli::status_value();
1746    let mut fields = Map::new();
1747    fields.insert("binary".into(), binary.into());
1748    for key in [
1749        "product_version",
1750        "membrane_source_commit",
1751        "target",
1752        "stateRoot",
1753    ] {
1754        fields.insert(key.into(), status.get(key).cloned().unwrap_or(Value::Null));
1755    }
1756    print_document(SCHEMA_WHERE, fields)
1757}
1758
1759/// `membrane status [--json]`.
1760pub fn status(args: &StatusArgs) -> DispatchOutcome {
1761    let mut status = rightkit_context_runtime::cli::status_value();
1762    // The resident reports its own model state below; without one, say what this build ships.
1763    status["model"] = rightkit_context_runtime::store::MODEL_READINESS.status_json();
1764    status["schema"] = SCHEMA_STATUS.into();
1765    let mut resident_answered = false;
1766    if let Resident::Answered(answer) = ask(ResidentOp::Status, json!({}), STATUS_DEADLINE) {
1767        status["mode"] = "resident".into();
1768        status["resident"] = answer;
1769        resident_answered = true;
1770    }
1771    if args.json {
1772        if let Err(error) = print_json(&status) {
1773            return DispatchOutcome::InternalError(error);
1774        }
1775    } else {
1776        println!("{}", status_text(&status));
1777    }
1778    if args.require_resident && !resident_answered {
1779        eprintln!("membrane: the resident is not answering");
1780        return DispatchOutcome::Exit(crate::EXIT_RESIDENT_UNREACHABLE);
1781    }
1782    DispatchOutcome::Ok
1783}
1784
1785fn status_text(status: &Value) -> String {
1786    let text = |pointer: &str| {
1787        status
1788            .pointer(pointer)
1789            .and_then(Value::as_str)
1790            .unwrap_or("unknown")
1791            .to_owned()
1792    };
1793    let resident = match status.pointer("/resident/running").and_then(Value::as_bool) {
1794        Some(true) => format!(
1795            "running (pid {})",
1796            status
1797                .pointer("/resident/pid")
1798                .and_then(Value::as_u64)
1799                .unwrap_or_default()
1800        ),
1801        _ => text("/resident/state"),
1802    };
1803    let store = if status.pointer("/db/present").and_then(Value::as_bool) == Some(true) {
1804        "present"
1805    } else {
1806        "not created yet"
1807    };
1808    [
1809        format!("membrane {}", text("/product_version")),
1810        format!("mode: {}", text("/mode")),
1811        format!("resident: {resident}"),
1812        format!("model: {}", text("/model")),
1813        format!("store: {store}"),
1814        format!("state root: {}", text("/stateRoot")),
1815    ]
1816    .join("\n")
1817}
1818
1819/// `membrane hook`: always exits 0. Context events try the resident first; every event runs in
1820/// process otherwise. Only the reply the host's schema accepts goes to stdout.
1821pub fn hook_event(args: &HookArgs) -> DispatchOutcome {
1822    let wire = match args.wire {
1823        WireArg::Claude => Wire::Claude,
1824        WireArg::Codex => Wire::Codex,
1825    };
1826    let event = args.event.as_str();
1827    let payload = read_hook_payload();
1828    let mut resident_absent = false;
1829    if hook::emits_context(event) {
1830        let request = json!({"wire": wire.as_str(), "event": event, "payload": payload});
1831        match ask(ResidentOp::Hook, request, HOOK_DEADLINE) {
1832            Resident::Answered(data) => {
1833                if let Some(output) = data.get("output").filter(|output| !output.is_null()) {
1834                    println!("{output}");
1835                }
1836                let state = data
1837                    .get("state")
1838                    .and_then(Value::as_str)
1839                    .unwrap_or("unknown");
1840                let reason = data.get("reason").and_then(Value::as_str).unwrap_or("");
1841                report_hook(event, state, reason);
1842                return DispatchOutcome::Ok;
1843            }
1844            Resident::Absent => resident_absent = true,
1845            Resident::Failed(_) => {}
1846        }
1847    }
1848    let outcome = hook::run(wire, event, payload);
1849    if let Some(output) = &outcome.output {
1850        println!("{output}");
1851    }
1852    // Without the host app the lexical stores answer alone. When they found nothing, the warm path
1853    // (semantic retrieval) is what was missing, and the receipt says so.
1854    let (state, reason) = match outcome.receipt.state {
1855        HookReceiptState::Empty if resident_absent => {
1856            (HookReceiptState::Off, "host not running".to_owned())
1857        }
1858        state => (state, outcome.receipt.reason.clone()),
1859    };
1860    report_hook(event, state.as_str(), &reason);
1861    DispatchOutcome::Ok
1862}
1863
1864/// One line on stderr when a run ended in anything but emitted or empty.
1865fn report_hook(event: &str, state: &str, reason: &str) {
1866    if !matches!(state, "emitted" | "empty") {
1867        eprintln!("membrane: hook {event}: {state} ({reason})");
1868    }
1869}
1870
1871/// `membrane receipts confirm`: flip this session's `emitted` receipts to `delivered` where the
1872/// host's transcript shows their marker. Prints nothing and always exits 0, because the host app's Stop
1873/// hook runs it; a transcript it cannot read leaves the receipts `emitted`.
1874pub fn receipts_confirm(args: &ConfirmArgs) -> DispatchOutcome {
1875    let wire = match args.wire {
1876        WireArg::Claude => Wire::Claude,
1877        WireArg::Codex => Wire::Codex,
1878    };
1879    receipt::confirm_delivered(
1880        &rightkit_context_runtime::cli::state_root(),
1881        &args.session,
1882        wire.as_str(),
1883        &args.transcript,
1884    );
1885    DispatchOutcome::Ok
1886}
1887
1888/// `membrane receipts list [--session <id>] [--json]`: the durable context receipts.
1889pub fn receipts_list(args: &ReceiptsListArgs) -> DispatchOutcome {
1890    let receipts = receipt::list_context_receipts(
1891        &rightkit_context_runtime::cli::state_root(),
1892        args.session.as_deref(),
1893    );
1894    if args.json {
1895        return match serde_json::to_value(&receipts)
1896            .map_err(|error| error.to_string())
1897            .and_then(|value| print_json(&value))
1898        {
1899            Ok(()) => DispatchOutcome::Ok,
1900            Err(error) => DispatchOutcome::InternalError(error),
1901        };
1902    }
1903    for receipt in &receipts {
1904        println!(
1905            "{} {} {} {} {} {}",
1906            receipt.state.as_str(),
1907            receipt.id,
1908            receipt.harness,
1909            receipt.event,
1910            receipt.session,
1911            receipt.ts
1912        );
1913    }
1914    DispatchOutcome::Ok
1915}
1916
1917/// The hook payload as JSON. Anything unreadable is an empty object, so the run still ends in a
1918/// receipt (refused) instead of an error.
1919fn read_hook_payload() -> Value {
1920    if io::stdin().is_terminal() {
1921        return json!({});
1922    }
1923    let (sender, receiver) = std::sync::mpsc::channel::<Vec<u8>>();
1924    let reader = std::thread::Builder::new()
1925        .name("membrane-hook-stdin".into())
1926        .spawn(move || {
1927            let mut stdin = io::stdin();
1928            loop {
1929                let mut chunk = vec![0u8; 8192];
1930                match stdin.read(&mut chunk) {
1931                    Ok(0) => {
1932                        let _ = sender.send(Vec::new());
1933                        break;
1934                    }
1935                    Ok(read) => {
1936                        chunk.truncate(read);
1937                        if sender.send(chunk).is_err() {
1938                            break;
1939                        }
1940                    }
1941                    Err(_) => break,
1942                }
1943            }
1944        });
1945    if reader.is_err() {
1946        return json!({});
1947    }
1948    let mut body = Vec::new();
1949    match receiver.recv_timeout(STDIN_FIRST_BYTES_GRACE) {
1950        Ok(chunk) => body.extend_from_slice(&chunk),
1951        Err(_) => return json!({}),
1952    }
1953    while body.len() <= MAX_HOOK_PAYLOAD_BYTES {
1954        match receiver.recv_timeout(STDIN_QUIET) {
1955            Ok(chunk) if chunk.is_empty() => break,
1956            Ok(chunk) => body.extend_from_slice(&chunk),
1957            Err(_) => break,
1958        }
1959    }
1960    serde_json::from_slice(&body).unwrap_or_else(|_| json!({}))
1961}
1962
1963/// `membrane serve`: the resident. The host app starts it with a stdin pipe it holds for the resident's life; `serve` reports itself and
1964/// returns the exit code ("already serving" is 0).
1965pub fn serve() -> DispatchOutcome {
1966    DispatchOutcome::Exit(crate::serve::run_serve())
1967}
1968
1969/// `membrane init <root> --repository <id> --scope <id>`: operator-owned registry enrollment.
1970pub fn init(args: &InitArgs) -> DispatchOutcome {
1971    let options = crate::native_init::InitOptions {
1972        root: args.root.clone(),
1973        repository_id: args.repository.clone(),
1974        scope_id: args.scope.clone(),
1975        rebind_from: args.rebind_from.clone(),
1976        virtual_id: args.virtual_id.clone(),
1977        tenant_id: args.tenant_id.clone(),
1978        parents: args.parent.clone(),
1979        native: args.native.clone(),
1980        config: args.config.clone(),
1981        dry_run: args.dry_run,
1982    };
1983    match crate::native_init::init(&options) {
1984        Ok(receipt) => match serde_json::to_string_pretty(&receipt) {
1985            Ok(json) => {
1986                println!("{json}");
1987                DispatchOutcome::Ok
1988            }
1989            Err(error) => DispatchOutcome::InternalError(format!(
1990                "init receipt serialization failed: {error}"
1991            )),
1992        },
1993        Err(error) => DispatchOutcome::UserError(format!("init: {error}")),
1994    }
1995}