Skip to main content

omgbase_surface/
catalog.rs

1//! The MCP tool catalog (`spec/surface/README.md` §4) as a library: a table
2//! of [`ToolSpec`]s (name, JSON-schema input, description) and one dispatch
3//! ([`Surface::call`]) that runs a tool against the store and returns its
4//! JSON result or the error envelope. Transport-agnostic — a server wraps
5//! each outcome in one text content item. Port of
6//! `packages/core/src/mcp/server.ts`.
7
8use std::path::Path;
9
10use omgbase_format::BlockKind;
11use omgbase_format::text::{normalize_text, normalize_visible_text};
12use omgbase_reconcile::Config;
13use omgbase_search::EmbeddingProvider;
14use omgbase_store::mutate_kernel::{At, Op, Parent, To};
15use omgbase_store::{
16    ApplyOrigin, ApplyRequest, ApplyResult, DocOpContext, DocStore, Expect, FsDocStore, Opset,
17    QueryVector, Store,
18};
19use omgbase_sync::{RealFileSystem, RepoRow};
20use rusqlite::{OptionalExtension, params};
21use serde_json::{Map, Value as Json, json};
22
23use crate::error::{Result, SurfaceError};
24use crate::graph::{GraphArgs, graph_neighborhood};
25use crate::history;
26use crate::links;
27use crate::query::{QueryOptions, query};
28use crate::read::{self, Resolution, ResolvedRef};
29use crate::reference::QUERY_SYNTAX;
30
31/// The actor every write from this surface records.
32pub const ACTOR: &str = "agent:mcp";
33
34/// One tool of the catalog.
35#[derive(Clone, Debug, PartialEq)]
36pub struct ToolSpec {
37    pub name: &'static str,
38    pub description: &'static str,
39    /// The JSON schema of the arguments object.
40    pub input_schema: Json,
41}
42
43/// What a tool call produced: its JSON result, or the error envelope with
44/// `is_error` set.
45#[derive(Clone, Debug, PartialEq)]
46pub struct ToolOutcome {
47    pub body: Json,
48    pub is_error: bool,
49}
50
51/// Where a mutating tool writes files.
52enum WriteTarget {
53    /// Derive the repo's root from its `fs` source and write through the
54    /// filesystem (a sourceless repo cannot mutate).
55    Derived,
56    /// Write through this store whatever the repo's sources say (a runner's
57    /// in-memory store).
58    Fixed(Box<dyn DocStore>),
59}
60
61/// The catalog bound to a store, a default repo and optional providers.
62pub struct Surface {
63    store: Store,
64    default_repo: String,
65    provider: Option<Box<dyn EmbeddingProvider>>,
66    on_mutation: Option<Box<dyn FnMut()>>,
67    clock: Box<dyn FnMut() -> String>,
68    writes: WriteTarget,
69    config: Config,
70}
71
72// ---- argument helpers ----------------------------------------------------------------
73
74fn bad_args(msg: impl Into<String>) -> SurfaceError {
75    SurfaceError::filter_invalid(msg, "arguments")
76}
77
78fn arg_str<'a>(args: &'a Json, key: &str) -> Option<&'a str> {
79    args.get(key).and_then(Json::as_str)
80}
81
82fn arg_string(args: &Json, key: &str) -> Result<String> {
83    arg_str(args, key)
84        .map(str::to_owned)
85        .ok_or_else(|| bad_args(format!("`{key}` must be a string")))
86}
87
88fn arg_i64(args: &Json, key: &str) -> Result<Option<i64>> {
89    match args.get(key) {
90        None | Some(Json::Null) => Ok(None),
91        Some(v) => v
92            .as_f64()
93            .filter(|n| n.fract() == 0.0)
94            .map(|n| Some(n as i64))
95            .ok_or_else(|| bad_args(format!("`{key}` must be an integer"))),
96    }
97}
98
99fn arg_usize(args: &Json, key: &str) -> Result<Option<usize>> {
100    Ok(arg_i64(args, key)?.map(|n| usize::try_from(n).unwrap_or(0)))
101}
102
103fn arg_bool(args: &Json, key: &str) -> Result<Option<bool>> {
104    match args.get(key) {
105        None | Some(Json::Null) => Ok(None),
106        Some(Json::Bool(b)) => Ok(Some(*b)),
107        Some(_) => Err(bad_args(format!("`{key}` must be a boolean"))),
108    }
109}
110
111fn arg_strings(args: &Json, key: &str) -> Result<Vec<String>> {
112    let Some(arr) = args.get(key).and_then(Json::as_array) else {
113        return Err(bad_args(format!("`{key}` must be an array of strings")));
114    };
115    arr.iter()
116        .map(|v| {
117            v.as_str()
118                .map(str::to_owned)
119                .ok_or_else(|| bad_args(format!("`{key}` must be an array of strings")))
120        })
121        .collect()
122}
123
124fn arg_object<'a>(args: &'a Json, key: &str) -> Result<Option<&'a Map<String, Json>>> {
125    match args.get(key) {
126        None | Some(Json::Null) => Ok(None),
127        Some(Json::Object(o)) => Ok(Some(o)),
128        Some(_) => Err(bad_args(format!("`{key}` must be an object"))),
129    }
130}
131
132fn resolution_arg(args: &Json, default: Resolution) -> Result<Resolution> {
133    match arg_str(args, "resolution") {
134        None => Ok(default),
135        Some(s) => Resolution::parse(s).ok_or_else(|| {
136            bad_args("`resolution` must be one of skeleton, outline, text, raw, full")
137        }),
138    }
139}
140
141/// `{ ...a, ...b }` (b wins).
142fn merge(mut a: Map<String, Json>, b: Json) -> Json {
143    if let Json::Object(o) = b {
144        for (k, v) in o {
145            a.insert(k, v);
146        }
147    }
148    Json::Object(a)
149}
150
151fn schema(props: &[(&str, Json)], required: &[&str], repo: bool) -> Json {
152    let mut p = Map::new();
153    for (k, v) in props {
154        p.insert((*k).to_owned(), v.clone());
155    }
156    if repo {
157        p.insert("repo".to_owned(), json!({ "type": "string" }));
158    }
159    json!({ "type": "object", "properties": p, "required": required })
160}
161
162fn s() -> Json {
163    json!({ "type": "string" })
164}
165fn i() -> Json {
166    json!({ "type": "integer" })
167}
168fn b() -> Json {
169    json!({ "type": "boolean" })
170}
171fn strings() -> Json {
172    json!({ "type": "array", "items": { "type": "string" } })
173}
174fn obj() -> Json {
175    json!({ "type": "object" })
176}
177fn nullable_string() -> Json {
178    json!({ "type": ["string", "null"] })
179}
180fn resolution_schema() -> Json {
181    json!({ "type": "string", "enum": ["skeleton", "outline", "text", "raw", "full"] })
182}
183fn at_schema() -> Json {
184    json!({ "oneOf": [
185        { "const": "start" }, { "const": "end" },
186        { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
187        { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] }
188    ] })
189}
190fn expect_schema() -> Json {
191    json!({ "type": "object", "properties": { "content_hash": { "type": "string" }, "parent_children_hash": { "type": "string" } } })
192}
193
194/// The catalog (§4 table), in the reference's registration order.
195#[must_use]
196pub fn tools() -> Vec<ToolSpec> {
197    let dp = |extra: &[(&str, Json)], required: &[&str]| {
198        let mut props = vec![("doc", s()), ("path", s())];
199        props.extend(extra.iter().cloned());
200        schema(&props, required, true)
201    };
202    vec![
203        ToolSpec {
204            name: "docs_outline",
205            description: "A document's compact indented outline (id, type, label per line; § marks headings). Args take a doc id or path.",
206            input_schema: dp(
207                &[
208                    (
209                        "resolution",
210                        json!({ "type": "string", "enum": ["skeleton", "outline"] }),
211                    ),
212                    ("depth", i()),
213                    ("budget_tokens", i()),
214                ],
215                &[],
216            ),
217        },
218        ToolSpec {
219            name: "docs_read",
220            description: "Read a whole document: verbatim `content`, `properties` grouped by source, `path`/`docId`/`rev`; include_ids adds `ids`, `hashes` (CAS tokens) and `parents`.",
221            input_schema: dp(&[("include_ids", b())], &[]),
222        },
223        ToolSpec {
224            name: "docs_get_many",
225            description: "Batch docs_read over `docs` (ids or paths): `{ items, errors, truncated }`, capped at 100 refs, optional token budget.",
226            input_schema: schema(
227                &[
228                    ("docs", strings()),
229                    ("include_ids", b()),
230                    ("budget_tokens", i()),
231                ],
232                &["docs"],
233                true,
234            ),
235        },
236        ToolSpec {
237            name: "nodes_get",
238            description: "Hydrate one block subtree at a resolution (skeleton|outline|text|raw|full); the owning doc is inferred from `id` when `doc`/`path` are omitted.",
239            input_schema: dp(&[("id", s()), ("resolution", resolution_schema())], &["id"]),
240        },
241        ToolSpec {
242            name: "nodes_get_many",
243            description: "Fetch up to 100 blocks by id in request order with budget truncation; `doc`/`path` is an optional scope. Returns `nodes`, `truncated`, `unresolved`.",
244            input_schema: dp(
245                &[
246                    ("ids", strings()),
247                    ("resolution", resolution_schema()),
248                    ("budget_tokens", i()),
249                ],
250                &["ids"],
251            ),
252        },
253        ToolSpec {
254            name: "read_ref",
255            description: "Read any ref — a document (id or path) or a block (`b_` id, or an `n_` node id) — classified as `{ kind: \"document\", … }` or `{ kind: \"block\", … }` (block `resolution` defaults to raw).",
256            input_schema: schema(
257                &[("ref", s()), ("resolution", resolution_schema())],
258                &["ref"],
259                true,
260            ),
261        },
262        ToolSpec {
263            name: "docs_tree",
264            description: "The directory-aware shape of a repo: live docs under `path` collapsed at `depth` segments into dir/doc entries with totals, ordered by path and paged.",
265            input_schema: schema(
266                &[
267                    ("path", s()),
268                    ("depth", i()),
269                    ("limit", i()),
270                    ("cursor", nullable_string()),
271                    ("budget_tokens", i()),
272                ],
273                &[],
274                true,
275            ),
276        },
277        ToolSpec {
278            name: "docs_list",
279            description: "Enumerate live documents as a page `{ items: [{ path, blocks, ts }], truncated, cursor }`, ordered by path; `path_glob` is a LIKE match (`*` matches across `/`).",
280            input_schema: schema(
281                &[
282                    ("path_glob", s()),
283                    ("limit", i()),
284                    ("cursor", nullable_string()),
285                    ("budget_tokens", i()),
286                ],
287                &[],
288                true,
289            ),
290        },
291        ToolSpec {
292            name: "query_syntax",
293            description: "The OQX syntax reference for the `query` tool.",
294            input_schema: schema(&[], &[], false),
295        },
296        ToolSpec {
297            name: "query",
298            description: "Run one OQX query (`select … from docs|blocks|nodes|edges where … follow … order by … limit N`). Returns lean hits `{ id, path, …projections }` with `truncated` + `cursor`, or a `count`/`exists`/`none` scalar, or `values`. See query_syntax.",
299            input_schema: schema(
300                &[
301                    ("query", s()),
302                    ("limit", i()),
303                    ("cursor", nullable_string()),
304                ],
305                &["query"],
306                true,
307            ),
308        },
309        ToolSpec {
310            name: "graph",
311            description: "The bounded neighborhood around root documents in one call — `{ documents, edges, frontier }` — compiled to an OQX `follow doc.out`/`doc.in` walk.",
312            input_schema: schema(
313                &[
314                    ("roots", strings()),
315                    ("degrees", i()),
316                    (
317                        "direction",
318                        json!({ "type": "string", "enum": ["in", "out", "both"] }),
319                    ),
320                    ("predicate", s()),
321                    ("select", strings()),
322                    ("max_documents", i()),
323                ],
324                &["roots"],
325                true,
326            ),
327        },
328        ToolSpec {
329            name: "text_search",
330            description: "Full-text (FTS5, bm25-ranked) search over block text.",
331            input_schema: schema(&[("q", s()), ("limit", i())], &["q"], true),
332        },
333        ToolSpec {
334            name: "resolve",
335            description: "Resolve a name/title/phrase to the blocks it refers to: ranked `{ id, locator, preview, evidence }` (FTS, fused with the vector ranking when a provider exists).",
336            input_schema: schema(&[("query", s()), ("limit", i())], &["query"], true),
337        },
338        ToolSpec {
339            name: "apply",
340            description: "Apply a changeset of kernel ops (insert/update/move/remove/split/merge) atomically; `dry_run` previews diffs.",
341            input_schema: schema(
342                &[
343                    (
344                        "ops",
345                        json!({ "type": "array", "items": { "type": "object" } }),
346                    ),
347                    ("reason", s()),
348                    ("dry_run", b()),
349                ],
350                &["ops"],
351                true,
352            ),
353        },
354        ToolSpec {
355            name: "blocks_insert",
356            description: "Insert blocks parsed from `markdown` under `to` (a block ref, or a document ref for its top level) at `at` (end|start|{before|after}).",
357            input_schema: schema(
358                &[
359                    ("to", s()),
360                    ("markdown", s()),
361                    ("at", at_schema()),
362                    ("dry_run", b()),
363                ],
364                &["to", "markdown"],
365                true,
366            ),
367        },
368        ToolSpec {
369            name: "blocks_update",
370            description: "Replace a block's markdown and/or set attrs (`checked` folds into attrs) with CAS pinned server-side when `expect` is omitted. Returns `id`, `ids` and the apply result.",
371            input_schema: schema(
372                &[
373                    ("block", s()),
374                    ("markdown", s()),
375                    ("checked", b()),
376                    ("attrs", obj()),
377                    ("expect", expect_schema()),
378                    ("dry_run", b()),
379                ],
380                &["block"],
381                true,
382            ),
383        },
384        ToolSpec {
385            name: "blocks_move",
386            description: "Move blocks under a new parent at a position; `to` is a block ref or the blocks' own document.",
387            input_schema: schema(
388                &[
389                    ("blocks", strings()),
390                    ("to", s()),
391                    ("at", at_schema()),
392                    ("dry_run", b()),
393                ],
394                &["blocks", "to"],
395                true,
396            ),
397        },
398        ToolSpec {
399            name: "blocks_remove",
400            description: "Remove blocks (and their subtrees).",
401            input_schema: schema(
402                &[("blocks", strings()), ("dry_run", b())],
403                &["blocks"],
404                true,
405            ),
406        },
407        ToolSpec {
408            name: "blocks_split",
409            description: "Split a block at UTF-8 byte offsets; CAS pinned server-side.",
410            input_schema: schema(
411                &[
412                    ("block", s()),
413                    (
414                        "at",
415                        json!({ "type": "array", "items": { "type": "integer" } }),
416                    ),
417                    ("dry_run", b()),
418                ],
419                &["block", "at"],
420                true,
421            ),
422        },
423        ToolSpec {
424            name: "blocks_merge",
425            description: "Merge adjacent blocks into the first, joined by `separator`.",
426            input_schema: schema(
427                &[("blocks", strings()), ("separator", s()), ("dry_run", b())],
428                &["blocks"],
429                true,
430            ),
431        },
432        ToolSpec {
433            name: "tasks_complete",
434            description: "Check (or uncheck with checked:false) task blocks.",
435            input_schema: schema(
436                &[("blocks", strings()), ("checked", b()), ("dry_run", b())],
437                &["blocks"],
438                true,
439            ),
440        },
441        ToolSpec {
442            name: "node_set",
443            description: "Set one editable property of a projected node (a link's name/value, a task's checked).",
444            input_schema: schema(
445                &[
446                    ("node", s()),
447                    ("prop", s()),
448                    ("value", s()),
449                    ("dry_run", b()),
450                ],
451                &["node", "prop", "value"],
452                true,
453            ),
454        },
455        ToolSpec {
456            name: "sections_append",
457            description: "Append markdown at the end of a heading's section; `heading` is a heading block id or its text (scoped by `doc`/`path`).",
458            input_schema: schema(
459                &[
460                    ("heading", s()),
461                    ("markdown", s()),
462                    ("doc", s()),
463                    ("path", s()),
464                    ("dry_run", b()),
465                ],
466                &["heading", "markdown"],
467                true,
468            ),
469        },
470        ToolSpec {
471            name: "docs_append",
472            description: "Append markdown at the end of a document as new top-level blocks (existing ids preserved).",
473            input_schema: schema(
474                &[("doc", s()), ("path", s()), ("text", s())],
475                &["text"],
476                true,
477            ),
478        },
479        ToolSpec {
480            name: "links_retarget",
481            description: "Rewrite one link destination everywhere it is linked (dry run by default).",
482            input_schema: schema(
483                &[
484                    ("from_target", s()),
485                    ("to_target", s()),
486                    ("path_glob", s()),
487                    ("dry_run", b()),
488                ],
489                &["from_target", "to_target"],
490                true,
491            ),
492        },
493        ToolSpec {
494            name: "links_stale",
495            description: "Dangling internal links (open edges to a `phantom:` target) plus external and total counts; `summary:true` returns counts only.",
496            input_schema: schema(
497                &[("path_glob", s()), ("limit", i()), ("summary", b())],
498                &[],
499                true,
500            ),
501        },
502        ToolSpec {
503            name: "links_repair",
504            description: "Bulk link repair: `repairs` ([{from,to}]) or one `from_target`/`to_target` pair, in one changeset (dry run by default).",
505            input_schema: schema(
506                &[
507                    (
508                        "repairs",
509                        json!({ "type": "array", "items": { "type": "object", "properties": { "from": { "type": "string" }, "to": { "type": "string" } }, "required": ["from", "to"] } }),
510                    ),
511                    ("from_target", s()),
512                    ("to_target", s()),
513                    ("path_glob", s()),
514                    ("dry_run", b()),
515                ],
516                &[],
517                true,
518            ),
519        },
520        ToolSpec {
521            name: "docs_create",
522            description: "Create a document at `path` from `markdown` with optional `frontmatter`.",
523            input_schema: schema(
524                &[("path", s()), ("markdown", s()), ("frontmatter", obj())],
525                &["path", "markdown"],
526                true,
527            ),
528        },
529        ToolSpec {
530            name: "docs_move",
531            description: "Rename a document to `to_path`, identity preserved; `retarget_inbound` rewrites inbound links.",
532            input_schema: schema(
533                &[("doc", s()), ("to_path", s()), ("retarget_inbound", b())],
534                &["doc", "to_path"],
535                true,
536            ),
537        },
538        ToolSpec {
539            name: "docs_delete",
540            description: "Delete a document: tombstone it and remove the file.",
541            input_schema: schema(&[("doc", s())], &["doc"], true),
542        },
543        ToolSpec {
544            name: "docs_set_meta",
545            description: "Set and/or unset frontmatter keys, re-ingesting the document.",
546            input_schema: schema(
547                &[("doc", s()), ("set", obj()), ("unset", strings())],
548                &["doc"],
549                true,
550            ),
551        },
552        ToolSpec {
553            name: "docs_plan_update",
554            description: "Plan a whole-document update without applying: the opset and a one-line-per-op plan.",
555            input_schema: schema(&[("doc", s()), ("content", s())], &["doc", "content"], true),
556        },
557        ToolSpec {
558            name: "docs_update",
559            description: "Whole-document update with identity preservation: plan then apply (`dry_run` returns the plan only).",
560            input_schema: schema(
561                &[
562                    ("doc", s()),
563                    ("content", s()),
564                    ("reason", s()),
565                    ("dry_run", b()),
566                ],
567                &["doc", "content"],
568                true,
569            ),
570        },
571        ToolSpec {
572            name: "observe",
573            description: "Record `content` as the authoritative bytes at `path` (an observed-origin commit; an echo when unchanged).",
574            input_schema: schema(
575                &[("path", s()), ("content", s())],
576                &["path", "content"],
577                true,
578            ),
579        },
580        ToolSpec {
581            name: "observe_many",
582            description: "Observe several files under one timestamp and one pool sweep.",
583            input_schema: schema(
584                &[(
585                    "files",
586                    json!({ "type": "array", "items": { "type": "object", "properties": { "path": { "type": "string" }, "content": { "type": "string" } }, "required": ["path", "content"] } }),
587                )],
588                &["files"],
589                true,
590            ),
591        },
592        ToolSpec {
593            name: "observe_delete",
594            description: "Record that `path` left the source: an observed, pooled tombstone.",
595            input_schema: schema(&[("path", s())], &["path"], true),
596        },
597        ToolSpec {
598            name: "history_node",
599            description: "A block's biography: the commits that touched it, newest first.",
600            input_schema: schema(&[("id", s()), ("limit", i())], &["id"], false),
601        },
602        ToolSpec {
603            name: "diff",
604            description: "Block-grain diff between two revisions of a document.",
605            input_schema: schema(
606                &[("doc", s()), ("from_rev", s()), ("to_rev", s())],
607                &["doc", "from_rev", "to_rev"],
608                true,
609            ),
610        },
611        ToolSpec {
612            name: "diff_unified",
613            description: "Line-based +/- diff between two revisions (default: the previous and current).",
614            input_schema: schema(
615                &[("doc", s()), ("from_rev", s()), ("to_rev", s())],
616                &["doc"],
617                true,
618            ),
619        },
620        ToolSpec {
621            name: "docs_read_at",
622            description: "The whole document as of a past revision.",
623            input_schema: dp(&[("rev", s())], &["rev"]),
624        },
625        ToolSpec {
626            name: "docs_history",
627            description: "Version history of the docs matching `path_glob` or `doc`, grouped by document.",
628            input_schema: schema(
629                &[
630                    ("path_glob", s()),
631                    ("doc", s()),
632                    ("include_deleted", b()),
633                    ("limit", i()),
634                ],
635                &[],
636                true,
637            ),
638        },
639        ToolSpec {
640            name: "changes_since",
641            description: "The change feed: commit digests after `cursor` (a repo commit seq).",
642            input_schema: schema(
643                &[
644                    ("cursor", i()),
645                    (
646                        "origin",
647                        json!({ "type": "string", "enum": ["api", "observed", "import"] }),
648                    ),
649                    ("limit", i()),
650                ],
651                &[],
652                true,
653            ),
654        },
655        ToolSpec {
656            name: "repos_status",
657            description: "Repo counts, unconverged docs and on-disk drift.",
658            input_schema: schema(&[], &[], true),
659        },
660        ToolSpec {
661            name: "sync_status",
662            description: "Sync state: last commit seq, last checkpoint, convergence.",
663            input_schema: schema(&[], &[], true),
664        },
665        ToolSpec {
666            name: "repos",
667            description: "The repos in this workspace: `{ repos: [{ slug, hasSource }] }`.",
668            input_schema: schema(&[], &[], false),
669        },
670    ]
671}
672
673impl Surface {
674    /// A surface over `store` whose default repo is `default_repo` (an id).
675    /// Mutations derive each repo's root from its `fs` source.
676    #[must_use]
677    pub fn new(
678        store: Store,
679        default_repo: &str,
680        provider: Option<Box<dyn EmbeddingProvider>>,
681    ) -> Self {
682        Self {
683            store,
684            default_repo: default_repo.to_owned(),
685            provider,
686            on_mutation: None,
687            clock: Box::new(omgbase_sync::now_ts),
688            writes: WriteTarget::Derived,
689            config: Config::default(),
690        }
691    }
692
693    /// Route every mutation's file writes through `doc_store` regardless of
694    /// the repo's sources (a runner's in-memory store).
695    #[must_use]
696    pub fn with_doc_store(mut self, doc_store: Box<dyn DocStore>) -> Self {
697        self.writes = WriteTarget::Fixed(doc_store);
698        self
699    }
700
701    /// Stamp commits with `clock()` instead of the wall clock.
702    #[must_use]
703    pub fn with_clock(mut self, clock: impl FnMut() -> String + 'static) -> Self {
704        self.clock = Box::new(clock);
705        self
706    }
707
708    /// Called after every successful write (never after a dry run).
709    #[must_use]
710    pub fn with_mutation_hook(mut self, hook: impl FnMut() + 'static) -> Self {
711        self.on_mutation = Some(Box::new(hook));
712        self
713    }
714
715    /// The matcher thresholds the observe tools pass through.
716    #[must_use]
717    pub fn with_config(mut self, config: Config) -> Self {
718        self.config = config;
719        self
720    }
721
722    #[must_use]
723    pub fn store(&self) -> &Store {
724        &self.store
725    }
726
727    pub fn store_mut(&mut self) -> &mut Store {
728        &mut self.store
729    }
730
731    #[must_use]
732    pub fn default_repo(&self) -> &str {
733        &self.default_repo
734    }
735
736    /// The catalog.
737    #[must_use]
738    pub fn tools(&self) -> Vec<ToolSpec> {
739        tools()
740    }
741
742    /// Run a tool: its JSON result, or the error envelope.
743    pub fn call(&mut self, name: &str, args: Json) -> ToolOutcome {
744        match self.call_result(name, &args) {
745            Ok(body) => ToolOutcome {
746                body,
747                is_error: false,
748            },
749            Err(e) => ToolOutcome {
750                body: e.to_json(),
751                is_error: true,
752            },
753        }
754    }
755
756    fn now(&mut self) -> String {
757        (self.clock)()
758    }
759
760    fn notify(&mut self) {
761        if let Some(hook) = &mut self.on_mutation {
762            hook();
763        }
764    }
765
766    // ---- repo scoping (§4) ------------------------------------------------------------
767
768    fn repo_rows(&self) -> Result<Vec<RepoRow>> {
769        Ok(omgbase_sync::workspace::list_repos(&self.store)?)
770    }
771
772    /// `(repo id, derived root)` for the `repo` argument; omitted → the default.
773    fn scope(&self, args: &Json) -> Result<(String, Option<String>)> {
774        let rows = self.repo_rows()?;
775        match arg_str(args, "repo") {
776            None => {
777                let root = rows
778                    .iter()
779                    .find(|r| r.repo_id == self.default_repo)
780                    .and_then(|r| r.root_path.clone());
781                Ok((self.default_repo.clone(), root))
782            }
783            Some(slug) => rows
784                .iter()
785                .find(|r| r.slug == slug)
786                .map(|r| (r.repo_id.clone(), r.root_path.clone()))
787                .ok_or_else(|| {
788                    SurfaceError::with_data(
789                        "repo_not_found",
790                        format!("no repo '{slug}' in this workspace"),
791                        json!({ "repo": slug }),
792                    )
793                }),
794        }
795    }
796
797    fn require_root(&self, root: Option<&str>) -> Result<()> {
798        if matches!(self.writes, WriteTarget::Fixed(_)) || root.is_some() {
799            Ok(())
800        } else {
801            Err(SurfaceError::new(
802                "repo_not_found",
803                "repo has no filesystem source; mutation disabled",
804            ))
805        }
806    }
807
808    /// Run `f` with the store and the write target for `root`.
809    fn with_writes<T>(
810        &mut self,
811        root: Option<&str>,
812        f: impl FnOnce(&mut Store, &mut dyn DocStore) -> Result<T>,
813    ) -> Result<T> {
814        self.require_root(root)?;
815        match &mut self.writes {
816            WriteTarget::Fixed(ds) => f(&mut self.store, ds.as_mut()),
817            WriteTarget::Derived => {
818                let mut fs = FsDocStore::new(root.expect("checked by require_root"));
819                f(&mut self.store, &mut fs)
820            }
821        }
822    }
823
824    // ---- ref resolution (§4) ---------------------------------------------------------
825
826    /// The owning doc from `doc` (id or path) / `path` / `block`; `doc_missing` when none.
827    fn resolve_doc_id(
828        &self,
829        repo_id: &str,
830        doc: Option<&str>,
831        path: Option<&str>,
832        block: Option<&str>,
833    ) -> Result<String> {
834        let conn = self.store.conn();
835        let found = if let Some(d) = doc.filter(|d| !d.is_empty()) {
836            read::find_doc_by_ref(conn, repo_id, d)?.map(|i| i.doc_id)
837        } else if let Some(p) = path.filter(|p| !p.is_empty()) {
838            read::find_doc_by_path(conn, repo_id, p)?.map(|i| i.doc_id)
839        } else if let Some(b) = block.filter(|b| !b.is_empty()) {
840            conn.query_row(
841                "SELECT doc_id FROM blocks WHERE block_id = ?1",
842                params![b],
843                |r| r.get::<_, String>(0),
844            )
845            .optional()?
846        } else {
847            None
848        };
849        found.ok_or_else(|| {
850            let mut m = Map::new();
851            if let Some(d) = doc {
852                m.insert("doc".to_owned(), json!(d));
853            }
854            if let Some(p) = path {
855                m.insert("path".to_owned(), json!(p));
856            }
857            if let Some(b) = block {
858                m.insert("block".to_owned(), json!(b));
859            }
860            SurfaceError::with_data(
861                "doc_missing",
862                format!("no document for {}", Json::Object(m.clone())),
863                Json::Object(m),
864            )
865        })
866    }
867
868    fn resolve_doc_from_args(&self, repo_id: &str, args: &Json) -> Result<String> {
869        self.resolve_doc_id(repo_id, arg_str(args, "doc"), arg_str(args, "path"), None)
870    }
871
872    /// `heading` (a heading block id or heading text) → the heading block id.
873    fn resolve_heading_id(
874        &self,
875        repo_id: &str,
876        heading: &str,
877        doc: Option<&str>,
878        path: Option<&str>,
879    ) -> Result<String> {
880        let conn = self.store.conn();
881        let as_block: Option<String> = conn
882            .query_row(
883                "SELECT block_id FROM blocks WHERE block_id = ?1 AND type = 'heading' AND deleted_commit IS NULL",
884                params![heading],
885                |r| r.get(0),
886            )
887            .optional()?;
888        if let Some(b) = as_block {
889            return Ok(b);
890        }
891        let want_doc = if doc.is_some_and(|d| !d.is_empty()) || path.is_some_and(|p| !p.is_empty())
892        {
893            Some(self.resolve_doc_id(repo_id, doc, path, None)?)
894        } else {
895            None
896        };
897        let needle = if heading.trim_start_matches([' ', '\t']).starts_with('#') {
898            normalize_visible_text(heading, BlockKind::Heading, 0)
899        } else {
900            normalize_text(heading)
901        };
902        let rows: Vec<(String, String, String)> = match &want_doc {
903            Some(d) => {
904                let mut stmt = conn.prepare(
905                    "SELECT block_id, doc_id, text FROM blocks WHERE repo_id = ?1 AND type = 'heading' AND doc_id = ?2 AND deleted_commit IS NULL",
906                )?;
907                let it = stmt.query_map(params![repo_id, d], |r| {
908                    Ok((r.get(0)?, r.get(1)?, r.get(2)?))
909                })?;
910                it.collect::<std::result::Result<_, _>>()?
911            }
912            None => {
913                let mut stmt = conn.prepare(
914                    "SELECT block_id, doc_id, text FROM blocks WHERE repo_id = ?1 AND type = 'heading' AND deleted_commit IS NULL",
915                )?;
916                let it =
917                    stmt.query_map(params![repo_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?;
918                it.collect::<std::result::Result<_, _>>()?
919            }
920        };
921        let matches: Vec<&(String, String, String)> = rows
922            .iter()
923            .filter(|(_, _, text)| normalize_text(text) == needle)
924            .collect();
925        match matches.len() {
926            0 => {
927                let mut data = Map::new();
928                data.insert("heading".to_owned(), json!(heading));
929                if let Some(d) = want_doc {
930                    data.insert("doc".to_owned(), json!(d));
931                }
932                Err(SurfaceError::with_data(
933                    "parent_missing",
934                    format!("no heading matching {}", Json::String(heading.to_owned())),
935                    Json::Object(data),
936                ))
937            }
938            1 => Ok(matches[0].0.clone()),
939            n => Err(SurfaceError::with_data(
940                "ambiguous_heading",
941                format!(
942                    "heading {} matches {n} headings; pass its block id or a doc/path scope",
943                    Json::String(heading.to_owned())
944                ),
945                json!({
946                    "heading": heading,
947                    "candidates": matches.iter().map(|(b, d, _)| json!({ "block": b, "doc": d })).collect::<Vec<_>>(),
948                }),
949            )),
950        }
951    }
952
953    /// A ref → a live block id (`block_missing` otherwise).
954    fn resolve_block_ref(&self, repo_id: &str, r: &str) -> Result<String> {
955        match read::resolve_ref(self.store.conn(), repo_id, r)? {
956            Some(ResolvedRef::Block { block_id, .. }) => Ok(block_id),
957            _ => Err(SurfaceError::with_data(
958                "block_missing",
959                format!("not a block: {r}"),
960                json!({ "ref": r }),
961            )),
962        }
963    }
964
965    /// A parent ref: a block, or a document ref for its top level.
966    fn resolve_parent_ref(&self, repo_id: &str, r: &str) -> Result<(Parent, String)> {
967        match read::resolve_ref(self.store.conn(), repo_id, r)? {
968            Some(ResolvedRef::Block { doc_id, block_id }) => Ok((Parent::Block(block_id), doc_id)),
969            Some(ResolvedRef::Document { doc_id }) => Ok((Parent::Doc, doc_id)),
970            None => Err(SurfaceError::with_data(
971                "block_missing",
972                format!("not a block or document: {r}"),
973                json!({ "ref": r }),
974            )),
975        }
976    }
977
978    fn doc_id_of_block(&self, block_id: &str) -> Result<Option<String>> {
979        Ok(self
980            .store
981            .conn()
982            .query_row(
983                "SELECT doc_id FROM blocks WHERE block_id = ?1 AND deleted_commit IS NULL",
984                params![block_id],
985                |r| r.get(0),
986            )
987            .optional()?)
988    }
989
990    /// The live block's raw hash (hex) for CAS pinning; `None` when unknown.
991    fn pin_hash(&self, block_id: &str) -> Result<Option<String>> {
992        let h: Option<Vec<u8>> = self
993            .store
994            .conn()
995            .query_row(
996                "SELECT raw_hash FROM blocks WHERE block_id = ?1 AND deleted_commit IS NULL",
997                params![block_id],
998                |r| r.get(0),
999            )
1000            .optional()?;
1001        Ok(h.map(|h| omgbase_format::hash::hex(&h)))
1002    }
1003
1004    /// The `at` spec with its anchor ref resolved; absent → end.
1005    fn resolve_at(&self, repo_id: &str, at: Option<&Json>) -> Result<At> {
1006        match at {
1007            None | Some(Json::Null) => Ok(At::End),
1008            Some(Json::String(s)) if s == "start" => Ok(At::Start),
1009            Some(Json::String(s)) if s == "end" => Ok(At::End),
1010            Some(Json::Object(o)) => {
1011                if let Some(b) = o.get("before").and_then(Json::as_str) {
1012                    return Ok(At::Before(self.resolve_block_ref(repo_id, b)?));
1013                }
1014                if let Some(a) = o.get("after").and_then(Json::as_str) {
1015                    return Ok(At::After(self.resolve_block_ref(repo_id, a)?));
1016                }
1017                Err(bad_args(
1018                    "`at` must be \"start\", \"end\", {before} or {after}",
1019                ))
1020            }
1021            Some(_) => Err(bad_args(
1022                "`at` must be \"start\", \"end\", {before} or {after}",
1023            )),
1024        }
1025    }
1026
1027    // ---- the apply tail -----------------------------------------------------------------
1028
1029    fn apply_ops(
1030        &mut self,
1031        repo_id: &str,
1032        root: Option<&str>,
1033        ops: Vec<Op>,
1034        reason: &str,
1035        dry_run: bool,
1036    ) -> Result<ApplyResult> {
1037        let ts = self.now();
1038        let req = ApplyRequest {
1039            repo_id: repo_id.to_owned(),
1040            ops,
1041            origin: ApplyOrigin::new(ACTOR, Some(reason)),
1042            dry_run,
1043            set_frontmatter: Vec::new(),
1044        };
1045        let res = self.with_writes(root, |store, ds| Ok(store.apply(&req, ds, &ts)?))?;
1046        if !dry_run {
1047            self.notify();
1048        }
1049        Ok(res)
1050    }
1051
1052    fn doc_ctx(&mut self, repo_id: &str) -> DocOpContext {
1053        DocOpContext {
1054            repo_id: repo_id.to_owned(),
1055            actor: Some(ACTOR.to_owned()),
1056            ts: self.now(),
1057        }
1058    }
1059
1060    // ---- dispatch -------------------------------------------------------------------------
1061
1062    /// Run a tool, returning its result or the error.
1063    #[allow(clippy::too_many_lines)]
1064    pub fn call_result(&mut self, name: &str, args: &Json) -> Result<Json> {
1065        match name {
1066            "docs_outline" => {
1067                let (repo, _) = self.scope(args)?;
1068                let doc_id = self.resolve_doc_from_args(&repo, args)?;
1069                let skeleton = match arg_str(args, "resolution") {
1070                    None | Some("outline") => false,
1071                    Some("skeleton") => true,
1072                    Some(_) => return Err(bad_args("`resolution` must be skeleton or outline")),
1073                };
1074                read::docs_outline(
1075                    &self.store,
1076                    &doc_id,
1077                    skeleton,
1078                    arg_i64(args, "depth")?,
1079                    arg_usize(args, "budget_tokens")?,
1080                )
1081            }
1082            "docs_read" => {
1083                let (repo, _) = self.scope(args)?;
1084                let doc_id = self.resolve_doc_from_args(&repo, args)?;
1085                read::docs_read(
1086                    &self.store,
1087                    &doc_id,
1088                    arg_bool(args, "include_ids")?.unwrap_or(false),
1089                )?
1090                .ok_or_else(|| SurfaceError::new("doc_missing", format!("no document for {args}")))
1091            }
1092            "docs_get_many" => {
1093                let (repo, _) = self.scope(args)?;
1094                let refs = arg_strings(args, "docs")?;
1095                read::docs_read_many(
1096                    &self.store,
1097                    &repo,
1098                    &refs,
1099                    arg_bool(args, "include_ids")?.unwrap_or(false),
1100                    arg_usize(args, "budget_tokens")?,
1101                )
1102            }
1103            "nodes_get" => {
1104                let (repo, _) = self.scope(args)?;
1105                let id = arg_string(args, "id")?;
1106                let doc_id = self.resolve_doc_id(
1107                    &repo,
1108                    arg_str(args, "doc"),
1109                    arg_str(args, "path"),
1110                    Some(&id),
1111                )?;
1112                read::nodes_get(
1113                    &self.store,
1114                    &doc_id,
1115                    &id,
1116                    resolution_arg(args, Resolution::Full)?,
1117                )?
1118                .ok_or_else(|| SurfaceError::new("block_missing", format!("no block {id}")))
1119            }
1120            "nodes_get_many" => {
1121                let (repo, _) = self.scope(args)?;
1122                let ids = arg_strings(args, "ids")?;
1123                let scoped = arg_str(args, "doc").is_some_and(|d| !d.is_empty())
1124                    || arg_str(args, "path").is_some_and(|p| !p.is_empty());
1125                let doc_id = if scoped {
1126                    Some(self.resolve_doc_from_args(&repo, args)?)
1127                } else {
1128                    None
1129                };
1130                read::nodes_get_many(
1131                    &self.store,
1132                    doc_id.as_deref(),
1133                    &ids,
1134                    resolution_arg(args, Resolution::Text)?,
1135                    arg_usize(args, "budget_tokens")?,
1136                )
1137            }
1138            "read_ref" => {
1139                let (repo, _) = self.scope(args)?;
1140                let r = arg_string(args, "ref")?;
1141                let resolved =
1142                    read::resolve_ref(self.store.conn(), &repo, &r)?.ok_or_else(|| {
1143                        SurfaceError::new(
1144                            "doc_missing",
1145                            format!("no document or block for {}", Json::String(r.clone())),
1146                        )
1147                    })?;
1148                match resolved {
1149                    ResolvedRef::Document { doc_id } => {
1150                        let res =
1151                            read::docs_read(&self.store, &doc_id, false)?.ok_or_else(|| {
1152                                SurfaceError::new(
1153                                    "doc_missing",
1154                                    format!("no document for {}", Json::String(r.clone())),
1155                                )
1156                            })?;
1157                        let mut m = Map::new();
1158                        m.insert("kind".to_owned(), json!("document"));
1159                        Ok(merge(m, res))
1160                    }
1161                    ResolvedRef::Block { doc_id, block_id } => {
1162                        let node = read::nodes_get(
1163                            &self.store,
1164                            &doc_id,
1165                            &block_id,
1166                            resolution_arg(args, Resolution::Raw)?,
1167                        )?
1168                        .ok_or_else(|| {
1169                            SurfaceError::new("block_missing", format!("no block {block_id}"))
1170                        })?;
1171                        let mut m = Map::new();
1172                        m.insert("kind".to_owned(), json!("block"));
1173                        Ok(merge(m, node))
1174                    }
1175                }
1176            }
1177            "docs_tree" => {
1178                let (repo, _) = self.scope(args)?;
1179                read::docs_tree(
1180                    &self.store,
1181                    &repo,
1182                    arg_str(args, "path"),
1183                    arg_i64(args, "depth")?,
1184                    arg_i64(args, "limit")?,
1185                    arg_str(args, "cursor"),
1186                    arg_usize(args, "budget_tokens")?,
1187                )
1188            }
1189            "docs_list" => {
1190                let (repo, _) = self.scope(args)?;
1191                read::docs_list(
1192                    &self.store,
1193                    &repo,
1194                    arg_str(args, "path_glob"),
1195                    arg_i64(args, "limit")?,
1196                    arg_str(args, "cursor"),
1197                    arg_usize(args, "budget_tokens")?,
1198                )
1199            }
1200            "query_syntax" => Ok(json!({ "syntax": QUERY_SYNTAX })),
1201            "query" => {
1202                let (repo, _) = self.scope(args)?;
1203                let source = arg_string(args, "query")?;
1204                // A `semantic(...)` query with no provider is `semantic_unavailable`
1205                // here (the runner itself reports `filter_invalid`, §9).
1206                if self.provider.is_none()
1207                    && !crate::query::collect_semantic_phrases(&source).is_empty()
1208                {
1209                    return Err(SurfaceError::new(
1210                        "semantic_unavailable",
1211                        "no embedding provider configured for this server",
1212                    ));
1213                }
1214                let opts = QueryOptions {
1215                    limit: arg_usize(args, "limit")?,
1216                    cursor: arg_str(args, "cursor"),
1217                    provider: self.provider.as_deref(),
1218                };
1219                Ok(query(&self.store, &repo, &source, opts)?.to_json())
1220            }
1221            "graph" => {
1222                let (repo, _) = self.scope(args)?;
1223                let g = GraphArgs {
1224                    roots: arg_strings(args, "roots")?,
1225                    degrees: arg_i64(args, "degrees")?,
1226                    direction: arg_str(args, "direction").map(str::to_owned),
1227                    predicate: arg_str(args, "predicate").map(str::to_owned),
1228                    select: if args.get("select").is_some() {
1229                        arg_strings(args, "select")?
1230                    } else {
1231                        Vec::new()
1232                    },
1233                    max_documents: arg_i64(args, "max_documents")?,
1234                };
1235                if self.provider.is_none()
1236                    && g.select.iter().any(|s| {
1237                        !crate::query::collect_semantic_phrases(&format!("from docs select x: {s}"))
1238                            .is_empty()
1239                    })
1240                {
1241                    return Err(SurfaceError::new(
1242                        "semantic_unavailable",
1243                        "no embedding provider configured for this server",
1244                    ));
1245                }
1246                graph_neighborhood(&self.store, &repo, &g, self.provider.as_deref())
1247            }
1248            "text_search" => {
1249                let (repo, _) = self.scope(args)?;
1250                let q = arg_string(args, "q")?;
1251                let res =
1252                    self.store
1253                        .text_search(&repo, &q, arg_usize(args, "limit")?.unwrap_or(50))?;
1254                Ok(json!({
1255                    "hits": res.hits.iter().map(|h| json!({
1256                        "blockId": h.block_id, "docId": h.doc_id, "path": h.path, "type": h.block_type, "text": h.text, "score": h.score,
1257                    })).collect::<Vec<_>>(),
1258                    "truncated": res.truncated,
1259                }))
1260            }
1261            "resolve" => {
1262                let (repo, _) = self.scope(args)?;
1263                let q = arg_string(args, "query")?;
1264                let vector = match &self.provider {
1265                    Some(p) => Some(QueryVector {
1266                        model: p.model().to_owned(),
1267                        vec: p
1268                            .embed_query(&q)
1269                            .map_err(|e| SurfaceError::new(e.code(), e.to_string()))?,
1270                    }),
1271                    None => None,
1272                };
1273                let hits = self
1274                    .store
1275                    .resolve(&repo, &q, vector, arg_usize(args, "limit")?)?;
1276                Ok(Json::Array(hits.iter().map(|h| json!({
1277                    "id": h.id, "locator": h.locator, "preview": h.preview, "evidence": evidence_json(&h.evidence),
1278                })).collect()))
1279            }
1280            "apply" => {
1281                let (repo, root) = self.scope(args)?;
1282                self.require_root(root.as_deref())?;
1283                let ops = args
1284                    .get("ops")
1285                    .and_then(Json::as_array)
1286                    .ok_or_else(|| bad_args("`ops` must be an array"))?;
1287                let ops: Vec<Op> = ops
1288                    .iter()
1289                    .map(|o| Op::from_json(o).map_err(bad_args))
1290                    .collect::<Result<_>>()?;
1291                let dry = arg_bool(args, "dry_run")?.unwrap_or(false);
1292                let reason = arg_str(args, "reason").map(str::to_owned);
1293                let ts = self.now();
1294                let req = ApplyRequest {
1295                    repo_id: repo.clone(),
1296                    ops,
1297                    origin: ApplyOrigin::new(ACTOR, reason.as_deref()),
1298                    dry_run: dry,
1299                    set_frontmatter: Vec::new(),
1300                };
1301                let res =
1302                    self.with_writes(root.as_deref(), |store, ds| Ok(store.apply(&req, ds, &ts)?))?;
1303                if !dry {
1304                    self.notify();
1305                }
1306                Ok(apply_json(&res))
1307            }
1308            "blocks_insert" => {
1309                let (repo, root) = self.scope(args)?;
1310                self.require_root(root.as_deref())?;
1311                let (parent, doc_id) = self.resolve_parent_ref(&repo, &arg_string(args, "to")?)?;
1312                let at = self.resolve_at(&repo, args.get("at"))?;
1313                let doc = if parent == Parent::Doc {
1314                    Some(doc_id)
1315                } else {
1316                    None
1317                };
1318                let ops = vec![Op::Insert {
1319                    doc,
1320                    to: To { parent, at },
1321                    markdown: arg_string(args, "markdown")?,
1322                }];
1323                Ok(apply_json(&self.apply_ops(
1324                    &repo,
1325                    root.as_deref(),
1326                    ops,
1327                    "blocks_insert",
1328                    arg_bool(args, "dry_run")?.unwrap_or(false),
1329                )?))
1330            }
1331            "blocks_update" => {
1332                let (repo, root) = self.scope(args)?;
1333                self.require_root(root.as_deref())?;
1334                let block = self.resolve_block_ref(&repo, &arg_string(args, "block")?)?;
1335                let expect = match arg_object(args, "expect")? {
1336                    Some(e) => Some(Expect {
1337                        content_hash: e
1338                            .get("content_hash")
1339                            .and_then(Json::as_str)
1340                            .map(str::to_owned),
1341                        parent_children_hash: e
1342                            .get("parent_children_hash")
1343                            .and_then(Json::as_str)
1344                            .map(str::to_owned),
1345                    }),
1346                    None => self.pin_hash(&block)?.map(Expect::content),
1347                };
1348                let checked = arg_bool(args, "checked")?;
1349                let extra = arg_object(args, "attrs")?;
1350                let attrs = if checked.is_some() || extra.is_some() {
1351                    let mut a = Map::new();
1352                    if let Some(c) = checked {
1353                        a.insert("checked".to_owned(), json!(c));
1354                    }
1355                    if let Some(x) = extra {
1356                        for (k, v) in x {
1357                            a.insert(k.clone(), v.clone());
1358                        }
1359                    }
1360                    Some(a)
1361                } else {
1362                    None
1363                };
1364                let ops = vec![Op::Update {
1365                    block: block.clone(),
1366                    markdown: arg_str(args, "markdown").map(str::to_owned),
1367                    attrs,
1368                    expect,
1369                    trivia: None,
1370                    child_ids: None,
1371                }];
1372                let dry = arg_bool(args, "dry_run")?.unwrap_or(false);
1373                let res = self.apply_ops(&repo, root.as_deref(), ops, "blocks_update", dry)?;
1374                let ids: Vec<String> = res
1375                    .results
1376                    .first()
1377                    .map_or_else(|| vec![block.clone()], |r| r.ids.clone());
1378                let mut m = Map::new();
1379                m.insert(
1380                    "id".to_owned(),
1381                    json!(ids.first().cloned().unwrap_or(block)),
1382                );
1383                m.insert("ids".to_owned(), json!(ids));
1384                Ok(merge(m, apply_json(&res)))
1385            }
1386            "blocks_move" => {
1387                let (repo, root) = self.scope(args)?;
1388                self.require_root(root.as_deref())?;
1389                let blocks: Vec<String> = arg_strings(args, "blocks")?
1390                    .iter()
1391                    .map(|b| self.resolve_block_ref(&repo, b))
1392                    .collect::<Result<_>>()?;
1393                let to_ref = arg_string(args, "to")?;
1394                let (parent, doc_id) = self.resolve_parent_ref(&repo, &to_ref)?;
1395                if parent == Parent::Doc {
1396                    if let Some(first) = blocks.first() {
1397                        if self.doc_id_of_block(first)? != Some(doc_id) {
1398                            return Err(SurfaceError::with_data(
1399                                "target_missing",
1400                                format!(
1401                                    "blocks_move cannot target another document's root ({to_ref}); anchor on a block in that document with at.before/at.after"
1402                                ),
1403                                json!({ "to": to_ref }),
1404                            ));
1405                        }
1406                    }
1407                }
1408                let at = self.resolve_at(&repo, args.get("at"))?;
1409                let ops = vec![Op::Move {
1410                    blocks,
1411                    to: To { parent, at },
1412                }];
1413                Ok(apply_json(&self.apply_ops(
1414                    &repo,
1415                    root.as_deref(),
1416                    ops,
1417                    "blocks_move",
1418                    arg_bool(args, "dry_run")?.unwrap_or(false),
1419                )?))
1420            }
1421            "blocks_remove" => {
1422                let (repo, root) = self.scope(args)?;
1423                self.require_root(root.as_deref())?;
1424                let blocks: Vec<String> = arg_strings(args, "blocks")?
1425                    .iter()
1426                    .map(|b| self.resolve_block_ref(&repo, b))
1427                    .collect::<Result<_>>()?;
1428                let ops = vec![Op::Remove {
1429                    blocks,
1430                    expect: None,
1431                }];
1432                Ok(apply_json(&self.apply_ops(
1433                    &repo,
1434                    root.as_deref(),
1435                    ops,
1436                    "blocks_remove",
1437                    arg_bool(args, "dry_run")?.unwrap_or(false),
1438                )?))
1439            }
1440            "blocks_split" => {
1441                let (repo, root) = self.scope(args)?;
1442                self.require_root(root.as_deref())?;
1443                let block = self.resolve_block_ref(&repo, &arg_string(args, "block")?)?;
1444                let at: Vec<usize> = args
1445                    .get("at")
1446                    .and_then(Json::as_array)
1447                    .ok_or_else(|| bad_args("`at` must be an array of byte offsets"))?
1448                    .iter()
1449                    .map(|v| {
1450                        v.as_u64()
1451                            .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
1452                            .ok_or_else(|| bad_args("`at` must be an array of byte offsets"))
1453                    })
1454                    .collect::<Result<_>>()?;
1455                // §9: an empty hash when the block has no live row.
1456                let expect = Some(Expect::content(self.pin_hash(&block)?.unwrap_or_default()));
1457                let ops = vec![Op::Split { block, at, expect }];
1458                Ok(apply_json(&self.apply_ops(
1459                    &repo,
1460                    root.as_deref(),
1461                    ops,
1462                    "blocks_split",
1463                    arg_bool(args, "dry_run")?.unwrap_or(false),
1464                )?))
1465            }
1466            "blocks_merge" => {
1467                let (repo, root) = self.scope(args)?;
1468                self.require_root(root.as_deref())?;
1469                let blocks: Vec<String> = arg_strings(args, "blocks")?
1470                    .iter()
1471                    .map(|b| self.resolve_block_ref(&repo, b))
1472                    .collect::<Result<_>>()?;
1473                let ops = vec![Op::Merge {
1474                    blocks,
1475                    separator: arg_str(args, "separator").map(str::to_owned),
1476                    expect: None,
1477                }];
1478                Ok(apply_json(&self.apply_ops(
1479                    &repo,
1480                    root.as_deref(),
1481                    ops,
1482                    "blocks_merge",
1483                    arg_bool(args, "dry_run")?.unwrap_or(false),
1484                )?))
1485            }
1486            "tasks_complete" => {
1487                let (repo, root) = self.scope(args)?;
1488                self.require_root(root.as_deref())?;
1489                let blocks: Vec<String> = arg_strings(args, "blocks")?
1490                    .iter()
1491                    .map(|b| self.resolve_block_ref(&repo, b))
1492                    .collect::<Result<_>>()?;
1493                let ops = if arg_bool(args, "checked")?.unwrap_or(true) {
1494                    self.store.tasks_complete(&blocks)?
1495                } else {
1496                    let mut ops = Vec::with_capacity(blocks.len());
1497                    for b in &blocks {
1498                        let mut a = Map::new();
1499                        a.insert("checked".to_owned(), json!(false));
1500                        ops.push(Op::Update {
1501                            block: b.clone(),
1502                            markdown: None,
1503                            attrs: Some(a),
1504                            expect: self.pin_hash(b)?.map(Expect::content),
1505                            trivia: None,
1506                            child_ids: None,
1507                        });
1508                    }
1509                    ops
1510                };
1511                Ok(apply_json(&self.apply_ops(
1512                    &repo,
1513                    root.as_deref(),
1514                    ops,
1515                    "tasks_complete",
1516                    arg_bool(args, "dry_run")?.unwrap_or(false),
1517                )?))
1518            }
1519            "node_set" => {
1520                let (repo, root) = self.scope(args)?;
1521                self.require_root(root.as_deref())?;
1522                let ops = self.store.node_set(
1523                    &arg_string(args, "node")?,
1524                    &arg_string(args, "prop")?,
1525                    &arg_string(args, "value")?,
1526                )?;
1527                Ok(apply_json(&self.apply_ops(
1528                    &repo,
1529                    root.as_deref(),
1530                    ops,
1531                    "node_set",
1532                    arg_bool(args, "dry_run")?.unwrap_or(false),
1533                )?))
1534            }
1535            "sections_append" => {
1536                let (repo, root) = self.scope(args)?;
1537                self.require_root(root.as_deref())?;
1538                let heading = self.resolve_heading_id(
1539                    &repo,
1540                    &arg_string(args, "heading")?,
1541                    arg_str(args, "doc"),
1542                    arg_str(args, "path"),
1543                )?;
1544                let ops = Store::sections_append(&heading, &arg_string(args, "markdown")?);
1545                Ok(apply_json(&self.apply_ops(
1546                    &repo,
1547                    root.as_deref(),
1548                    ops,
1549                    "sections_append",
1550                    arg_bool(args, "dry_run")?.unwrap_or(false),
1551                )?))
1552            }
1553            "docs_append" => {
1554                let (repo, root) = self.scope(args)?;
1555                self.require_root(root.as_deref())?;
1556                let doc_id = self.resolve_doc_from_args(&repo, args)?;
1557                let ops = Store::docs_append(&doc_id, &arg_string(args, "text")?);
1558                Ok(apply_json(&self.apply_ops(
1559                    &repo,
1560                    root.as_deref(),
1561                    ops,
1562                    "docs_append",
1563                    false,
1564                )?))
1565            }
1566            "links_retarget" | "links_repair" => {
1567                let (repo, root) = self.scope(args)?;
1568                self.require_root(root.as_deref())?;
1569                let repairs: Vec<omgbase_store::LinkRepair> = if name == "links_retarget" {
1570                    vec![omgbase_store::LinkRepair {
1571                        from: arg_string(args, "from_target")?,
1572                        to: arg_string(args, "to_target")?,
1573                    }]
1574                } else if let Some(list) = args.get("repairs").and_then(Json::as_array) {
1575                    list.iter()
1576                        .map(|r| {
1577                            Ok(omgbase_store::LinkRepair {
1578                                from: arg_string(r, "from")?,
1579                                to: arg_string(r, "to")?,
1580                            })
1581                        })
1582                        .collect::<Result<_>>()?
1583                } else if let (Some(f), Some(t)) =
1584                    (arg_str(args, "from_target"), arg_str(args, "to_target"))
1585                {
1586                    vec![omgbase_store::LinkRepair {
1587                        from: f.to_owned(),
1588                        to: t.to_owned(),
1589                    }]
1590                } else {
1591                    Vec::new()
1592                };
1593                if repairs.is_empty() {
1594                    return Err(SurfaceError::new(
1595                        "target_missing",
1596                        "links_repair requires `repairs` (array of {from,to}) or a `from_target`+`to_target` pair",
1597                    ));
1598                }
1599                let plan = self.store.links_repair(
1600                    &repo,
1601                    &repairs,
1602                    arg_str(args, "path_glob").filter(|g| !g.is_empty()),
1603                )?;
1604                let dry = arg_bool(args, "dry_run")?.unwrap_or(true);
1605                let res = self.apply_ops(&repo, root.as_deref(), plan.ops.clone(), name, dry)?;
1606                let mut m = Map::new();
1607                m.insert(
1608                    "hits".to_owned(),
1609                    Json::Array(plan.hits.iter().map(|h| json!({ "block": h.block, "path": h.path, "oldRaw": h.old_raw, "newRaw": h.new_raw })).collect()),
1610                );
1611                m.insert(
1612                    "pairs".to_owned(),
1613                    Json::Array(
1614                        plan.pairs
1615                            .iter()
1616                            .map(|p| json!({ "from": p.from, "to": p.to, "hits": p.hits }))
1617                            .collect(),
1618                    ),
1619                );
1620                m.insert("applied".to_owned(), json!(!dry));
1621                Ok(merge(m, apply_json(&res)))
1622            }
1623            "links_stale" => {
1624                let (repo, _) = self.scope(args)?;
1625                let glob = arg_str(args, "path_glob").filter(|g| !g.is_empty());
1626                if arg_bool(args, "summary")?.unwrap_or(false) {
1627                    return links::links_stale_summary(&self.store, &repo, glob);
1628                }
1629                links::links_stale(&self.store, &repo, glob, arg_i64(args, "limit")?)
1630            }
1631            "docs_create" => {
1632                let (repo, root) = self.scope(args)?;
1633                let ctx = self.doc_ctx(&repo);
1634                let path = arg_string(args, "path")?;
1635                let markdown = arg_string(args, "markdown")?;
1636                let fm = arg_object(args, "frontmatter")?.cloned();
1637                let res = self.with_writes(root.as_deref(), |store, ds| {
1638                    Ok(store.docs_create(&ctx, ds, &path, &markdown, fm.as_ref())?)
1639                })?;
1640                self.notify();
1641                Ok(doc_op_json(&res))
1642            }
1643            "docs_move" => {
1644                let (repo, root) = self.scope(args)?;
1645                let ctx = self.doc_ctx(&repo);
1646                let doc = arg_string(args, "doc")?;
1647                let to = arg_string(args, "to_path")?;
1648                let retarget = arg_bool(args, "retarget_inbound")?.unwrap_or(false);
1649                let res = self.with_writes(root.as_deref(), |store, ds| {
1650                    Ok(store.docs_move(&ctx, ds, &doc, &to, retarget)?)
1651                })?;
1652                self.notify();
1653                Ok(json!({
1654                    "docId": res.doc_id,
1655                    "path": res.path,
1656                    "committed": res.committed,
1657                    "dangling": res.dangling.iter().map(omgbase_store::InboundLink::to_json).collect::<Vec<_>>(),
1658                    "retargeted": res.retargeted.as_ref().map(|r| json!({ "blocks": r.blocks, "docs": r.docs })),
1659                }))
1660            }
1661            "docs_delete" => {
1662                let (repo, root) = self.scope(args)?;
1663                let ctx = self.doc_ctx(&repo);
1664                let doc = arg_string(args, "doc")?;
1665                let res = self.with_writes(root.as_deref(), |store, ds| {
1666                    Ok(store.docs_delete(&ctx, ds, &doc)?)
1667                })?;
1668                self.notify();
1669                Ok(doc_op_json(&res))
1670            }
1671            "docs_set_meta" => {
1672                let (repo, root) = self.scope(args)?;
1673                let ctx = self.doc_ctx(&repo);
1674                let doc = arg_string(args, "doc")?;
1675                let set = arg_object(args, "set")?.cloned();
1676                let unset = if args.get("unset").is_some() {
1677                    arg_strings(args, "unset")?
1678                } else {
1679                    Vec::new()
1680                };
1681                let res = self.with_writes(root.as_deref(), |store, ds| {
1682                    Ok(store.docs_set_meta(&ctx, ds, &doc, set.as_ref(), &unset)?)
1683                })?;
1684                self.notify();
1685                Ok(doc_op_json(&res))
1686            }
1687            "docs_plan_update" => {
1688                let (repo, root) = self.scope(args)?;
1689                self.require_root(root.as_deref())?;
1690                let doc = arg_string(args, "doc")?;
1691                let content = arg_string(args, "content")?;
1692                let opset = self
1693                    .store
1694                    .plan_update(&repo, &doc, &content, &self.config.clone())?;
1695                Ok(json!({ "opset": opset_json(&opset), "plan": render_opset_plan(&opset) }))
1696            }
1697            "docs_update" => {
1698                let (repo, root) = self.scope(args)?;
1699                let doc = arg_string(args, "doc")?;
1700                let content = arg_string(args, "content")?;
1701                let dry = arg_bool(args, "dry_run")?.unwrap_or(false);
1702                let reason = arg_str(args, "reason").map(str::to_owned);
1703                let origin = ApplyOrigin::new(ACTOR, reason.as_deref());
1704                let config = self.config.clone();
1705                let ts = self.now();
1706                let (opset, result) = self.with_writes(root.as_deref(), |store, ds| {
1707                    Ok(store.docs_update(&repo, &doc, &content, &config, &origin, dry, ds, &ts)?)
1708                })?;
1709                if !dry {
1710                    self.notify();
1711                }
1712                Ok(json!({
1713                    "opset": opset_json(&opset),
1714                    "plan": render_opset_plan(&opset),
1715                    "result": result.map(|r| apply_json(&r)),
1716                }))
1717            }
1718            "observe" => {
1719                let (repo, _) = self.scope(args)?;
1720                let path = arg_string(args, "path")?;
1721                let content = arg_string(args, "content")?;
1722                let ts = self.now();
1723                let config = self.config.clone();
1724                let out = self
1725                    .store
1726                    .observe_one(&repo, &path, &content, &ts, &config)?;
1727                self.store.sweep_pool(&ts)?;
1728                self.notify();
1729                Ok(observe_json(&out))
1730            }
1731            "observe_many" => {
1732                let (repo, _) = self.scope(args)?;
1733                let files = args
1734                    .get("files")
1735                    .and_then(Json::as_array)
1736                    .ok_or_else(|| bad_args("`files` must be an array of {path, content}"))?;
1737                let items: Vec<omgbase_store::BatchItem> = files
1738                    .iter()
1739                    .map(|f| {
1740                        Ok(omgbase_store::BatchItem::observed(
1741                            &arg_string(f, "path")?,
1742                            &arg_string(f, "content")?,
1743                        ))
1744                    })
1745                    .collect::<Result<_>>()?;
1746                let ts = self.now();
1747                let config = self.config.clone();
1748                let outcomes = self.store.observe_batch(&repo, &items, &ts, &config)?;
1749                self.store.sweep_pool(&ts)?;
1750                self.notify();
1751                let mut out = Vec::with_capacity(outcomes.len());
1752                for o in &outcomes {
1753                    match o.as_observed() {
1754                        Some(obs) => out.push(observe_json(obs)),
1755                        None => {
1756                            return Err(SurfaceError::other(format!(
1757                                "observe_many: unexpected outcome for {}",
1758                                o.path()
1759                            )));
1760                        }
1761                    }
1762                }
1763                Ok(Json::Array(out))
1764            }
1765            "observe_delete" => {
1766                let (repo, _) = self.scope(args)?;
1767                let path = arg_string(args, "path")?;
1768                let ts = self.now();
1769                let out = self.store.observe_delete(&repo, &path, &ts)?;
1770                self.notify();
1771                Ok(json!({ "docId": out.doc_id, "path": out.path, "deleted": out.deleted() }))
1772            }
1773            "history_node" => history::history_node(
1774                &self.store,
1775                &arg_string(args, "id")?,
1776                arg_i64(args, "limit")?,
1777            ),
1778            "diff" => {
1779                let (repo, _) = self.scope(args)?;
1780                let doc_id = self.resolve_doc_id(&repo, arg_str(args, "doc"), None, None)?;
1781                history::diff_blocks(
1782                    &self.store,
1783                    &doc_id,
1784                    &arg_string(args, "from_rev")?,
1785                    &arg_string(args, "to_rev")?,
1786                )
1787            }
1788            "diff_unified" => {
1789                let (repo, _) = self.scope(args)?;
1790                let doc_ref = arg_string(args, "doc")?;
1791                let doc_id = self.resolve_doc_id(&repo, Some(&doc_ref), None, None)?;
1792                let revs = history::recent_revs(self.store.conn(), &doc_id)?;
1793                let to_rev = arg_str(args, "to_rev")
1794                    .map(str::to_owned)
1795                    .or_else(|| revs.first().cloned());
1796                let from_rev = arg_str(args, "from_rev")
1797                    .map(str::to_owned)
1798                    .or_else(|| revs.get(1).cloned())
1799                    .or_else(|| revs.first().cloned());
1800                let (Some(from), Some(to)) = (from_rev, to_rev) else {
1801                    return Err(SurfaceError::new(
1802                        "target_missing",
1803                        format!("no revisions to diff for {}", Json::String(doc_ref)),
1804                    ));
1805                };
1806                let path: Option<String> = self
1807                    .store
1808                    .conn()
1809                    .query_row(
1810                        "SELECT path FROM docs WHERE doc_id = ?1",
1811                        params![doc_id],
1812                        |r| r.get(0),
1813                    )
1814                    .optional()?;
1815                let diff = history::diff_unified_text(&self.store, &doc_id, &from, &to)?;
1816                Ok(
1817                    json!({ "doc": doc_id, "path": path.unwrap_or_default(), "from": from, "to": to, "diff": diff }),
1818                )
1819            }
1820            "docs_read_at" => {
1821                let (repo, _) = self.scope(args)?;
1822                let doc_id = self.resolve_doc_from_args(&repo, args)?;
1823                let rev = arg_string(args, "rev")?;
1824                read::docs_read_at(&self.store, &doc_id, &rev)?.ok_or_else(|| {
1825                    SurfaceError::with_data(
1826                        "target_missing",
1827                        format!(
1828                            "no revision {} for document {doc_id}",
1829                            Json::String(rev.clone())
1830                        ),
1831                        json!({ "doc": doc_id, "rev": rev }),
1832                    )
1833                })
1834            }
1835            "docs_history" => {
1836                let (repo, _) = self.scope(args)?;
1837                let glob = arg_str(args, "path_glob").filter(|g| !g.is_empty());
1838                let doc = arg_str(args, "doc").filter(|d| !d.is_empty());
1839                if glob.is_none() && doc.is_none() {
1840                    return Err(SurfaceError::new(
1841                        "target_missing",
1842                        "docs_history requires one of path_glob or doc",
1843                    ));
1844                }
1845                let include_deleted = arg_bool(args, "include_deleted")?.unwrap_or(false);
1846                if let Some(d) = doc {
1847                    if history::resolve_doc_row(self.store.conn(), &repo, d, include_deleted)?
1848                        .is_none()
1849                    {
1850                        return Err(SurfaceError::new(
1851                            "doc_missing",
1852                            format!("no document for {}", Json::String(d.to_owned())),
1853                        ));
1854                    }
1855                }
1856                history::docs_history(
1857                    &self.store,
1858                    &repo,
1859                    glob,
1860                    doc,
1861                    include_deleted,
1862                    arg_i64(args, "limit")?,
1863                )
1864            }
1865            "changes_since" => {
1866                let (repo, _) = self.scope(args)?;
1867                let page = self.store.changes_since(
1868                    &repo,
1869                    arg_i64(args, "cursor")?.unwrap_or(0),
1870                    arg_usize(args, "limit")?.unwrap_or(50),
1871                    arg_str(args, "origin").filter(|o| !o.is_empty()),
1872                )?;
1873                Ok(page.to_json())
1874            }
1875            "repos_status" => {
1876                let (repo, root) = self.scope(args)?;
1877                let fs = RealFileSystem;
1878                let disk = root
1879                    .as_deref()
1880                    .map(|r| (&fs as &dyn omgbase_sync::FileSystem, Path::new(r)));
1881                Ok(omgbase_sync::repos_status(&self.store, &repo, disk)?.to_json())
1882            }
1883            "sync_status" => {
1884                let (repo, root) = self.scope(args)?;
1885                let fs = RealFileSystem;
1886                let disk = root
1887                    .as_deref()
1888                    .map(|r| (&fs as &dyn omgbase_sync::FileSystem, Path::new(r)));
1889                Ok(omgbase_sync::sync_status(&self.store, &repo, disk)?.to_json())
1890            }
1891            "repos" => {
1892                let rows = self.repo_rows()?;
1893                Ok(json!({
1894                    "repos": rows.iter().map(|r| json!({ "slug": r.slug, "hasSource": r.root_path.is_some() })).collect::<Vec<_>>(),
1895                }))
1896            }
1897            other => Err(SurfaceError::other(format!("unknown tool {other}"))),
1898        }
1899    }
1900}
1901
1902/// `spec/mutate` §4's result on the wire: `{ results: [{ ids, removed?,
1903/// mergedInto? }], revisions, diffs?, committed }` (camelCase, as the
1904/// reference).
1905#[must_use]
1906pub fn apply_json(res: &ApplyResult) -> Json {
1907    let mut m = Map::new();
1908    m.insert(
1909        "results".to_owned(),
1910        Json::Array(
1911            res.results
1912                .iter()
1913                .map(|r| {
1914                    let mut o = Map::new();
1915                    o.insert("ids".to_owned(), json!(r.ids));
1916                    if let Some(rm) = &r.removed {
1917                        o.insert("removed".to_owned(), json!(rm));
1918                    }
1919                    if let Some(mi) = &r.merged_into {
1920                        o.insert("mergedInto".to_owned(), json!(mi));
1921                    }
1922                    Json::Object(o)
1923                })
1924                .collect(),
1925        ),
1926    );
1927    m.insert(
1928        "revisions".to_owned(),
1929        Json::Array(
1930            res.revisions
1931                .iter()
1932                .map(|r| json!({ "doc": r.doc, "path": r.path }))
1933                .collect(),
1934        ),
1935    );
1936    if let Some(diffs) = &res.diffs {
1937        let mut d = Map::new();
1938        for (path, diff) in diffs {
1939            d.insert(
1940                path.clone(),
1941                json!({ "before": diff.before, "after": diff.after }),
1942            );
1943        }
1944        m.insert("diffs".to_owned(), Json::Object(d));
1945    }
1946    m.insert("committed".to_owned(), json!(res.committed));
1947    Json::Object(m)
1948}
1949
1950/// A document operation's result: `{ docId, path, committed }`.
1951fn doc_op_json(res: &omgbase_store::DocOpResult) -> Json {
1952    json!({ "docId": res.doc_id, "path": res.path, "committed": res.committed })
1953}
1954
1955/// `spec/mutate` §7's opset on the wire (camelCase precondition keys and
1956/// `matcherV`, as the reference).
1957#[must_use]
1958pub fn opset_json(opset: &Opset) -> Json {
1959    let mut m = Map::new();
1960    m.insert("version".to_owned(), json!(1));
1961    m.insert("kind".to_owned(), json!("doc_update"));
1962    m.insert(
1963        "target".to_owned(),
1964        json!({ "doc": opset.target_doc, "path": opset.target_path }),
1965    );
1966    m.insert(
1967        "precondition".to_owned(),
1968        json!({
1969            "doc": opset.precondition.doc,
1970            "path": opset.precondition.path,
1971            "baseRevision": opset.precondition.base_revision,
1972            "baseContentHash": opset.precondition.base_content_hash,
1973        }),
1974    );
1975    m.insert("matcherV".to_owned(), json!(opset.matcher_v));
1976    m.insert(
1977        "ops".to_owned(),
1978        Json::Array(
1979            opset
1980                .ops
1981                .iter()
1982                .map(|p| {
1983                    let mut o = Map::new();
1984                    o.insert("op".to_owned(), p.op.to_json());
1985                    o.insert("disposition".to_owned(), json!(p.disposition.as_str()));
1986                    o.insert("blocks".to_owned(), json!(p.blocks));
1987                    o.insert("confidence".to_owned(), json!(p.confidence));
1988                    o.insert("reason".to_owned(), json!(p.reason));
1989                    if let Some(d) = &p.detail {
1990                        o.insert("detail".to_owned(), d.clone());
1991                    }
1992                    Json::Object(o)
1993                })
1994                .collect(),
1995        ),
1996    );
1997    if let Some(fm) = &opset.frontmatter {
1998        m.insert("frontmatter".to_owned(), json!({ "raw": fm }));
1999    }
2000    m.insert("summary".to_owned(), opset.summary.to_json());
2001    m.insert("converges".to_owned(), json!(opset.converges));
2002    m.insert("diagnostics".to_owned(), json!(opset.diagnostics));
2003    Json::Object(m)
2004}
2005
2006/// `spec/search` §4's evidence on the wire: `{ rrf, boosts, ftsRank?,
2007/// vectorRank?, cosine? }`.
2008fn evidence_json(e: &omgbase_store::Evidence) -> Json {
2009    let mut m = Map::new();
2010    m.insert("rrf".to_owned(), json!(e.rrf));
2011    m.insert("boosts".to_owned(), e.boosts.to_json());
2012    if let Some(r) = e.fts_rank {
2013        m.insert("ftsRank".to_owned(), json!(r));
2014    }
2015    if let Some(r) = e.vector_rank {
2016        m.insert("vectorRank".to_owned(), json!(r));
2017        if let Some(c) = e.cosine {
2018            m.insert("cosine".to_owned(), json!(c));
2019        }
2020    }
2021    Json::Object(m)
2022}
2023
2024/// The public `observe` result: `{ docId, path, rev, commitId, converged,
2025/// echo, conflicted, dispositions: [{ kind, count }] }`.
2026fn observe_json(o: &omgbase_store::ObserveOutcome) -> Json {
2027    json!({
2028        "docId": o.doc_id,
2029        "path": o.path,
2030        "rev": o.rev,
2031        "commitId": o.commit_id,
2032        "converged": o.converged,
2033        "echo": o.echo,
2034        "conflicted": o.conflicted,
2035        "dispositions": o.dispositions.iter().map(|(k, n)| json!({ "kind": k, "count": n })).collect::<Vec<_>>(),
2036    })
2037}
2038
2039fn verb(d: omgbase_store::mutate_kernel::PlanDisposition) -> &'static str {
2040    use omgbase_store::mutate_kernel::PlanDisposition as D;
2041    match d {
2042        D::Same => "KEEP  ",
2043        D::Edited | D::EditedMoved => "UPDATE",
2044        D::Moved => "MOVE  ",
2045        D::Inserted => "INSERT",
2046        D::Deleted => "REMOVE",
2047        D::SplitFrom => "SPLIT ",
2048        D::MergedInto => "MERGE ",
2049        D::CopiedFrom => "COPY  ",
2050        D::Resurrected => "RESURR",
2051        D::BulkRewrite => "REWRITE",
2052        D::Retiled => "RETILE",
2053    }
2054}
2055
2056/// The one-line-per-op plan text of `docs_plan_update` / `docs_update`.
2057#[must_use]
2058pub fn render_opset_plan(opset: &Opset) -> String {
2059    let mut lines = Vec::new();
2060    for p in &opset.ops {
2061        let subject = p.blocks.first().map_or("(new)", String::as_str);
2062        let conf = p.confidence.map_or(String::new(), |c| format!(" ~{c:.2}"));
2063        let why = p
2064            .reason
2065            .as_ref()
2066            .map_or(String::new(), |r| format!(" [{r}]"));
2067        lines.push(format!(
2068            "{} {:<9} {}{conf}{why}",
2069            verb(p.disposition),
2070            subject,
2071            p.disposition.as_str()
2072        ));
2073    }
2074    let s = &opset.summary;
2075    lines.push(String::new());
2076    lines.push(format!(
2077        "preserved: {}  updated: {}  moved: {}  created: {}  removed: {}  split: {}  merged: {}  ambiguous: {}",
2078        s.preserved, s.updated, s.moved, s.created, s.removed, s.split, s.merged, s.ambiguous
2079    ));
2080    if !opset.converges {
2081        lines.push(
2082            "WARNING: plan does not reproduce the proposed content exactly — will not apply."
2083                .to_owned(),
2084        );
2085    }
2086    lines.join("\n")
2087}
2088
2089#[cfg(test)]
2090mod tests {
2091    use super::*;
2092    use omgbase_store::{MemDocStore, SequentialMinter};
2093
2094    fn surface() -> Surface {
2095        let mut store =
2096            Store::open_in_memory_with_minter(Box::new(SequentialMinter::new())).unwrap();
2097        let repo = store.create_repo("fixture").unwrap();
2098        let mut n = 0;
2099        Surface::new(store, &repo, None)
2100            .with_doc_store(Box::new(MemDocStore::new()))
2101            .with_clock(move || {
2102                n += 1;
2103                format!("2026-09-26T10:{n:02}:00.000Z")
2104            })
2105    }
2106
2107    #[test]
2108    fn catalog_lists_every_tool_of_the_table() {
2109        let names: Vec<&str> = tools().iter().map(|t| t.name).collect();
2110        for want in [
2111            "docs_outline",
2112            "docs_read",
2113            "docs_get_many",
2114            "nodes_get",
2115            "nodes_get_many",
2116            "read_ref",
2117            "docs_tree",
2118            "docs_list",
2119            "query_syntax",
2120            "query",
2121            "graph",
2122            "text_search",
2123            "resolve",
2124            "apply",
2125            "blocks_insert",
2126            "blocks_update",
2127            "blocks_move",
2128            "blocks_remove",
2129            "blocks_split",
2130            "blocks_merge",
2131            "tasks_complete",
2132            "node_set",
2133            "sections_append",
2134            "docs_append",
2135            "links_retarget",
2136            "links_stale",
2137            "links_repair",
2138            "docs_create",
2139            "docs_move",
2140            "docs_delete",
2141            "docs_set_meta",
2142            "docs_plan_update",
2143            "docs_update",
2144            "observe",
2145            "observe_many",
2146            "observe_delete",
2147            "history_node",
2148            "diff",
2149            "diff_unified",
2150            "docs_read_at",
2151            "docs_history",
2152            "changes_since",
2153            "repos_status",
2154            "sync_status",
2155            "repos",
2156        ] {
2157            assert!(names.contains(&want), "missing {want}");
2158        }
2159        assert_eq!(names.len(), 45);
2160        for t in tools() {
2161            assert_eq!(t.input_schema["type"], "object");
2162        }
2163    }
2164
2165    #[test]
2166    fn observe_read_and_query_round_trip() {
2167        let mut s = surface();
2168        let out = s.call("observe", json!({ "path": "a.md", "content": "---\nlayer: canon\n---\n# Title\n\nHello world.\n\n- [ ] task one\n" }));
2169        assert!(!out.is_error, "{}", out.body);
2170        assert_eq!(out.body["docId"], "d_0");
2171        assert_eq!(out.body["echo"], false);
2172        let read = s.call("docs_read", json!({ "doc": "a.md", "include_ids": true }));
2173        assert!(!read.is_error);
2174        assert_eq!(read.body["path"], "a.md");
2175        assert_eq!(read.body["properties"]["frontmatter"]["layer"], "canon");
2176        assert!(read.body["ids"].as_array().unwrap().len() >= 3);
2177        let q = s.call("query", json!({ "query": "select $title, layer, t: nodes collect { value where kind == \"md:task\" } from docs where layer == \"canon\" && nodes count { where kind == \"md:task\" } == 1" }));
2178        assert!(!q.is_error, "{}", q.body);
2179        assert_eq!(q.body["hits"][0]["$title"], "Title");
2180        assert_eq!(q.body["hits"][0]["layer"], "canon");
2181        assert_eq!(q.body["hits"][0]["t"][0]["value"], "task one");
2182        assert_eq!(q.body["hits"][0]["id"], "d_0");
2183        assert_eq!(q.body["consumer"], "collect");
2184        let c = s.call(
2185            "query",
2186            json!({ "query": "$repo.blocks count { where text(\"hello\") }" }),
2187        );
2188        assert_eq!(c.body["count"], 1);
2189        let bad = s.call(
2190            "query",
2191            json!({ "query": "from docs where path == \"a.md\"" }),
2192        );
2193        assert!(bad.is_error);
2194        assert_eq!(bad.body["error"], "filter_invalid");
2195        assert!(
2196            bad.body["message"]
2197                .as_str()
2198                .unwrap()
2199                .contains("did you mean the intrinsic $path")
2200        );
2201        let sem = s.call(
2202            "query",
2203            json!({ "query": "from docs where semantic(\"x\") > 0.5" }),
2204        );
2205        assert_eq!(sem.body["error"], "semantic_unavailable");
2206        let outline = s.call("docs_outline", json!({ "path": "a.md" }));
2207        let text = outline.body["text"].as_str().unwrap();
2208        assert!(text.starts_with("b_0 h1   Title  §"), "{text}");
2209        assert!(text.contains("☐ task one"));
2210        let missing = s.call("docs_read", json!({ "doc": "nope.md" }));
2211        assert_eq!(missing.body["error"], "doc_missing");
2212        let repos = s.call("repos", json!({}));
2213        assert_eq!(repos.body["repos"][0]["slug"], "fixture");
2214        let unknown = s.call("docs_list", json!({ "repo": "zzz" }));
2215        assert_eq!(unknown.body["error"], "repo_not_found");
2216    }
2217
2218    #[test]
2219    fn writes_go_through_the_fixed_doc_store_and_fire_the_hook() {
2220        use std::cell::Cell;
2221        use std::rc::Rc;
2222        let fired = Rc::new(Cell::new(0));
2223        let f2 = Rc::clone(&fired);
2224        let mut s = surface().with_mutation_hook(move || f2.set(f2.get() + 1));
2225        s.call(
2226            "observe",
2227            json!({ "path": "a.md", "content": "# T\n\nOne.\n" }),
2228        );
2229        assert_eq!(fired.get(), 1);
2230        let dry = s.call(
2231            "blocks_insert",
2232            json!({ "to": "a.md", "markdown": "Two.", "dry_run": true }),
2233        );
2234        assert!(!dry.is_error, "{}", dry.body);
2235        assert_eq!(dry.body["committed"], false);
2236        assert_eq!(fired.get(), 1, "a dry run never fires the hook");
2237        let wet = s.call("blocks_insert", json!({ "to": "a.md", "markdown": "Two." }));
2238        assert!(!wet.is_error, "{}", wet.body);
2239        assert_eq!(fired.get(), 2);
2240        let read = s.call("docs_read", json!({ "doc": "d_0" }));
2241        assert_eq!(read.body["content"], "# T\n\nOne.\n\nTwo.\n");
2242        let upd = s.call(
2243            "blocks_update",
2244            json!({ "block": "b_1", "markdown": "One, edited." }),
2245        );
2246        assert!(!upd.is_error, "{}", upd.body);
2247        assert_eq!(upd.body["id"], "b_1");
2248        let app = s.call(
2249            "sections_append",
2250            json!({ "heading": "T", "markdown": "Three." }),
2251        );
2252        assert!(!app.is_error, "{}", app.body);
2253        let amb = s.call(
2254            "sections_append",
2255            json!({ "heading": "Nope", "markdown": "x" }),
2256        );
2257        assert_eq!(amb.body["error"], "parent_missing");
2258        let hist = s.call("history_node", json!({ "id": "b_1" }));
2259        let entries = hist.body.as_array().unwrap();
2260        assert!(entries.len() >= 2, "{}", hist.body);
2261        assert_eq!(entries[0]["origin"], "api", "newest first");
2262        let du = s.call("diff_unified", json!({ "doc": "a.md" }));
2263        assert!(!du.is_error, "{}", du.body);
2264        assert!(du.body["diff"].as_str().unwrap().contains("+ Three."));
2265    }
2266}