Skip to main content

rightkit_context/
cli.rs

1//! Command line of the one `membrane` binary (C4).
2//!
3//! `host context|memory|blueprint ...` pass their arguments straight through to these
4//! commands, and agent hooks call `membrane hook`. Nothing here keeps a process running except
5//! `serve`, which the host app starts and owns.
6
7use clap::{Args, Parser, Subcommand, ValueEnum};
8use std::ffi::OsString;
9use std::path::PathBuf;
10
11#[derive(Debug, Parser)]
12#[command(
13    name = "membrane",
14    bin_name = "membrane",
15    about = "Membrane: context, memory and Blueprint queries for the host app.",
16    version,
17    disable_help_subcommand = true
18)]
19pub struct Cli {
20    #[command(subcommand)]
21    pub command: Command,
22}
23
24#[derive(Debug, Subcommand)]
25pub enum Command {
26    /// Context for an agent.
27    Context {
28        #[command(subcommand)]
29        command: ContextCommand,
30    },
31    /// Durable memory: `push`, `search`, `delete`, plus the maintenance commands.
32    Memory {
33        #[command(subcommand)]
34        command: MemoryCommand,
35    },
36    /// Search or erase the indexed ChatGPT and Codex history: `search <text>`, `status`, `erase`.
37    History(HistoryArgs),
38    /// Adapt: observe executions, recall Taste, apply reviewed manifests, and review Taste.
39    Adapt {
40        #[command(subcommand)]
41        command: AdaptCommand,
42    },
43    /// Append committed session events to a session's transcript, behind a cursor.
44    Transcript {
45        #[command(subcommand)]
46        command: TranscriptCommand,
47    },
48    /// Query the Blueprint graph of the current repository.
49    Blueprint(BlueprintArgs),
50    /// Report what Membrane is doing.
51    Status(StatusArgs),
52    /// Print the path of the running `membrane` binary, with its version (`membrane.where.v1`).
53    Where(WhereArgs),
54    /// Answer one agent hook event: payload on stdin, reply on stdout. Always exits 0.
55    Hook(HookArgs),
56    /// Delivery receipts for hook context: `confirm` (from the host app's Stop hook) and `list`.
57    Receipts {
58        #[command(subcommand)]
59        command: ReceiptsCommand,
60    },
61    /// Run the resident for the host app. Exits when the host app closes this process's stdin pipe.
62    Serve,
63    /// Enroll a repository in the registry that Blueprint and context pulls authorize against.
64    Init(InitArgs),
65}
66
67#[derive(Debug, Subcommand)]
68pub enum ContextCommand {
69    /// Print the context Membrane would give an agent starting this task.
70    Pull(PullArgs),
71}
72
73#[derive(Debug, Args)]
74pub struct PullArgs {
75    /// Repository to pull context for (default: the current directory).
76    #[arg(long)]
77    pub cwd: Option<PathBuf>,
78    /// The repository, by its root path. Resolved exactly as `--cwd` is. Both flags may be given
79    /// (CodeRight sends both) when they name the same path; different paths are exit 2.
80    #[arg(long, alias = "repo-root")]
81    pub repo: Option<PathBuf>,
82    /// The task or prompt the context is for.
83    #[arg(long)]
84    pub prompt: Option<String>,
85    /// Context budget in tokens.
86    #[arg(long)]
87    pub budget: Option<usize>,
88    /// Print one JSON document (`membrane.context.pull.v1`) instead of the bare context text.
89    #[arg(long)]
90    pub json: bool,
91    /// Record the returned context as a receipt for this harness, under `--request-id`.
92    #[arg(long, value_enum, requires = "request_id")]
93    pub wire: Option<PullWireArg>,
94    /// The caller's id for this context. `receipts mark <id> --delivered` names it later.
95    #[arg(long)]
96    pub request_id: Option<String>,
97}
98
99/// The harnesses that may record a receipt through `context pull --wire`. Their transcripts are
100/// their own; Membrane only keeps the receipt.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
102pub enum PullWireArg {
103    Coderight,
104}
105
106#[derive(Debug, Subcommand)]
107pub enum MemoryCommand {
108    /// Store text as a durable memory, optionally named, scoped, tiered and keyworded.
109    Push(PushArgs),
110    /// Search memories by text, within tiers and a scope chain or a repository's scope.
111    Search(SearchArgs),
112    /// Delete one memory by id.
113    Delete(DeleteArgs),
114    /// A durable-memory maintenance command (`list`, `get`, `recall`, `put`, `export`, ...),
115    /// run in process against the store: `membrane memory <command> [args...]`. `list --json`,
116    /// `get <id> --json`, `scopes` and `info` answer as versioned documents.
117    #[command(external_subcommand)]
118    Durable(Vec<String>),
119}
120
121#[derive(Debug, Args)]
122pub struct PushArgs {
123    /// The text to remember.
124    #[arg(required_unless_present = "stdin", conflicts_with = "stdin")]
125    pub text: Option<String>,
126    /// Read the text from standard input.
127    #[arg(long)]
128    pub stdin: bool,
129    /// Name the memory: its id becomes `<scope>/<name>`, so pushing the same name in the same
130    /// scope again replaces it. Without a name the id is generated.
131    #[arg(long)]
132    pub name: Option<String>,
133    /// The scope to store it under: a repository path, a scope slug, or `global` (the default).
134    #[arg(long)]
135    pub scope: Option<String>,
136    /// The tier to store it in (default `semantic`).
137    #[arg(long, value_enum)]
138    pub tier: Option<TierArg>,
139    /// A retrieval keyword. Repeat the flag for several. Without any, keywords are derived from
140    /// the text.
141    #[arg(long = "keyword")]
142    pub keywords: Vec<String>,
143    /// Print one JSON document (`membrane.memory.push.v1`) with the new id.
144    #[arg(long)]
145    pub json: bool,
146}
147
148#[derive(Debug, Subcommand)]
149pub enum AdaptCommand {
150    /// Record one observation: an `AdaptObservationRequestV1` JSON document (`membrane.adapt.observe.v1`).
151    Observe(AdaptObserveArgs),
152    /// Recall the active Taste records for a query (`membrane.adapt.recall.v1`).
153    Recall(AdaptRecallArgs),
154    /// Admit a reviewed manifest, or sealed Insight issues (`membrane.adapt.apply.v1`).
155    Apply(AdaptApplyArgs),
156    /// Build a pending Taste manifest from native mine output (`membrane.adapt.taste_review.v1`).
157    TasteReview(AdaptTasteReviewArgs),
158    /// Live Adapt progress for a scope (`membrane.adapt.status.v1`).
159    Status(AdaptStatusArgs),
160    /// Bind semantic decisions to a pending Taste manifest (`membrane.adapt.adjudicate_taste.v1`).
161    AdjudicateTaste(AdaptAdjudicateTasteArgs),
162    /// Mine committed session transcripts from the store, report only (`membrane.adapt.mine_session.v1`).
163    MineSession(AdaptMineSessionArgs),
164}
165
166#[derive(Debug, Args)]
167pub struct AdaptStatusArgs {
168    /// The scope whose Adapt progress is read.
169    #[arg(long, default_value = "global")]
170    pub scope: String,
171    /// The Cortex store (default: the store under the state root).
172    #[arg(long)]
173    pub db: Option<PathBuf>,
174    /// Print one JSON document (`membrane.adapt.status.v1`).
175    #[arg(long)]
176    pub json: bool,
177}
178
179#[derive(Debug, Args)]
180pub struct AdaptAdjudicateTasteArgs {
181    /// The pending manifest (`PreferenceManifestV1` JSON) from `adapt taste-review`.
182    #[arg(long)]
183    pub manifest: PathBuf,
184    /// The semantic decisions (`SemanticAdjudicationV1` JSON).
185    #[arg(long)]
186    pub decisions: PathBuf,
187    /// When the decisions were validated; must equal the decisions document's `validated_at`.
188    #[arg(long)]
189    pub validated_at: String,
190    /// The Cortex store (default: the store under the state root).
191    #[arg(long)]
192    pub db: Option<PathBuf>,
193    /// Print one JSON document (`membrane.adapt.adjudicate_taste.v1`).
194    #[arg(long)]
195    pub json: bool,
196}
197
198#[derive(Debug, Args)]
199pub struct AdaptMineSessionArgs {
200    /// The sessions whose committed events are mined. Repeat for several.
201    #[arg(long = "session", required = true)]
202    pub session_ids: Vec<String>,
203    /// The scope the findings are for.
204    #[arg(long, default_value = "workspace")]
205    pub scope: String,
206    /// How many times a pattern must recur to be reported.
207    #[arg(long, default_value_t = 2)]
208    pub min_recurrence: u32,
209    /// The Cortex store (default: the store under the state root).
210    #[arg(long)]
211    pub db: Option<PathBuf>,
212    /// Print one JSON document (`membrane.adapt.mine_session.v1`).
213    #[arg(long)]
214    pub json: bool,
215}
216
217#[derive(Debug, Args)]
218pub struct AdaptObserveArgs {
219    /// Read the observation document from standard input.
220    #[arg(long, conflicts_with = "input")]
221    pub stdin: bool,
222    /// Read the observation document from this file.
223    #[arg(long, conflicts_with = "stdin")]
224    pub input: Option<PathBuf>,
225    /// The Cortex store (default: the store under the state root).
226    #[arg(long)]
227    pub db: Option<PathBuf>,
228    /// Print one JSON document (`membrane.adapt.observe.v1`).
229    #[arg(long)]
230    pub json: bool,
231}
232
233#[derive(Debug, Args)]
234pub struct AdaptRecallArgs {
235    /// The text the Taste records must apply to.
236    pub query: String,
237    /// Most records to return.
238    #[arg(short = 'k', default_value_t = 6)]
239    pub k: usize,
240    /// The scope to recall from.
241    #[arg(long, default_value = "global")]
242    pub scope: String,
243    /// A scope dimension as KEY=VALUE. Repeat the flag for several.
244    #[arg(long = "dimension", value_name = "KEY=VALUE")]
245    pub dimensions: Vec<String>,
246    /// The Cortex store (default: the store under the state root).
247    #[arg(long)]
248    pub db: Option<PathBuf>,
249    /// Print one JSON document (`membrane.adapt.recall.v1`).
250    #[arg(long)]
251    pub json: bool,
252}
253
254#[derive(Debug, Args)]
255pub struct AdaptApplyArgs {
256    /// A reviewed preference manifest (`PreferenceManifestV1` JSON) to admit.
257    #[arg(long, conflicts_with = "insights")]
258    pub manifest: Option<PathBuf>,
259    /// Sealed Insight issues (a JSON array) to request admission for. Needs `--installation-id`.
260    #[arg(long, conflicts_with = "manifest")]
261    pub insights: Option<PathBuf>,
262    /// The installation the Insights are admitted under (with `--insights`).
263    #[arg(long)]
264    pub installation_id: Option<String>,
265    /// Validate and plan without writing.
266    #[arg(long)]
267    pub dry_run: bool,
268    /// The Cortex store (default: the store under the state root).
269    #[arg(long)]
270    pub db: Option<PathBuf>,
271    /// Print one JSON document (`membrane.adapt.apply.v1`).
272    #[arg(long)]
273    pub json: bool,
274}
275
276#[derive(Debug, Args)]
277pub struct AdaptTasteReviewArgs {
278    /// Native mine output with Taste source bindings (`{"taste_review": {...}}` JSON).
279    #[arg(long)]
280    pub input: PathBuf,
281    /// The installation the manifest is bound to.
282    #[arg(long)]
283    pub installation_id: String,
284    /// The canonical pool digest to bind; default is the current pool.
285    #[arg(long)]
286    pub canonical_pool_sha256: Option<String>,
287    /// When the manifest is created, as the caller records it.
288    #[arg(long)]
289    pub created_at: String,
290    /// The Cortex store (default: the store under the state root).
291    #[arg(long)]
292    pub db: Option<PathBuf>,
293    /// Print one JSON document (`membrane.adapt.taste_review.v1`).
294    #[arg(long)]
295    pub json: bool,
296}
297
298#[derive(Debug, Subcommand)]
299pub enum TranscriptCommand {
300    /// Append committed events at `--cursor`, the session's current end (`membrane.transcript.append.v1`).
301    Append(TranscriptAppendArgs),
302    /// The committed end cursor of a session's transcript (`membrane.transcript.tip.v1`).
303    Tip(TranscriptTipArgs),
304}
305
306#[derive(Debug, Args)]
307pub struct TranscriptTipArgs {
308    /// The session whose transcript end is read.
309    #[arg(long)]
310    pub session: String,
311    /// The Cortex store (default: the store under the state root).
312    #[arg(long)]
313    pub db: Option<PathBuf>,
314    /// Print one JSON document (`membrane.transcript.tip.v1`).
315    #[arg(long)]
316    pub json: bool,
317}
318
319#[derive(Debug, Args)]
320pub struct TranscriptAppendArgs {
321    /// The session whose transcript is appended to.
322    #[arg(long)]
323    pub session: String,
324    /// The session's current end: the `expected_stream_seq` the batch extends.
325    #[arg(long)]
326    pub cursor: u64,
327    /// The scope the rows belong to.
328    #[arg(long, default_value = "global")]
329    pub scope: String,
330    /// Read the events (a JSON array of `SessionTranscriptEventV1` rows) from standard input.
331    #[arg(long, conflicts_with = "text")]
332    pub stdin: bool,
333    /// The events as one JSON array of `SessionTranscriptEventV1` rows.
334    #[arg(long, conflicts_with = "stdin")]
335    pub text: Option<String>,
336    /// The Cortex store (default: the store under the state root).
337    #[arg(long)]
338    pub db: Option<PathBuf>,
339    /// Print one JSON document (`membrane.transcript.append.v1`).
340    #[arg(long)]
341    pub json: bool,
342}
343
344/// A memory tier, by the name `memory search --tier` takes.
345#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
346pub enum TierArg {
347    Working,
348    Episodic,
349    Semantic,
350}
351
352#[derive(Debug, Args)]
353pub struct SearchArgs {
354    /// The text to search for.
355    pub query: String,
356    /// Only memories in this tier. Repeat the flag for several tiers.
357    #[arg(long = "tier", value_enum)]
358    pub tiers: Vec<TierArg>,
359    /// Most results to return, 1 to 100.
360    #[arg(long, default_value_t = 6)]
361    pub limit: usize,
362    /// Only the memories a repository can see: its own scope, the scopes above it, and `global`.
363    /// Without `--cwd`, `--repo` or `--scope`, every scope is searched.
364    #[arg(long, conflicts_with_all = ["repo", "scopes"])]
365    pub cwd: Option<PathBuf>,
366    /// The repository, by its root path. Resolved exactly as `--cwd` is.
367    #[arg(long, alias = "repo-root", conflicts_with_all = ["cwd", "scopes"])]
368    pub repo: Option<PathBuf>,
369    /// A scope chain: search exactly these scopes (paths or slugs), most specific first. Repeat
370    /// the flag for several. No ancestors or `global` are added.
371    #[arg(long = "scope", conflicts_with_all = ["cwd", "repo"])]
372    pub scopes: Vec<String>,
373    /// The Cortex store (default: the store under the state root).
374    #[arg(long)]
375    pub db: Option<PathBuf>,
376    /// Print one JSON document (`membrane.memory.search.v1`).
377    #[arg(long)]
378    pub json: bool,
379}
380
381#[derive(Debug, Args)]
382pub struct DeleteArgs {
383    /// The memory id, as `memory search` or `memory list` printed it.
384    pub id: String,
385    /// The Cortex store (default: the store under the state root).
386    #[arg(long)]
387    pub db: Option<PathBuf>,
388    /// Print one JSON document (`membrane.memory.delete.v1`).
389    #[arg(long)]
390    pub json: bool,
391}
392
393#[derive(Debug, Args)]
394pub struct HistoryArgs {
395    /// `search <text> [--scope S] [--limit N] --json`, `status --json`, or
396    /// `erase --conversation ID | --source ID`.
397    #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
398    pub words: Vec<String>,
399}
400
401#[derive(Debug, Args)]
402pub struct BlueprintArgs {
403    /// A Blueprint verb with its arguments (`status`, `search <text>`, `impact <node>`, `build`,
404    /// `refresh`, ...), or free text, which is searched. `build` and `refresh` publish a new graph
405    /// generation for the repository.
406    #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
407    pub query: Vec<String>,
408}
409
410#[derive(Debug, Args)]
411pub struct WhereArgs {
412    /// Print one JSON object (`membrane.where.v1`) instead of the bare path.
413    #[arg(long)]
414    pub json: bool,
415}
416
417#[derive(Debug, Args)]
418pub struct StatusArgs {
419    /// Print one JSON object (`membrane.status.v1`).
420    #[arg(long)]
421    pub json: bool,
422    /// Exit 4 unless the resident answered; the status is still printed.
423    #[arg(long)]
424    pub require_resident: bool,
425}
426
427#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
428pub enum WireArg {
429    Claude,
430    Codex,
431}
432
433#[derive(Debug, Args)]
434pub struct HookArgs {
435    /// The harness whose hook schema the reply follows.
436    #[arg(long, value_enum)]
437    pub wire: WireArg,
438    /// The hook event, e.g. `SessionStart` or `UserPromptSubmit`.
439    #[arg(long)]
440    pub event: String,
441}
442
443#[derive(Debug, Subcommand)]
444pub enum ReceiptsCommand {
445    /// Mark emitted context `delivered` when its marker is in the host transcript. Prints
446    /// nothing and always exits 0.
447    Confirm(ConfirmArgs),
448    /// List the context receipts.
449    List(ReceiptsListArgs),
450    /// Mark the receipt `<id>` delivered, for a caller that injected the context itself.
451    Mark(MarkArgs),
452}
453
454#[derive(Debug, Args)]
455pub struct MarkArgs {
456    /// The `--request-id` the context was pulled with.
457    pub id: String,
458    /// Required: the only change `mark` makes. An `emitted` receipt becomes `delivered`; any
459    /// other state is left as it is.
460    #[arg(long, required = true)]
461    pub delivered: bool,
462    /// Print one JSON document (`membrane.receipts.mark.v1`).
463    #[arg(long)]
464    pub json: bool,
465}
466
467#[derive(Debug, Args)]
468pub struct ConfirmArgs {
469    /// The harness whose transcript this is.
470    #[arg(long, value_enum)]
471    pub wire: WireArg,
472    /// The session whose receipts are confirmed.
473    #[arg(long)]
474    pub session: String,
475    /// The host's record of the session: the Claude transcript or the Codex rollout (JSONL).
476    #[arg(long)]
477    pub transcript: PathBuf,
478}
479
480#[derive(Debug, Args)]
481pub struct ReceiptsListArgs {
482    /// Only this session's receipts.
483    #[arg(long)]
484    pub session: Option<String>,
485    /// Print one JSON array.
486    #[arg(long)]
487    pub json: bool,
488}
489
490#[derive(Debug, Args)]
491pub struct InitArgs {
492    /// The repository root to enroll.
493    pub root: PathBuf,
494    #[arg(long)]
495    pub repository: String,
496    #[arg(long)]
497    pub scope: String,
498    /// Move an existing exact registry binding from this old root to `root`.
499    #[arg(long)]
500    pub rebind_from: Option<PathBuf>,
501    #[arg(long)]
502    pub virtual_id: Option<String>,
503    #[arg(long)]
504    pub tenant_id: Option<String>,
505    #[arg(long)]
506    pub parent: Vec<String>,
507    #[arg(long)]
508    pub native: Option<String>,
509    #[arg(long)]
510    pub config: Option<PathBuf>,
511    /// Show what would change without writing the registry.
512    #[arg(long)]
513    pub dry_run: bool,
514}
515
516/// Parse a command line. Argument zero is the program name.
517pub fn parse<I, T>(args: I) -> Result<Cli, clap::Error>
518where
519    I: IntoIterator<Item = T>,
520    T: Into<OsString> + Clone,
521{
522    Cli::try_parse_from(args)
523}