diff --git a/Cargo.lock b/Cargo.lock index 80552d9..ac93aba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "anwesen" -version = "0.4.0" +version = "0.3.0" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index 077aa42..57c7492 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "anwesen" description = "Read-only HTTP daemon over a markdown vault, querying YAML frontmatter." -version = "0.4.0" +version = "0.3.0" edition = "2024" rust-version = "1.95" license = "BSD-3-Clause" diff --git a/README.md b/README.md index f51daa3..a7bb236 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Anwesen answers three kinds of question over HTTP: The frontmatter index is built once at startup and kept current by watching the vault directory. The index lives in memory; a restart rebuilds it, and there is nothing on disk to corrupt or migrate. -The same query-and-merge engine also runs offline, with no server. `anwesen merge` walks a directory, evaluates a query, and writes the merged markdown to stdout; `anwesen query` writes the same JSON document `GET /query` returns (see [Local generation](#local-generation)). +The same query-and-merge engine also runs offline, with no server: `anwesen merge` walks a directory, evaluates a query, and writes the merged markdown to stdout (see [Local generation](#local-generation)). ## Quick start @@ -52,12 +52,6 @@ Build one file out of many notes, without starting the daemon: anwesen merge --vault /path/to/vault --query 'tags=adr&__anw-order=title' > ADRs.md ``` -Ask which notes match, and what their frontmatter holds, without starting the daemon: - -``` -anwesen query --vault /path/to/vault --query 'tags=adr' | jq -r '.results[].path' -``` - ## CLI ``` @@ -65,7 +59,6 @@ anwesen serve --vault [--bind ] [--log-level ] [--otlp-slow-request-ms ] anwesen doctor --vault anwesen merge --vault --query -anwesen query --vault --query anwesen version ``` @@ -74,7 +67,7 @@ anwesen version | `--vault ` | `ANWESEN_VAULT` | _required_ | Path to the vault root. | | `--bind ` | `ANWESEN_BIND` | `127.0.0.1:8080` | Listen address for `serve`. | | `--log-level ` | `ANWESEN_LOG_LEVEL` | `info` | `error`, `warn`, `info`, `debug`, or `trace`. | -| `--query ` | `ANWESEN_QUERY` | empty (match all) | A `/query` query string: frontmatter predicates plus `__anw-` controls. `merge` and `query` only. | +| `--query ` | -- | _required for `merge`_ | A `/query` query string: frontmatter predicates plus `__anw-` controls. | | `--otlp-slow-request-ms` | `ANWESEN_OTLP_SLOW_REQUEST_MS` | `500` | Requests at or over this duration, or answering 5xx, also export a span. | Every flag has a matching `ANWESEN_` environment variable. CLI flags win @@ -86,7 +79,6 @@ exported is configured entirely through the standard `OTEL_` variables below. - **`serve`** -- run the daemon: walk the vault, build the index, watch for changes, serve the API. - **`doctor`** -- walk the vault once and report what would stop clean ingestion: unreadable files, unparseable YAML, path collisions on the HTTP surface, and frontmatter type drift (the same key carrying incompatible types across notes). Read-only; non-zero exit if any issue is found. - **`merge`** -- one-shot local generation: walk the vault, evaluate `--query`, and write the merged markdown document to stdout. No server, no HTTP. See [Local generation](#local-generation). -- **`query`** -- the same one-shot walk, writing the JSON document `GET /query` returns: which notes match, and what their frontmatter, `last_modified`, `etag` and `size` hold. No server, no HTTP. See [Local generation](#local-generation). - **`version`** -- print version and exit. ## Telemetry @@ -181,7 +173,7 @@ ISO-8601 dates and RFC 3339 datetimes are coerced to typed dates at read time, s | `__anw-order=[:asc\|:desc]` | path order | Order fragments (merge mode only). | | `__anw-kind=` | off | Refuse a mixed merge unless every matched note shares one value for the key (merge mode only). | -By default `/query` returns metadata only; fetch bodies with `/notes/`. The same JSON document is available offline, without the daemon, via `anwesen query` (see [Local generation](#local-generation)). +By default `/query` returns metadata only; fetch bodies with `/notes/`. #### Markdown-merge mode @@ -209,11 +201,7 @@ Returns vault path, note count, last index/event timestamps, watcher state, an i ## Local generation -Two subcommands answer a query on the command line, with no server and no HTTP round-trip: `merge` writes the merged markdown document, `query` writes the JSON projection. Both take the same `--vault` and `--query` flags, both walk the vault once, and both run the engine the endpoint runs -- so the output matches what the daemon would have returned for the same vault and query. - -### `merge` - -`anwesen merge` walks the vault, evaluates the query, and writes the merged document to stdout: +`anwesen merge` produces the markdown-merge document on the command line, with no server and no HTTP round-trip. It walks the vault, evaluates the query, and writes the merged document to stdout: ``` anwesen merge --vault /path/to/vault --query 'tags=adr&__anw-order=title&__anw-kind=kind' @@ -223,24 +211,6 @@ The `--query` string is the exact `/query` grammar: frontmatter predicates plus This is the materialization path: build a `CLAUDE.md`, a skill bundle, or any single file assembled from many notes, driven from a script or a one-off shell. -### `query` - -`anwesen query` answers the other half: which notes match, and what their frontmatter holds. It writes the same JSON document `GET /query` returns -- `results`, `total`, `truncated`, with `path`, `frontmatter`, `last_modified`, `etag` and `size` per row -- on one line, ready for `jq`: - -``` -anwesen query --vault /path/to/vault --query 'kind=PDR&__anw-limit=1' -``` - -```json -{"results":[{"path":"Projects/PDR-001-intro.md","frontmatter":{"kind":"PDR","num":1,"title":"PDR-001 Intro"},"last_modified":"2026-05-14T17:05:08Z","etag":"\"f657eab5...\"","size":57}],"total":2,"truncated":true} -``` - -`total` counts the full match set; `truncated` says the cap cut it. - -Bodies are elided here as they are on the endpoint; `merge` is the way to get them offline. `__anw-order` and `__anw-kind` are merge-mode controls and do not affect this output. A malformed query or an unreadable vault exits non-zero with the reason on stderr; an empty match set is an empty `results` list and exit `0`. - -A script can therefore move between the daemon and the CLI without a second parser: same shape, same field names, same timestamp dialect. - ## Design notes - **In place, read-only.** Anwesen reads the same directory Obsidian writes to and never writes back. The vault stays editable in Obsidian with no coordination, and there is no write API by design. diff --git a/src/app.rs b/src/app.rs index cc4bcf6..f3ee5fc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -121,12 +121,6 @@ pub struct Anwesen { /// Request-level telemetry handle ([ANW-37]). `None` disables export and /// the request middleware entirely. pub telemetry: Option>, - /// Set once the supervisor tree is up. Hydra's `Application::run` logs a - /// start failure and returns normally, so `serve` cannot tell a clean - /// shutdown from a tree that never came up. `main` reads this after `run` - /// and exits nonzero when it is still false, which is what lets systemd - /// retry ([ANW-45](https://crvrs.youtrack.cloud/issue/ANW-45)). - pub started: Arc, } impl Anwesen { @@ -139,7 +133,6 @@ impl Anwesen { store: NoteStore::new(), health: HealthState::new(), telemetry, - started: Arc::new(AtomicBool::new(false)), } } } @@ -194,12 +187,10 @@ impl Application for Anwesen { .child_spec(), ]; - let pid = Supervisor::with_children(children) + Supervisor::with_children(children) .strategy(SupervisionStrategy::OneForOne) .start_link(SupervisorOptions::new().name("anwesen_root")) - .await?; - self.started.store(true, Ordering::Release); - Ok(pid) + .await } } diff --git a/src/cli.rs b/src/cli.rs index 32bbced..52e65e4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -7,14 +7,9 @@ //! [--otlp-slow-request-ms ] //! anwesen doctor --vault [--log-level ] //! anwesen merge --vault [--query ] [--log-level ] -//! anwesen query --vault [--query ] [--log-level ] //! anwesen version //! ``` //! -//! `merge` and `query` differ only in what they write -- the merged markdown -//! document or the `/query` JSON projection ([ANW-43]) -- so they share one -//! [`VaultQueryArgs`] flag set and cannot drift. -//! //! `--bind` and `--otlp-slow-request-ms` are `serve`-only ([ANW-37]); //! `doctor` and `merge` do not bind a port; `version` takes no flags. Each //! flag has a matching `ANWESEN_` environment variable and CLI wins @@ -46,11 +41,7 @@ pub enum Command { Doctor(DoctorArgs), /// Walk the vault once, evaluate the query, and write the merged markdown /// document to stdout. One-shot; no server. Read-only. - Merge(VaultQueryArgs), - /// Walk the vault once, evaluate the query, and write the same JSON - /// document `GET /query` returns to stdout. One-shot; no server. - /// Read-only. - Query(VaultQueryArgs), + Merge(MergeArgs), /// Print the version and exit. Version, } @@ -106,9 +97,8 @@ pub struct DoctorArgs { pub log_level: LogLevel, } -/// Flags shared by the two one-shot subcommands, `merge` and `query`. #[derive(Debug, clap::Args)] -pub struct VaultQueryArgs { +pub struct MergeArgs { /// Path to the vault root. #[arg(long, env = "ANWESEN_VAULT")] pub vault: PathBuf, @@ -116,12 +106,12 @@ pub struct VaultQueryArgs { /// Query in the `/query` query-string grammar, for example /// `tags=anwesen&__anw-kind=skill&__anw-order=order`. The `__anw-kind` /// homogeneity guard and `__anw-order` fragment ordering ride inside this - /// string -- there are no separate flags. `__anw-kind` and `__anw-order` - /// apply to `merge` only. Empty matches every note under the vault root. + /// string -- there are no separate flags. Empty merges every note under + /// the vault root. #[arg(long, env = "ANWESEN_QUERY", default_value = "")] pub query: String, - /// Log verbosity. Logs go to stderr; the document goes to stdout. + /// Log verbosity. Logs go to stderr; the merged document goes to stdout. #[arg(long, env = "ANWESEN_LOG_LEVEL", default_value = "info")] pub log_level: LogLevel, } @@ -281,47 +271,6 @@ mod tests { assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument); } - #[test] - fn query_takes_the_same_flags_as_merge() { - let cli = parse(&[ - "query", - "--vault", - "/tmp/v", - "--query", - "tags=anwesen&__anw-limit=5", - "--log-level", - "warn", - ]) - .expect("parse"); - match cli.command { - Command::Query(a) => { - assert_eq!(a.vault, PathBuf::from("/tmp/v")); - assert_eq!(a.query, "tags=anwesen&__anw-limit=5"); - assert!(matches!(a.log_level, LogLevel::Warn)); - } - _ => panic!("expected query"), - } - } - - #[test] - fn query_requires_vault_and_defaults_the_query() { - assert!(parse(&["query"]).is_err()); - match parse(&["query", "--vault", "/tmp/v"]) - .expect("parse") - .command - { - Command::Query(a) => assert_eq!(a.query, ""), - _ => panic!("expected query"), - } - } - - #[test] - fn query_rejects_bind() { - // --bind is serve-only; query does not listen. - let err = parse(&["query", "--vault", "/tmp/v", "--bind", "0.0.0.0:9000"]).unwrap_err(); - assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument); - } - #[test] fn version_takes_no_flags() { assert!(matches!( diff --git a/src/http.rs b/src/http.rs index 1d847a9..52d4c0f 100644 --- a/src/http.rs +++ b/src/http.rs @@ -22,7 +22,7 @@ use axum::http::{HeaderMap, HeaderValue, StatusCode}; use axum::middleware::{Next, from_fn, from_fn_with_state}; use axum::response::{IntoResponse, Response}; use axum::routing::get; -use chrono::{DateTime, Utc}; +use chrono::{DateTime, SecondsFormat, Utc}; use http_body::Body as _; use hydra::Process; use serde::Serialize; @@ -32,11 +32,17 @@ use std::path::PathBuf; use crate::app::RestartCounters; use crate::health::HealthState; -use crate::query::rfc3339_z; use crate::store::NoteStore; use crate::telemetry::{self, Telemetry, TraceHeaders}; use crate::vault::{Note, frontmatter_to_json}; +/// Canonical RFC 3339 form with a `Z` suffix -- the shape the User Manual +/// example uses for `last_modified`. Centralized here so every HTTP +/// `last_modified` field stays in the same dialect. +fn rfc3339_z(dt: DateTime) -> String { + dt.to_rfc3339_opts(SecondsFormat::Secs, true) +} + /// Shared state injected into every handler. #[derive(Clone)] pub struct HttpState { diff --git a/src/lib.rs b/src/lib.rs index 818b23e..59f1689 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,7 +10,7 @@ pub mod app; pub mod doctor; pub mod health; pub mod http; -pub mod oneshot; +pub mod merge; pub mod query; pub mod store; pub mod telemetry; diff --git a/src/main.rs b/src/main.rs index 05027d9..4ac8e27 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,15 @@ //! Anwesen: read-only HTTP daemon over a markdown vault. //! -//! This module wires the CLI to the `serve`, `doctor`, `merge`, `query`, and +//! This module wires the CLI to the `serve`, `doctor`, `merge`, and //! `version` subcommands. mod cli; use std::sync::Arc; -use std::sync::atomic::Ordering; use anwesen::app::Anwesen; use anwesen::doctor; -use anwesen::oneshot; +use anwesen::merge; use anwesen::telemetry::{self, OtelEnv, RawTelemetryArgs, TelemetryConfig}; use anyhow::Result; use clap::Parser; @@ -47,22 +46,12 @@ fn main() -> Result<()> { telemetry = telemetry.is_some(), "anwesen serve: starting supervisor tree" ); - let app = Anwesen::new(args.vault, args.bind, telemetry.clone()); - let started = app.started.clone(); // Blocks until the supervisor exits (SIGTERM / SIGINT / crash). - app.run(); + Anwesen::new(args.vault, args.bind, telemetry.clone()).run(); // Flush and shut down exporters after the server loop returns. if let Some(telemetry) = telemetry { telemetry.shutdown(); } - // `run` returns normally whether the tree came up or never - // started, so a failed start would otherwise look like a clean - // exit and systemd's `Restart=on-failure` would not retry - // (ANW-45). Exit nonzero when the tree never came up. - if !started.load(Ordering::Acquire) { - tracing::error!("anwesen serve: supervisor tree failed to start"); - std::process::exit(1); - } } Command::Doctor(args) => { init_logging(args.log_level); @@ -74,26 +63,13 @@ fn main() -> Result<()> { } Command::Merge(args) => { init_logging(args.log_level); - match oneshot::merge(&args.vault, &args.query) { + match merge::run(&args.vault, &args.query) { // `print!`, not `println!`: the merged document is byte-stable // and byte-identical to the HTTP merge body, which carries no // trailing newline. An empty match set prints nothing, exit 0. Ok(doc) => print!("{doc}"), Err(e) => { - eprint!("{}", e.render("merge")); - std::process::exit(1); - } - } - } - Command::Query(args) => { - init_logging(args.log_level); - match oneshot::query_json(&args.vault, &args.query) { - // `println!` here, unlike `merge`: the JSON body carries no - // trailing newline either, but stdout is one document per - // line for the shells and `jq` pipelines this exists for. - Ok(doc) => println!("{doc}"), - Err(e) => { - eprint!("{}", e.render("query")); + eprint!("{}", e.render()); std::process::exit(1); } } diff --git a/src/merge.rs b/src/merge.rs new file mode 100644 index 0000000..a9b6d2b --- /dev/null +++ b/src/merge.rs @@ -0,0 +1,205 @@ +//! One-shot local markdown-merge for the `anwesen merge` subcommand ([ANW-27]). +//! +//! Walks a vault directory once (the same [`vault::scan`] as `doctor`), +//! evaluates the `--query` string, and assembles the merged markdown document +//! with [`query::execute_merge`] -- the very engine the HTTP `/query` merge +//! mode ([ANW-26]) uses. CLI and HTTP output are therefore byte-identical for +//! the same vault and query. No HTTP, no watcher, no persistent index. + +use std::fmt::Write as _; +use std::path::Path; + +use crate::query::{self, MergeError, QueryError}; +use crate::store::NoteStore; +use crate::vault::{self, ScanIssue}; + +/// Why a one-shot merge could not produce a document. +#[derive(Debug)] +pub enum MergeCliError { + /// The `--query` string did not parse. Same grammar, same message as the + /// HTTP `/query` `400`. + Query(QueryError), + /// One or more files could not be read, or their frontmatter did not + /// parse. Same hard-failure posture as `doctor`; soft warnings (e.g. a + /// non-mapping frontmatter root) are ignored, matching what `serve` + /// ingests. + Scan(Vec), + /// The `__anw-kind` homogeneity guard rejected the matched set. The + /// `String` is the same naming message the HTTP path returns as `400`, + /// surfaced here on stderr instead. + Kind(String), +} + +impl MergeCliError { + /// Render the error for stderr. One concern per line, deterministic so the + /// stderr surface is golden-testable. + #[must_use] + pub fn render(&self) -> String { + match self { + Self::Query(e) => format!("{e}\n"), + Self::Scan(issues) => { + let mut s = String::from("merge: cannot read vault\n"); + for issue in issues { + let _ = writeln!(s, " {}: {}", issue.path.display(), issue.kind); + } + s + } + Self::Kind(msg) => msg.clone(), + } + } +} + +/// Walk `vault_root`, evaluate `raw_query`, and return the merged document. +/// +/// On success the returned `String` is byte-identical to the HTTP merge body +/// for the same vault and query. An empty match set yields an empty string. +/// +/// # Errors +/// - [`MergeCliError::Query`] when `raw_query` is malformed; +/// - [`MergeCliError::Scan`] when the directory is unreadable or any file's +/// frontmatter fails to parse; +/// - [`MergeCliError::Kind`] when the `__anw-kind` homogeneity guard fails. +pub fn run(vault_root: &Path, raw_query: &str) -> Result { + let parsed = query::parse(raw_query).map_err(MergeCliError::Query)?; + + let scan = vault::scan(vault_root); + if !scan.issues.is_empty() { + return Err(MergeCliError::Scan(scan.issues)); + } + + // The merge engine reads from a NoteStore exactly as the HTTP path does; + // a one-shot `replace` is the whole "index" this subcommand needs. + let store = NoteStore::new(); + store.replace(scan.notes); + + query::execute_merge(&store, &parsed) + .map_err(|MergeError::KindGuard(msg)| MergeCliError::Kind(msg)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::Path; + use tempfile::TempDir; + + fn write(root: &Path, rel: &str, body: &str) { + let p = root.join(rel); + if let Some(parent) = p.parent() { + fs::create_dir_all(parent).unwrap(); + } + fs::write(p, body).unwrap(); + } + + #[test] + fn merges_bodies_with_source_markers() { + let tmp = TempDir::new().unwrap(); + write(tmp.path(), "a.md", "---\nnum: 1\n---\nalpha\n"); + write(tmp.path(), "b.md", "---\nnum: 2\n---\nbeta\n"); + let out = run(tmp.path(), "").unwrap(); + // Body is frontmatter-stripped; fragments join with a blank line and + // there is no trailing newline -- byte-identical to the HTTP body. + assert_eq!( + out, + "\nalpha\n\n\n\nbeta\n" + ); + } + + #[test] + fn order_desc_then_path_tiebreak() { + let tmp = TempDir::new().unwrap(); + write(tmp.path(), "a.md", "---\nnum: 1\n---\nlow\n"); + write(tmp.path(), "b.md", "---\nnum: 3\n---\nhigh\n"); + write(tmp.path(), "c.md", "---\nnum: 2\n---\nmid\n"); + let out = run(tmp.path(), "__anw-order=num:desc").unwrap(); + let bodies: Vec<&str> = out + .lines() + .filter(|l| !l.starts_with("\nalpha\n\n\n\nbeta\n" - ); - } - - #[test] - fn order_desc_then_path_tiebreak() { - let tmp = TempDir::new().unwrap(); - write(tmp.path(), "a.md", "---\nnum: 1\n---\nlow\n"); - write(tmp.path(), "b.md", "---\nnum: 3\n---\nhigh\n"); - write(tmp.path(), "c.md", "---\nnum: 2\n---\nmid\n"); - let out = merge(tmp.path(), "__anw-order=num:desc").unwrap(); - let bodies: Vec<&str> = out - .lines() - .filter(|l| !l.starts_with("