1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
//! The `neosian memory` grammar (`memory/cli_grammar.py`, DESIGN ยง14.2):
//! argv to a typed command, pure. Nothing here builds a store or touches
//! the home, which is what makes exit 2 mean "nothing on disk". The six
//! commands' flags are the ladder's argument names, kebab-cased; the
//! operator verbs sit beside them and are never commands a model reaches.
use std::borrow::Cow;
use std::env;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use clap::{Args, Subcommand};
use super::mounts::{Mount, Refusal};
use crate::home::project_mounts;
use crate::repr::repr;
use crate::store::grammar::Actor;
pub const SCOPE_ENV: &str = "NEOSIAN_SCOPE";
/// Where the `--scope` sugar mounts: the path a trained memory tool roots at.
pub const SUGAR_MOUNT_PATH: &str = "memories";
/// The store flags every memory command takes.
#[derive(Args)]
pub struct Flags {
/// Select a portable workspace profile and its local bindings.
#[arg(long)]
pub profile: Option<String>,
/// FileStore root directory (created on start; default: the home,
/// ~/.neosian or $NEOSIAN_HOME)
#[arg(long)]
pub root: Option<PathBuf>,
/// State process URL; bearer token from NEOSIAN_CLIENT_TOKEN.
#[arg(long)]
pub url: Option<String>,
/// Postgres schema (Postgres only).
#[arg(long)]
pub schema: Option<String>,
/// single read-write mount of SCOPE at /memories
#[arg(long)]
scope: Option<String>,
/// explicit mount; repeatable (ro = read-only, eo = edit-only:
/// existing documents only)
#[arg(long, value_name = "scope=...,path=...[,ro|,eo]")]
mount: Vec<String>,
/// who writes: <kind>:<id>[/...], recorded on every row
#[arg(long, default_value = "cli:local")]
actor: String,
/// print the result as JSON on stdout
#[arg(long)]
pub json: bool,
}
#[derive(Subcommand)]
pub enum Command {
/// Search current mounted memory and explicitly selected metadata.
Search {
#[command(flatten)]
search: super::search::cli::Search,
#[command(flatten)]
flags: Flags,
},
/// Remove aged empty documents and exact duplicates. Pause other writers first.
Maintain {
/// Preview the deletions without changing any document.
#[arg(long)]
dry_run: bool,
/// Protect documents updated in the last N days.
#[arg(long, default_value_t = 7, value_parser = clap::value_parser!(u32).range(0..=365000))]
min_age_days: u32,
#[command(flatten)]
flags: Flags,
},
/// which documents agent sessions read: counts over 7 and 30 days, all time, and the last read
Heat {
/// virtual path: / (every mount), a mount, a directory or a document
#[arg(default_value = "/")]
path: String,
/// list what the sessions that read the document at PATH also read
#[arg(long)]
related: bool,
/// rows to show: most read, or most shared with --related
#[arg(long, value_name = "N", default_value_t = 20, value_parser = clap::value_parser!(u32).range(1..=10000))]
limit: u32,
#[command(flatten)]
flags: Flags,
},
/// print a document, a directory listing, or / (the index)
View {
/// virtual path
#[arg(default_value = "/")]
path: String,
/// 1-based inclusive line range; END -1 means end of document
#[arg(long, num_args = 2, value_names = ["START", "END"], allow_negative_numbers = true)]
view_range: Option<Vec<i64>>,
#[command(flatten)]
flags: Flags,
},
/// create or overwrite a document
Create {
/// virtual path, e.g. /memories/topic-name
path: String,
/// document text ('-' = stdin)
#[arg(long, allow_hyphen_values = true)]
content: String,
#[command(flatten)]
flags: Flags,
},
/// replace exactly one occurrence
#[command(name = "str_replace")]
StrReplace {
/// virtual path
path: String,
/// text to replace
#[arg(long, allow_hyphen_values = true)]
old_str: String,
/// replacement text ('-' = stdin)
#[arg(long, allow_hyphen_values = true)]
new_str: String,
#[command(flatten)]
flags: Flags,
},
/// splice text at a line number
Insert {
/// virtual path
path: String,
/// 0-based line
#[arg(long, allow_negative_numbers = true)]
insert_line: i64,
/// text to insert ('-' = stdin)
#[arg(long, allow_hyphen_values = true)]
insert_text: String,
#[command(flatten)]
flags: Flags,
},
/// delete a document
Delete {
/// virtual path
path: String,
#[command(flatten)]
flags: Flags,
},
/// move a document (cross-mount is not atomic)
Rename {
/// current virtual path
#[arg(value_name = "OLD")]
old_path: String,
/// destination virtual path
#[arg(value_name = "NEW")]
new_path: String,
#[command(flatten)]
flags: Flags,
},
/// list a document's version rows, newest first
Versions {
/// virtual document path
path: String,
/// most recent rows to show
#[arg(
long,
value_name = "N",
default_value_t = 50,
allow_negative_numbers = true
)]
limit: i64,
#[command(flatten)]
flags: Flags,
},
/// clear a document's content everywhere, keeping the audit skeleton
Redact {
/// virtual document path (or a mount root + --all)
path: String,
/// required to redact a whole mount's scope (irreversible)
#[arg(long)]
all: bool,
#[command(flatten)]
flags: Flags,
},
/// undo one version row (must be the newest)
Revert {
/// virtual document path
path: String,
/// the version row to undo (from `versions`)
#[arg(long, value_name = "N", allow_negative_numbers = true)]
version: i64,
#[command(flatten)]
flags: Flags,
},
}
impl Command {
pub fn flags(&self) -> &Flags {
match self {
Self::Search { flags, .. }
| Self::Maintain { flags, .. }
| Self::Heat { flags, .. }
| Self::View { flags, .. }
| Self::Create { flags, .. }
| Self::StrReplace { flags, .. }
| Self::Insert { flags, .. }
| Self::Delete { flags, .. }
| Self::Rename { flags, .. }
| Self::Versions { flags, .. }
| Self::Redact { flags, .. }
| Self::Revert { flags, .. } => flags,
}
}
/// The guards the grammar owes beyond its shape, each a pure check of
/// a string or a number.
fn guard(&self) -> Result<(), Refusal> {
let refuse = |message: String| Err(Refusal::Usage(message));
match self {
Self::Versions { limit, .. } if *limit < 1 => {
refuse("--limit must be at least 1".to_string())
}
Self::Revert { version, .. } if *version < 1 => {
refuse("--version must be at least 1 (versions start at 1)".to_string())
}
Self::Heat {
path,
related: true,
..
} if !path.trim_matches('/').contains('/') => refuse(format!(
"--related needs one document's path, not {}",
repr(path)
)),
Self::Redact { path, all, .. } => {
let root = !path.trim_matches('/').contains('/');
match (root, all) {
(true, false) => refuse(format!(
"{} names a whole mount: pass --all to redact its entire scope \
(irreversible)",
repr(path)
)),
(false, true) => refuse(
"--all redacts a whole mount: pass the mount root, not a document"
.to_string(),
),
_ => Ok(()),
}
}
_ => Ok(()),
}
}
/// The text of the one payload flag a command carries; `-` reads stdin
/// whole. Python's stdin translates newlines on Windows alone (a CRLF
/// or a lone CR becomes a newline there), and so does this.
pub fn payload(&self) -> io::Result<Cow<'_, str>> {
let value = match self {
Self::Create { content, .. } => content,
Self::StrReplace { new_str, .. } => new_str,
Self::Insert { insert_text, .. } => insert_text,
_ => return Ok(Cow::Borrowed("")),
};
if value != "-" {
return Ok(Cow::Borrowed(value));
}
let mut text = String::new();
io::stdin().read_to_string(&mut text)?;
if cfg!(windows) {
text = text.replace("\r\n", "\n").replace('\r', "\n");
}
Ok(Cow::Owned(text))
}
/// What the invocation resolves to, nothing built: the mounts its
/// flags name (else `NEOSIAN_SCOPE` as the sugar mount, else the
/// working directory's project layout) and its actor, each held to its
/// grammar, then the command's own guards.
pub fn settings(
&self,
cwd: &Path,
selected: &crate::remote::selection::Selection,
) -> Result<(Vec<Mount>, Actor), Refusal> {
let settings = self.flags().selected_settings(cwd, selected)?;
if let Self::Search { search, .. } = self {
search.validate(&settings.0).map_err(Refusal::Usage)?;
}
self.guard()?;
Ok(settings)
}
}
impl Flags {
/// Configuration-only skill actions have no storage selection to override.
pub fn local_profile(&self) -> Result<&str, String> {
if self.root.is_some()
|| self.url.is_some()
|| self.schema.is_some()
|| self.scope.is_some()
|| !self.mount.is_empty()
{
return Err(
"profile selection changes do not accept storage or mount overrides".into(),
);
}
self.profile
.as_deref()
.ok_or_else(|| "skill selection changes require explicit --profile".into())
}
pub fn select(&self, cwd: &Path) -> Result<crate::remote::selection::Selection, String> {
crate::remote::selection::Selection::resolve_profile(
self.root.as_deref(),
self.url.as_deref(),
self.schema.as_deref(),
self.profile.as_deref(),
cwd,
self.scope.is_some() || !self.mount.is_empty(),
)
}
pub fn selected_settings(
&self,
cwd: &Path,
selected: &crate::remote::selection::Selection,
) -> Result<(Vec<Mount>, Actor), Refusal> {
if let Some(mounts) = selected.mounts() {
let actor = Actor::parse(&self.actor).map_err(Refusal::Usage)?;
return Ok((mounts.map_err(Refusal::Usage)?, actor));
}
self.settings(cwd)
}
/// Shared mount and actor grammar for memory and messages.
pub fn settings(&self, cwd: &Path) -> Result<(Vec<Mount>, Actor), Refusal> {
let flags = self;
if flags.scope.is_some() && !flags.mount.is_empty() {
let sugar = "--scope is the single-mount sugar; use --mount for multi-mount";
return Err(Refusal::Usage(sugar.to_string()));
}
let named = env::var(SCOPE_ENV).ok().filter(|scope| !scope.is_empty());
let mounts = match flags.scope.as_ref().or(named.as_ref()) {
_ if !flags.mount.is_empty() => {
let parsed: Result<Vec<_>, _> =
flags.mount.iter().map(|m| Mount::parse(m)).collect();
parsed?
}
Some(scope) => vec![Mount::new(scope, SUGAR_MOUNT_PATH, (false, false), "")?],
None => project_mounts(cwd)?,
};
let twice = |mount: &Mount| {
mounts
.iter()
.filter(|other| other.path == mount.path)
.count()
> 1
};
if mounts.iter().any(twice) {
return Err(Refusal::Usage("mount paths must be unique".to_string()));
}
let actor = Actor::parse(&flags.actor).map_err(|reason| {
let actor = repr(&flags.actor);
Refusal::Usage(format!("--actor {actor}: {reason} (e.g. cli:claude-code)"))
})?;
Ok((mounts, actor))
}
}