diff --git a/CHANGELOG.md b/CHANGELOG.md index 54630c30b..778af17de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- Improve agent-facing query correctness and recovery: callers, impact, and + affected include source-backed alias/import/export usage evidence; CompassQL + exposes live node degree and supports ordering by pre-projection bindings; + historical reads neutralize configured checkout filters; direction-only + trail misses suggest `compass path`; and full reports retain bounded hub, + suggested-query, and learned-question entries. +- Unify bounded relationship resolution across callers, impact, and affected, + including importer-consistency diagnostics and explicit relationship + provenance. Add the bounded `compass architecture` view, shared agent output + formats, visible coverage witnesses, a 64-candidate query default, and + read-only historical queries with state-health audit events. + ## 0.3.28 - 2026-09-19 - Improve agent-facing query correctness and recovery across callers, impact, diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 2048c9f13..1e07b5d21 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -118,6 +118,11 @@ View must reject unknown major versions, enforce the documented bounds, and distinguish `no_match`, `needs_resolution`, `no_path`, source truncation, and projection truncation from a positive complete answer. +The additive `relationship_inconsistency` diagnostic extends the strict +`compass.query/1` diagnostic enum and changes its contract fingerprint. Strict +TypeScript consumers and the checked-in manifest must accept the new value +before interpreting a relationship result that carries it. + Immutable history now accepts up to 5 GiB of aggregate authoritative key and value bytes per realization, raised from 512 MiB. The history schema and canonical encoding are unchanged, as are the per-key, per-value, per-tree, diff --git a/MIGRATION.md b/MIGRATION.md index ee2ac7337..7f5253674 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -23,6 +23,19 @@ reports `NO PATH FOUND` separately when both endpoints exist but are unreachable. Consumers that parsed the prior human path prose should migrate to these explicit signals; machine-query schema versions are unchanged. +Typed relationship commands now share source-backed import/reference +resolution. `callers`, `impact`, and typed `affected` may therefore return +additional importer evidence and can emit a `relationship_inconsistency` +diagnostic when their bounded traversal disagrees with the importer probe. +Treat that diagnostic as incomplete coverage rather than an empty answer. +The default typed search candidate limit is now 64; count-shaped automation +should inspect the structured `truncated` flag and diagnostics. + +`ask`, `search`, `query`, `callers`, `callees`, `impact`, `path`, and `explain` +accept the shared `--format text|json|agent-json` contract where applicable. +Use `compass architecture --format agent-json` for a bounded repository +overview with omission counts and witness IDs. + ## Rebuild SQLite adjacency sidecars Store snapshots now declare edge-ID-ordered directional adjacency so bounded diff --git a/crates/compass-cli/assets/compass-skill/SKILL.md b/crates/compass-cli/assets/compass-skill/SKILL.md index 1b673cb53..244c0a98f 100644 --- a/crates/compass-cli/assets/compass-skill/SKILL.md +++ b/crates/compass-cli/assets/compass-skill/SKILL.md @@ -105,9 +105,13 @@ Use the specialized navigation commands when they fit: - `compass explain ""` for one node and its neighborhood; use the same `--budget N` and `--page N` continuation workflow for large neighborhoods or ambiguity lists. +- `compass architecture` for a bounded repository overview with explicit + coverage, omissions, and witness group IDs. - `compass program` for normalized functions, call evidence, or capability completeness rather than graph topology. -- `compass affected "" --depth N` for downstream review scope. +- `compass affected "" --depth N` for downstream review scope; on a + typed graph it shares importer/reference resolution with `impact`, and + `--format agent-json` preserves bounded diagnostics for an agent. - `compass query --cql "..."` for exact, deterministic graph patterns. - `compass tree` for a graph-aware repository tree. - `compass query "" --at REV` for an immutable historical graph. @@ -197,7 +201,7 @@ recovery, and MCP setup. Classify the effect before selecting a command: - Read-only local: `ask`, `search`, `callers`, `callees`, `impact`, `explore`, - `node`, `call-graph`, `query`, `program`, `path`, `explain`, `affected`, + `node`, `call-graph`, `query`, `program`, `path`, `explain`, `architecture`, `affected`, `tree`, `document`, `models list`, `models verify`, and local diagnostics. - Local publication: `init`, `ensure`, `update`, `extract`, `watch`, `cluster-only`, `label`, `models install`, history materialization, installation, and @@ -261,7 +265,8 @@ the user wants human-readable community labels and accepts provider use. Use Do not force every request through `query`: -- Architecture or concept: `query`, then `explain`. +- Architecture or concept: `architecture`, then `query` or `explain` for a + focused relationship. - Dependency route: `path`. - Change-review scope: `affected`. - Exact relationship or automation: `query --cql`. diff --git a/crates/compass-cli/assets/compass-skill/references/command-reference.md b/crates/compass-cli/assets/compass-skill/references/command-reference.md index 325fa9368..b06325c07 100644 --- a/crates/compass-cli/assets/compass-skill/references/command-reference.md +++ b/crates/compass-cli/assets/compass-skill/references/command-reference.md @@ -35,8 +35,12 @@ whether a Compass capability is covered by the installed skill. Run - `compass path`: shortest known graph route between two matched nodes. - `compass explain`: budgeted, deterministic pages for one matched node plus its local neighborhood. +- `compass architecture`: bounded architecture projection with explicit + coverage, omissions, and witness IDs for agent inspection. - `compass affected`: downstream review candidates, optionally filtered by - relation and depth. + relation and depth. Typed graphs use the same source-backed relationship + resolver as `callers` and `impact`; use `--format json|agent-json` when an + agent needs diagnostics and evidence counts. - `compass tree`: repository hierarchy enriched with graph metadata. - `compass history`: configure, materialize, inspect, export, prefer, or garbage collect immutable commit realizations. @@ -55,9 +59,10 @@ whether a Compass capability is covered by the installed skill. Run - `compass store restore`: validate that manifest, graph export, selector, and sidecar before restoring into a new or empty output directory. -These are read-only unless a missing historical realization must be materialized. -An `--at REV` query can therefore create local history-store artifacts even -though the query itself does not edit the working tree. +These commands are read-only. An `--at REV` query requires an existing +materialized realization; run `compass history build REV --code-only` explicitly +before querying an uncached revision. Query caches may still be refreshed, but +no extraction or credential-dependent provider runs implicitly. ## Build and enrich diff --git a/crates/compass-cli/assets/compass-skill/references/history.md b/crates/compass-cli/assets/compass-skill/references/history.md index 6553fc7a2..2dfc09eca 100644 --- a/crates/compass-cli/assets/compass-skill/references/history.md +++ b/crates/compass-cli/assets/compass-skill/references/history.md @@ -32,17 +32,20 @@ compass history build main --all --first-parent --code-only --format json compass history list --format json ``` -Explicit historical queries can materialize a missing revision even when eager -history is disabled: +Explicit historical queries are read-only. They never materialize a missing +revision or invoke extraction; build the exact revision first: ```bash +compass history build HEAD~20 --code-only compass query "authentication flow" --at HEAD~20 compass path OldHandler Database --at v1.2.0 compass explain LegacyGateway --at RELEASE_TAG ``` -Compass resolves a revision to an exact commit and builds it in a protected, -offline worktree. Report the resolved revision when answering. +If the selected revision is not already materialized, the command stops with +the exact `compass history build REV --code-only` prerequisite. Compass still +resolves every read to an exact immutable realization; report that resolved +revision when answering. ## Compare and inspect @@ -62,6 +65,9 @@ Use `compass diff` for a ranked semantic review. Use `compass history diff` when the user needs an exhaustive, deterministic record-level comparison of immutable graph roots. +`compass history export` is read-only as well; build an uncached revision with +`compass history build REV --code-only` before exporting it. + Semantic realizations with different extraction fingerprints are not silently treated as equivalent. Use `history list`, `show`, and `prefer` to inspect or select an intended realization. diff --git a/crates/compass-cli/assets/compass-skill/references/query.md b/crates/compass-cli/assets/compass-skill/references/query.md index d98e9c84b..705c45d13 100644 --- a/crates/compass-cli/assets/compass-skill/references/query.md +++ b/crates/compass-cli/assets/compass-skill/references/query.md @@ -85,6 +85,7 @@ compass explore CheckoutController PaymentGateway --root . compass node route:/checkout CheckoutController.create compass explain PaymentGateway compass explain PaymentGateway --budget 8000 --page 2 +compass architecture --format agent-json compass path CheckoutHandler PaymentGateway compass affected authorizePayment --depth 3 compass tree diff --git a/crates/compass-cli/src/code_query_commands.rs b/crates/compass-cli/src/code_query_commands.rs index f4933a1f3..828fea2bd 100644 --- a/crates/compass-cli/src/code_query_commands.rs +++ b/crates/compass-cli/src/code_query_commands.rs @@ -11,12 +11,15 @@ use compass_query::{ EngineSelection, NaturalQueryRequest, open_with_engine, open_with_verified_document, }; -use crate::Outcome; +use crate::{Outcome, SharedOutputFormat, parse_shared_output_format}; pub(crate) fn command(operation: &str, args: &[String]) -> Outcome { - let format = option(args, "--format").unwrap_or("text"); - if format == "agent-json" - && args.iter().any(|arg| { + let (format, query_args) = match parse_shared_output_format(args, operation) { + Ok(parsed) => parsed, + Err(error) => return Outcome::failure(format!("error: {error}")), + }; + if format == SharedOutputFormat::AgentJson + && query_args.iter().any(|arg| { matches!( arg.as_str(), "--cursor" | "--text-budget" | "--evidence" | "--result-envelope" @@ -28,21 +31,21 @@ pub(crate) fn command(operation: &str, args: &[String]) -> Outcome { "error: --cursor, --text-budget, --evidence, and --result-envelope are text-only and cannot be used with --format agent-json".to_owned(), ); } - match execute(operation, args) { + match execute(operation, &query_args) { Ok(execution) => { - if format == "json" { + if format == SharedOutputFormat::Json { match serde_json::to_string_pretty(&execution.response) { Ok(json) => Outcome::success(json), Err(error) => Outcome::failure(format!("error: {error}")), } - } else if format == "agent-json" { + } else if format == SharedOutputFormat::AgentJson { match build_code_query_view(&execution.response, execution.context) .and_then(|view| serde_json::to_string_pretty(&view).map_err(Into::into)) { Ok(json) => Outcome::success(json), Err(error) => Outcome::failure(format!("error: {error}")), } - } else if format == "text" { + } else if format == SharedOutputFormat::Text { match build_code_query_view(&execution.response, execution.context) .and_then(|view| render_agent_query_text(&view)) { @@ -50,7 +53,7 @@ pub(crate) fn command(operation: &str, args: &[String]) -> Outcome { Err(error) => Outcome::failure(format!("error: {error}")), } } else { - Outcome::failure("error: --format must be json, agent-json, or text".to_owned()) + Outcome::failure("error: unsupported output format".to_owned()) } } Err(error) => Outcome::failure(format!("error: {error}")), diff --git a/crates/compass-cli/src/help.rs b/crates/compass-cli/src/help.rs index 48315dbaf..5ec1a25bc 100644 --- a/crates/compass-cli/src/help.rs +++ b/crates/compass-cli/src/help.rs @@ -115,7 +115,7 @@ const GROUPS: &[Group] = &[ }, Group { title: "Visualize and export", - commands: &["tree", "export"], + commands: &["tree", "architecture", "export"], }, Group { title: "Integrate and automate", @@ -176,7 +176,7 @@ const PAGES: &[Page] = &[ "ask", "Route a natural-language question to a typed code-graph query", ["compass ask [OPTIONS]"], - "Arguments:\n Natural-language code-graph question\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --at Use an immutable trusted revision graph\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-depth Traversal radius\n --max-nodes Node bound\n --max-edges Edge bound\n --max-paths Path bound\n --max-candidates Candidate bound\n --include-heuristic Include heuristic evidence\n --format Output format [default: text]\n\nExamples:\n compass ask \"who calls PaymentService.charge?\"\n compass ask \"what does CheckoutController.create call?\" --format json\n compass ask \"path from CheckoutController.create to PaymentGateway.charge\"\n compass ask \"who calls PaymentService.charge?\" --at HEAD~2 --format json\n\nNotes:\n High-confidence callers, callees, impact, and path questions route to the matching typed operation. Contradictory or low-confidence input falls back to bounded symbol search. --at is mutually exclusive with --graph, --program, --cache, and --engine. The response uses compass.query/1." + "Arguments:\n Natural-language code-graph question\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --at Use an immutable trusted revision graph\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-depth Traversal radius\n --max-nodes Node bound\n --max-edges Edge bound\n --max-paths Path bound\n --max-candidates Candidate bound [default: 64]\n --include-heuristic Include heuristic evidence\n --format Output format [default: text]\n\nExamples:\n compass ask \"who calls PaymentService.charge?\"\n compass ask \"what does CheckoutController.create call?\" --format json\n compass ask \"path from CheckoutController.create to PaymentGateway.charge\"\n compass ask \"who calls PaymentService.charge?\" --at HEAD~2 --format json\n\nNotes:\n High-confidence callers, callees, impact, and path questions route to the matching typed operation. Contradictory or low-confidence input falls back to bounded symbol search. --at is mutually exclusive with --graph, --program, --cache, and --engine. The response uses compass.query/1." ), page!( "call-graph", @@ -320,37 +320,37 @@ const PAGES: &[Page] = &[ "search", "Search typed code symbols by name", ["compass search [OPTIONS]"], - "Arguments:\n Symbol name or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-candidates Candidate bound\n --format Output format [default: text]\n\nExamples:\n compass search PaymentService\n compass search checkout --format json\n\nNotes:\n Search uses the versioned compass.query/1 response contract in both formats." + "Arguments:\n Symbol name or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-candidates Candidate bound [default: 64]\n --format Output format [default: text]\n\nExamples:\n compass search PaymentService\n compass search checkout --format json\n\nNotes:\n Search uses the versioned compass.query/1 response contract in all formats." ), page!( "callers", "List direct incoming usages of a typed symbol", ["compass callers [OPTIONS]"], - "Arguments:\n Symbol ID, name, or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-nodes Node bound\n --max-edges Edge bound\n --include-heuristic Include heuristic evidence (default is exact-first)\n --format Output format [default: text]\n\nExamples:\n compass callers PaymentService.charge\n compass callers sym:checkout --format json\n\nNotes:\n Incoming usages include calls, routes, references, imports, exports, and aliases; each result retains its exact relationship kind." + "Arguments:\n Symbol ID, name, or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-nodes Node bound\n --max-edges Edge bound\n --include-heuristic Include heuristic evidence (default is exact-first)\n --format Output format [default: text]\n\nExamples:\n compass callers PaymentService.charge\n compass callers sym:checkout --format json\n\nNotes:\n Incoming usages include calls, routes, references, imports, exports, and aliases; each result retains its exact relationship kind." ), page!( "callees", "List direct callees of a typed symbol", ["compass callees [OPTIONS]"], - "Arguments:\n Symbol ID, name, or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-nodes Node bound\n --max-edges Edge bound\n --include-heuristic Include heuristic evidence (default is exact-first)\n --format Output format [default: text]\n\nExamples:\n compass callees CheckoutController.create\n compass callees sym:checkout --format json" + "Arguments:\n Symbol ID, name, or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-nodes Node bound\n --max-edges Edge bound\n --include-heuristic Include heuristic evidence (default is exact-first)\n --format Output format [default: text]\n\nExamples:\n compass callees CheckoutController.create\n compass callees sym:checkout --format json" ), page!( "impact", "Compute the bounded transitive impact of a symbol", ["compass impact [OPTIONS]"], - "Arguments:\n Changed symbol ID, name, or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-depth Traversal radius\n --max-nodes Node bound\n --max-edges Edge bound\n --include-heuristic Traverse heuristic evidence\n --format Output format [default: text]\n\nExamples:\n compass impact PaymentGateway --max-depth 3\n compass impact sym:gateway --include-heuristic --format json" + "Arguments:\n Changed symbol ID, name, or qualified name\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-depth Traversal radius\n --max-nodes Node bound\n --max-edges Edge bound\n --include-heuristic Traverse heuristic evidence\n --format Output format [default: text]\n\nExamples:\n compass impact PaymentGateway --max-depth 3\n compass impact sym:gateway --include-heuristic --format json" ), page!( "explore", "Return related source grouped by file with connecting paths", ["compass explore [SYMBOL...] [OPTIONS]"], - "Arguments:\n Symbol IDs, names, or qualified names\n\nOptions:\n --root Repository root used to read source\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-paths Path bound\n --max-source-bytes Source-byte bound\n --max-response-bytes Serialized response bound\n --include-heuristic Include heuristic evidence (default is exact-first)\n --format Output format [default: text]\n\nExamples:\n compass explore CheckoutController PaymentGateway --root .\n compass explore sym:a sym:b --root . --format json" + "Arguments:\n Symbol IDs, names, or qualified names\n\nOptions:\n --root Repository root used to read source\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-paths Path bound\n --max-source-bytes Source-byte bound\n --max-response-bytes Serialized response bound\n --include-heuristic Include heuristic evidence (default is exact-first)\n --format Output format [default: text]\n\nExamples:\n compass explore CheckoutController PaymentGateway --root .\n compass explore sym:a sym:b --root . --format json" ), page!( "node", "Show a bounded evidence trail between two symbols", ["compass node [OPTIONS]"], - "Arguments:\n Trail origin symbol\n Trail destination symbol\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-depth Traversal radius\n --max-paths Path bound\n --include-heuristic Include heuristic evidence\n --format Output format [default: text]\n\nExamples:\n compass node route:/checkout CheckoutController.create\n compass node sym:a sym:b --include-heuristic --format json" + "Arguments:\n Trail origin symbol\n Trail destination symbol\n\nOptions:\n --graph Typed graph [default: compass-out/graph.json]\n --program Optional Program IR enrichment\n --cache Query-index cache directory\n --engine Graph storage engine [default: default]\n --max-depth Traversal radius\n --max-paths Path bound\n --include-heuristic Include heuristic evidence\n --format Output format [default: text]\n\nExamples:\n compass node route:/checkout CheckoutController.create\n compass node sym:a sym:b --include-heuristic --format json" ), page!( "query", @@ -365,7 +365,7 @@ const PAGES: &[Page] = &[ "compass query --text-budget ", "compass query --cursor " ], - "Arguments:\n Natural-language graph question\n Inline CompassQL query\n\nOptions:\nNatural discovery:\n --direction Direction: auto, incoming, outgoing, or both [default: auto]\n --scope Repeatable OR scope: community, source, package, or node\n --context Repeatable strict relationship-context filter\n --dfs Use depth-first expansion [default: breadth-first]\n --include-heuristic Include heuristic evidence [default: excluded]\n --evidence Include full provenance and typed detail in text\n --format Discovery output [default: text]\n --text-budget Approximate tokens in one text page [default: 8000]\n --cursor Continue the same immutable semantic result (text only)\n --max-depth Traversal depth [default: 2; hard maximum: 8]\n --max-seeds Ranked seed count [default: 3; hard maximum: 3]\n --max-candidates Ranked candidate count [default/hard maximum: 256]\n --max-nodes Returned node count [default/hard maximum: 500]\n --max-edges Returned edge count [default/hard maximum: 1000]\n --max-expanded-relationships Examined relationships [default/hard maximum: 10000]\n --max-response-bytes Serialized response bytes [default/hard maximum: 8388608]\n --timeout-ms Discovery deadline in milliseconds [default/hard maximum: 30000]\n\nLegacy traversal:\n --traverse Force legacy relevance traversal\n --budget Approximate tokens per page [default: 2000]\n --page Result page, starting at 1 [default: 1]\n\nGraph selection:\n --graph Read a graph JSON file\n --at Query an exact immutable realization; conflicts with --graph\n\nCompassQL:\n --cql Use CompassQL mode\n --file Read CompassQL from a file\n --stdin Read CompassQL from standard input\n --repl Start the interactive CompassQL shell\n --param Bind a parameter; repeatable\n --params-file Read parameters from JSON\n --format CompassQL result format [default: table]\n --output Write CompassQL results to a file\n --timeout-ms CompassQL execution timeout\n --max-rows CompassQL row limit [default: 10000]\n --max-path-depth CompassQL path-depth limit [default: 32]\n --max-expanded-relationships CompassQL relationship expansion limit\n --max-memory-bytes CompassQL memory limit [default: 268435456]\n\nExamples:\n compass query \"who calls PaymentService.charge?\"\n compass query \"authentication flow\" --direction both --scope package:auth\n compass query \"what uses charge?\" --direction incoming --context call --format json\n compass query \"authentication flow\" --evidence\n compass query \"authentication flow\" --cursor ''\n compass query \"authentication flow\" --budget 8000 --page 2\n compass query --cql \"MATCH (n) RETURN n LIMIT 10\" --format json\n compass query --cql --file report.cql --params-file params.json\n\nTips:\n Direction, scope, context, and DFS compose through the bounded typed discovery contract. Scope is repeatable OR and never guesses a kind. Plain text is concise; pass --evidence for provenance. Discovery limits must be positive; values above a hard maximum are rejected rather than clamped. Legacy --traverse, --budget, and --page cannot be mixed with discovery controls.\n Historical discovery requires an immutable realization retaining trusted compass.graph/1 data." + "Arguments:\n Natural-language graph question\n Inline CompassQL query\n\nOptions:\nNatural discovery:\n --direction Direction: auto, incoming, outgoing, or both [default: auto]\n --scope Repeatable OR scope: community, source, package, or node\n --context Repeatable strict relationship-context filter\n --dfs Use depth-first expansion [default: breadth-first]\n --include-heuristic Include heuristic evidence [default: excluded]\n --evidence Include full provenance and typed detail in text\n --format Discovery output [default: text]\n --text-budget Approximate tokens in one text page [default: 8000]\n --cursor Continue the same immutable semantic result (text only)\n --max-depth Traversal depth [default: 2; hard maximum: 8]\n --max-seeds Ranked seed count [default: 3; hard maximum: 3]\n --max-candidates Ranked candidate count [default/hard maximum: 256]\n --max-nodes Returned node count [default/hard maximum: 500]\n --max-edges Returned edge count [default/hard maximum: 1000]\n --max-expanded-relationships Examined relationships [default/hard maximum: 10000]\n --max-response-bytes Serialized response bytes [default/hard maximum: 8388608]\n --timeout-ms Discovery deadline in milliseconds [default/hard maximum: 30000]\n\nLegacy traversal:\n --traverse Force legacy relevance traversal\n --budget Approximate tokens per page [default: 2000]\n --page Result page, starting at 1 [default: 1]\n\nGraph selection:\n --graph Read a graph JSON file\n --at Query an exact immutable realization; conflicts with --graph\n\nCompassQL:\n --cql Use CompassQL mode\n --file Read CompassQL from a file\n --stdin Read CompassQL from standard input\n --repl Start the interactive CompassQL shell\n --param Bind a parameter; repeatable\n --params-file Read parameters from JSON\n --format CompassQL result format [default: table]\n --output Write CompassQL results to a file\n --timeout-ms CompassQL execution timeout\n --max-rows CompassQL row limit [default: 10000]\n --max-path-depth CompassQL path-depth limit [default: 32]\n --max-expanded-relationships CompassQL relationship expansion limit\n --max-memory-bytes CompassQL memory limit [default: 268435456]\n\nExamples:\n compass query \"who calls PaymentService.charge?\"\n compass query \"authentication flow\" --direction both --scope package:auth\n compass query \"what uses charge?\" --direction incoming --context call --format json\n compass query \"authentication flow\" --evidence\n compass query \"authentication flow\" --cursor ''\n compass query \"authentication flow\" --budget 8000 --page 2\n compass query --cql \"MATCH (n) RETURN n LIMIT 10\" --format json\n compass query --cql --file report.cql --params-file params.json\n\nTips:\n Direction, scope, context, and DFS compose through the bounded typed discovery contract. Scope is repeatable OR and never guesses a kind. Plain text is concise; pass --evidence for provenance. Discovery limits must be positive; values above a hard maximum are rejected rather than clamped. Legacy --traverse, --budget, and --page cannot be mixed with discovery controls.\n Historical discovery requires an immutable realization retaining trusted compass.graph/1 data." ), page!( "program", @@ -425,19 +425,25 @@ const PAGES: &[Page] = &[ "path", "Find the shortest relationship path between two graph nodes", ["compass path [OPTIONS]"], - "Arguments:\n Exact source node name, qualified name, or ID\n Exact target node name, qualified name, or ID\n\nOptions:\n --max-depth Maximum hops examined [default: 8]\n --graph Read a graph JSON file\n --at Use an immutable Git revision; conflicts with --graph\n\nExamples:\n compass path CheckoutHandler PaymentGateway\n compass path api route --max-depth 5 --at v1.2.0\n\nNotes:\n Resolution completes before traversal. Path traversal may follow relationships in either direction; displayed arrows preserve stored direction. The final path node is always the resolved target ID. Relations are weighted so structural chains beat weak shared-reference shortcuts; a close shorter-but-weaker alternative is reported separately." + "Arguments:\n Exact source node name, qualified name, or ID\n Exact target node name, qualified name, or ID\n\nOptions:\n --max-depth Maximum hops examined [default: 8]\n --format Shared output contract [default: text]\n --graph Read a graph JSON file\n --at Use an immutable Git revision; conflicts with --graph\n\nExamples:\n compass path CheckoutHandler PaymentGateway\n compass path api route --max-depth 5 --at v1.2.0\n compass path api route --format agent-json\n\nNotes:\n Resolution completes before traversal. Path traversal may follow relationships in either direction; displayed arrows preserve stored direction. The final path node is always the resolved target ID. Relations are weighted so structural chains beat weak shared-reference shortcuts; a close shorter-but-weaker alternative is reported separately." ), page!( "explain", "Explain a node and its important relationships", ["compass explain [OPTIONS]"], - "Arguments:\n Node ID, name, label, or qualified name\n\nOptions:\n --budget Approximate tokens per page [default: 2000]\n --page Connection or ambiguity page, starting at 1 [default: 1]\n --graph Read a graph JSON file\n --at Use an immutable Git revision; conflicts with --graph\n\nExamples:\n compass explain PaymentService\n compass explain PaymentService --budget 8000\n compass explain PaymentService --page 2\n compass explain auth --at HEAD~5" + "Arguments:\n Node ID, name, label, or qualified name\n\nOptions:\n --budget Approximate tokens per page [default: 2000]\n --page Connection or ambiguity page, starting at 1 [default: 1]\n --format Shared output contract [default: text]\n --graph Read a graph JSON file\n --at Use an immutable Git revision; conflicts with --graph\n\nExamples:\n compass explain PaymentService\n compass explain PaymentService --budget 8000\n compass explain PaymentService --page 2\n compass explain auth --at HEAD~5 --format agent-json" + ), + page!( + "architecture", + "Summarize the bounded architecture projection for agent inspection", + ["compass architecture [OPTIONS]"], + "Options:\n --graph Graph JSON [default: compass-out/graph.json]\n --labels Community-label JSON\n --format Output format [default: text]\n\nExamples:\n compass architecture\n compass architecture --format agent-json\n compass architecture --graph compass-out/graph.json --format json\n\nNotes:\n The projection preserves omission counts and witness group IDs. Omitted groups are not evidence that the architecture is empty." ), page!( "affected", "Find code reachable from a proposed change", ["compass affected [OPTIONS]"], - "Arguments:\n Starting node or community label\n\nOptions:\n --relation Follow one relationship type; repeatable\n --depth Maximum traversal depth\n --graph Read a graph JSON file\n\nExamples:\n compass affected PaymentGateway\n compass affected auth --relation CALLS --depth 3" + "Arguments:\n Starting node or community label\n\nOptions:\n --relation Follow one relationship type; repeatable\n --depth Maximum traversal depth\n --graph Read a graph JSON file\n --format Output format [default: text]\n\nExamples:\n compass affected PaymentGateway\n compass affected auth --relation CALLS --depth 3\n compass affected PaymentGateway --format agent-json" ), page!( "benchmark", @@ -1322,7 +1328,7 @@ mod tests { #[test] fn catalog_has_unique_complete_public_roots() { let roots = root_commands(); - assert_eq!(roots.len(), 53); + assert_eq!(roots.len(), 54); for root in roots { let matches = PAGES.iter().filter(|page| page.path == root).count(); assert_eq!(matches, 1, "{root}"); diff --git a/crates/compass-cli/src/history_commands.rs b/crates/compass-cli/src/history_commands.rs index 8e5b54a83..ca0121a13 100644 --- a/crates/compass-cli/src/history_commands.rs +++ b/crates/compass-cli/src/history_commands.rs @@ -62,8 +62,7 @@ pub(crate) fn load_graph_at( let commit = repository .resolve(revision) .map_err(|error| error.to_string())?; - let options = configured_build_options(&repository)?; - let (history, preferred) = resolve_or_materialize(&repository, commit, &options, false, false)?; + let (history, preferred) = resolve_materialized(&repository, &commit)?; let cache = history.cache().map_err(|error| error.to_string())?; let cache_key = serde_json::json!({ "schema": "compass.history.graph_query_key/1", @@ -103,8 +102,7 @@ pub(crate) fn load_typed_graph_at( let commit = repository .resolve(revision) .map_err(|error| error.to_string())?; - let options = configured_build_options(&repository)?; - let (history, preferred) = resolve_or_materialize(&repository, commit, &options, false, false)?; + let (history, preferred) = resolve_materialized(&repository, &commit)?; let realization = preferred.id; let reader = history .reader(&realization) @@ -126,9 +124,7 @@ pub(crate) fn load_history_view_model_at( let commit = repository .resolve(revision) .map_err(|error| error.to_string())?; - let options = configured_build_options(&repository)?; - let (history, preferred) = - resolve_or_materialize(&repository, commit.clone(), &options, false, false)?; + let (history, preferred) = resolve_materialized(&repository, &commit)?; let reader = history .reader(&preferred.id) .map_err(|error| error.to_string())?; @@ -152,6 +148,32 @@ pub(crate) fn resolve_or_materialize( resolve_or_materialize_inner(repository, commit, options, rebuild, replace_corrupt, false) } +/// Resolve an already-published realization without creating a history store, +/// queueing a job, checking out a revision, or invoking any extractor. Query +/// and diff commands use this read-only path so an uncached revision produces +/// an actionable prerequisite error instead of an opaque build failure. +fn resolve_materialized( + repository: &Repository, + commit: &CommitId, +) -> Result<(HistoryStore, PublishedVersion), String> { + let history = HistoryStore::open_existing(repository) + .map_err(|error| error.to_string())? + .ok_or_else(|| { + format!( + "revision {commit} is not materialized; this read-only command will not build it. Run `compass history build {commit} --code-only` first" + ) + })?; + let preferred = history + .preferred(commit) + .map_err(|error| error.to_string())? + .ok_or_else(|| { + format!( + "revision {commit} is not materialized; this read-only command will not build it. Run `compass history build {commit} --code-only` first" + ) + })?; + Ok((history, preferred)) +} + fn resolve_or_materialize_matching_profile( repository: &Repository, commit: CommitId, @@ -290,98 +312,22 @@ pub(crate) fn resolve_comparable_pair( if required_fingerprint.is_some() && (old.is_none() || new.is_none()) { return Err("the requested fingerprint is not materialized at both commits".to_owned()); } - let (history, old, new) = match (old, new) { - (Some(old), Some(new)) if required_fingerprint.is_some() => ( - existing.ok_or_else(|| "history store disappeared".to_owned())?, - old, - new, - ), - (Some(old), Some(new)) => { - let old_options = - HistoryBuildOptions::from_rebuild_profile(old.version.build_profile.clone()) - .map_err(|error| error.to_string())?; - let new_options = - HistoryBuildOptions::from_rebuild_profile(new.version.build_profile.clone()) - .map_err(|error| error.to_string())?; - if old_options.profile() == new_options.profile() { - let (_, old) = resolve_or_materialize_matching_profile( - repository, - old_commit, - &old_options, - false, - false, - )?; - let (history, new) = resolve_or_materialize_matching_profile( - repository, - new_commit, - &new_options, - false, - false, - )?; - (history, old, new) - } else { - return Err(format!( - "realizations retain different user-selected build options after current-engine reconstruction\n\nOLD {} ({}) profile: {}\nNEW {} ({}) profile: {}\n\nBuild a comparable realization:\n compass history build {} --profile-from {}", - old.version.git_commit, - old.id, - old.version.profile_digest, - new.version.git_commit, - new.id, - new.version.profile_digest, - new.version.git_commit, - old.version.git_commit, - )); - } - } - (Some(old), None) => { - let options = - HistoryBuildOptions::from_rebuild_profile(old.version.build_profile.clone()) - .map_err(|error| error.to_string())?; - let old = if old.version.build_profile == options.profile() { - old - } else { - resolve_or_materialize_matching_profile( - repository, old_commit, &options, true, false, - )? - .1 - }; - let (history, new) = resolve_or_materialize_matching_profile( - repository, new_commit, &options, false, false, - )?; - (history, old, new) - } - (None, Some(new)) => { - let options = - HistoryBuildOptions::from_rebuild_profile(new.version.build_profile.clone()) - .map_err(|error| error.to_string())?; - let new = if new.version.build_profile == options.profile() { - new - } else { - resolve_or_materialize_matching_profile( - repository, new_commit, &options, true, false, - )? - .1 - }; - let (history, old) = resolve_or_materialize_matching_profile( - repository, old_commit, &options, false, false, - )?; - (history, old, new) - } - (None, None) => { - let options = configured_build_options(repository)?; - let (_, old) = resolve_or_materialize_matching_profile( - repository, - old_commit.clone(), - &options, - false, - false, - )?; - let (history, new) = resolve_or_materialize_matching_profile( - repository, new_commit, &options, false, false, - )?; - (history, old, new) - } - }; + if old.is_none() { + return Err(format!( + "revision {old_commit} is not materialized; history diff is read-only and will not build it. Run `compass history build {old_commit} --code-only` first" + )); + } + if new.is_none() { + return Err(format!( + "revision {new_commit} is not materialized; history diff is read-only and will not build it. Run `compass history build {new_commit} --code-only` first" + )); + } + // Comparison is a read path. Profile reconstruction under a newer binary + // can differ from the published profile, so even an apparently cached + // pair must never pass through the materialization helper here. + let history = existing.ok_or_else(|| "history store disappeared".to_owned())?; + let old = old.ok_or_else(|| "old realization disappeared".to_owned())?; + let new = new.ok_or_else(|| "new realization disappeared".to_owned())?; let old_engine = engine_compatibility_digest(&old.version.build_profile)?; let new_engine = engine_compatibility_digest(&new.version.build_profile)?; if old_engine != new_engine { @@ -827,10 +773,8 @@ fn execute(frontend: Frontend, args: &[String]) -> Result Outcome { let mut failed = false; for platform in selected { let consumers = BTreeSet::from([platform.clone()]); - let adapter_snapshots = match snapshot_files(&uninstall_paths_for(&scope, &consumers)) { + let mut uninstall_paths = uninstall_paths_for(&scope, &consumers); + // Audit events are part of the managed transaction. Snapshot the + // bounded log alongside adapters so a failed uninstall can restore + // the exact pre-operation tree instead of leaving a misleading + // removal record behind after rollback. + uninstall_paths.push(state_event_path(scope.root())); + let adapter_snapshots = match snapshot_files(&uninstall_paths) { Ok(snapshots) => snapshots, Err(error) => { failed = true; @@ -1813,10 +1819,18 @@ fn uninstall_kilo_direct(root: &Path) -> Outcome { &format!("command removed: {}", command.display()), ); if is_managed_skill(&skill) { - let _ = fs::remove_file(&skill); - removed.push(format!("skill removed: {}", skill.display())); - let _ = fs::remove_file(skill.with_file_name(".compass_version")); - let _ = fs::remove_dir_all(skill.with_file_name("references")); + if fs::remove_file(&skill).is_ok() { + record_managed_path_event(root, "remove_managed_skill", &skill); + removed.push(format!("skill removed: {}", skill.display())); + } + let metadata = skill.with_file_name(".compass_version"); + if fs::remove_file(&metadata).is_ok() { + record_managed_path_event(root, "remove_managed_metadata", &metadata); + } + let references = skill.with_file_name("references"); + if fs::remove_dir_all(&references).is_ok() { + record_managed_path_event(root, "remove_managed_references", &references); + } } remove_empty_ancestors(&skill.with_file_name("placeholder"), &home); if removed.is_empty() && !removed_command { @@ -2034,6 +2048,17 @@ fn is_managed_skill(path: &Path) -> bool { parent.join(".compass_version").is_file() && legacy_skill_is_unmodified(parent) } +pub(crate) fn managed_skill_is_configured(path: &Path) -> bool { + let Some(parent) = path.parent() else { + return false; + }; + parent.join(".compass-install.json").is_file() || parent.join(".compass_version").is_file() +} + +pub(crate) fn managed_skill_is_healthy(path: &Path) -> bool { + !managed_skill_is_configured(path) || is_managed_skill(path) +} + fn install_skill( config: Platform, project: bool, @@ -2817,10 +2842,13 @@ fn remove_skill( } if path.exists() { match fs::remove_file(&path) { - Ok(()) => lines.push(format!( - " skill removed -> {}", - display_path(&path, project, project_dir) - )), + Ok(()) => { + record_managed_path_event(project_dir, "remove_managed_skill", &path); + lines.push(format!( + " skill removed -> {}", + display_path(&path, project, project_dir) + )); + } Err(error) => { lines.push(format!( "error: could not remove {}: {error}", @@ -2835,38 +2863,70 @@ fn remove_skill( parent.join(".compass_version"), parent.join(".compass-install.json"), ] { - if metadata.exists() - && let Err(error) = fs::remove_file(&metadata) - { - lines.push(format!( - "error: could not remove {}: {error}", - metadata.display() - )); + if metadata.exists() { + match fs::remove_file(&metadata) { + Ok(()) => { + record_managed_path_event(project_dir, "remove_managed_metadata", &metadata) + } + Err(error) => lines.push(format!( + "error: could not remove {}: {error}", + metadata.display() + )), + } } } let references = parent.join("references"); - if references.exists() - && let Err(error) = fs::remove_dir_all(&references) - { - lines.push(format!( - "error: could not remove {}: {error}", - references.display() - )); + if references.exists() { + match fs::remove_dir_all(&references) { + Ok(()) => { + record_managed_path_event(project_dir, "remove_managed_references", &references) + } + Err(error) => lines.push(format!( + "error: could not remove {}: {error}", + references.display() + )), + } } remove_empty_ancestors(&parent, if project { project_dir } else { Path::new("") }); } BTreeSet::new() } +fn record_managed_path_event(project_dir: &Path, event: &str, path: &Path) { + let output = state_event_path(project_dir) + .parent() + .map(Path::to_path_buf) + .unwrap_or_else(|| project_dir.join("compass-out")); + let _ = compass_files::BuildGuard::record_state_event(&output, event, path); +} + +fn state_event_path(project_dir: &Path) -> PathBuf { + env::var_os("COMPASS_OUT") + .map(PathBuf::from) + .unwrap_or_else(|| project_dir.join("compass-out")) + .join("state-events.jsonl") +} + fn uninstall_vscode(project_dir: &Path) -> Outcome { let mut lines = Vec::new(); if let Some(home) = home_directory() { let path = home.join(".copilot/skills/compass/SKILL.md"); if is_managed_skill(&path) && fs::remove_file(&path).is_ok() { + record_managed_path_event(project_dir, "remove_managed_skill", &path); lines.push(format!(" skill removed -> {}", path.display())); if let Some(parent) = path.parent() { - let _ = fs::remove_file(parent.join(".compass_version")); - let _ = fs::remove_dir_all(parent.join("references")); + let metadata = parent.join(".compass_version"); + if fs::remove_file(&metadata).is_ok() { + record_managed_path_event(project_dir, "remove_managed_metadata", &metadata); + } + let references = parent.join("references"); + if fs::remove_dir_all(&references).is_ok() { + record_managed_path_event( + project_dir, + "remove_managed_references", + &references, + ); + } } } } diff --git a/crates/compass-cli/src/lib.rs b/crates/compass-cli/src/lib.rs index dd4b26335..a7f69d270 100644 --- a/crates/compass-cli/src/lib.rs +++ b/crates/compass-cli/src/lib.rs @@ -62,6 +62,7 @@ use compass_global::{GlobalPaths, global_add}; use compass_graph::god_nodes; use compass_graphdb::{push_to_falkordb, push_to_neo4j}; use compass_model::GraphError; +use compass_model::code_graph::{EdgeKind, GraphDocument}; use compass_model::query_contract::{ CodeQueryLimits, DiscoveryDirection, DiscoveryLimits, DiscoveryQueryRequest, DiscoveryQueryResponse, DiscoveryScope, DiscoveryScopeKind, DiscoveryTraversal, ImpactRequest, @@ -73,12 +74,12 @@ use compass_output::{ HtmlOptions, ObsidianOptions, SourceNavigation, SvgOptions, TreeOptions, WikiOptions, WorkbenchCoverage, WorkbenchCoverageStatus, WorkbenchModel, WorkbenchView, WorkbenchViewContent, affected_lens_view_model, artifact_lens_view_model, - build_discovery_query_view, export_obsidian, export_wiki, graph_artifact_identity, - graph_community_view_model_document, graph_view_model_bundle_document, + build_code_query_view, build_discovery_query_view, export_obsidian, export_wiki, + graph_artifact_identity, graph_community_view_model_document, graph_view_model_bundle_document, graph_view_model_document, node_filenames, project_architecture, - render_agent_query_header_lines, render_orientation_json, validate_orientation_graph_identity, - write_callflow_html, write_canvas, write_cypher, write_graphml, write_svg, write_tree_html, - write_workbench_html_with_source_navigation, + render_agent_query_header_lines, render_agent_query_text, render_orientation_json, + validate_orientation_graph_identity, write_callflow_html, write_canvas, write_cypher, + write_graphml, write_svg, write_tree_html, write_workbench_html_with_source_navigation, }; use compass_prs::{ProcessRunner, SystemRunner}; use compass_query::{ @@ -148,6 +149,90 @@ pub struct Outcome { html_output: Option, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum SharedOutputFormat { + Text, + Json, + AgentJson, +} + +/// Parse the output contract shared by structural code-query commands and the +/// legacy path/explain projections. Keeping extraction here means every +/// command accepts both `--format value` and `--format=value` with identical +/// validation and does not accidentally treat the flag as a positional node. +pub(crate) fn parse_shared_output_format( + args: &[String], + command: &str, +) -> Result<(SharedOutputFormat, Vec), String> { + let mut format = SharedOutputFormat::Text; + let mut remaining = Vec::with_capacity(args.len()); + let mut index = 0; + while index < args.len() { + match args[index].as_str() { + "--format" => { + let Some(value) = args.get(index + 1) else { + return Err(format!( + "--format requires text, json, or agent-json for {command}" + )); + }; + format = parse_shared_output_format_value(value, command)?; + index += 2; + } + value if value.starts_with("--format=") => { + format = parse_shared_output_format_value(&value[9..], command)?; + index += 1; + } + _ => { + remaining.push(args[index].clone()); + index += 1; + } + } + } + Ok((format, remaining)) +} + +fn parse_shared_output_format_value( + value: &str, + command: &str, +) -> Result { + match value { + "text" => Ok(SharedOutputFormat::Text), + "json" => Ok(SharedOutputFormat::Json), + "agent-json" => Ok(SharedOutputFormat::AgentJson), + _ => Err(format!( + "--format must be text, json, or agent-json for {command}" + )), + } +} + +fn render_shared_output(format: SharedOutputFormat, command: &str, answer: String) -> Outcome { + match format { + SharedOutputFormat::Text => Outcome::success(answer), + SharedOutputFormat::Json => serde_json::to_string_pretty(&serde_json::json!({ + "schema": "compass.command-result/1", + "command": command, + "answer": answer, + "truncated": false, + })) + .map_or_else( + |error| Outcome::failure(format!("error: could not render JSON: {error}")), + Outcome::success, + ), + SharedOutputFormat::AgentJson => serde_json::to_string_pretty(&serde_json::json!({ + "schema": "compass.agent-command/1", + "command": command, + "answer": answer, + "status": "answered", + "truncated": false, + "nextActions": [], + })) + .map_or_else( + |error| Outcome::failure(format!("error: could not render agent JSON: {error}")), + Outcome::success, + ), + } +} + pub(crate) fn resolve_output_artifact(output: &Path, name: &str) -> Result { compass_files::BuildGuard::resolve_artifact(output, name).map_err(|error| error.to_string()) } @@ -392,6 +477,7 @@ pub fn run(frontend: Frontend, arguments: impl IntoIterator) -> "program" => program_commands::command(frontend, &args), "path" => command_path(frontend, &args), "explain" => command_explain(frontend, &args), + "architecture" => command_architecture(frontend, &args), "affected" => command_affected(&args), "export" => command_export(frontend, &args), "benchmark" => command_benchmark(&args), @@ -1745,6 +1831,98 @@ fn command_build_with_validation( outcome } +/// Report managed-state drift before a build publishes a new snapshot. These +/// checks are deliberately read-only and bounded: they inspect only canonical +/// marker paths and a capped snapshot directory listing, never source content +/// or credentials. A successful ensure still performs the normal repair, but +/// the operator gets an explicit explanation and a command they can run +/// independently when the drift is outside the build's ownership boundary. +fn collect_state_health_notes( + root: &Path, + output_directory: &Path, + graph_healthy: bool, +) -> Vec { + let mut notes = Vec::new(); + let record_attempt = |path: &Path| { + let _ = + compass_files::BuildGuard::record_state_event(output_directory, "repair_attempt", path); + }; + let project_config = root.join(".compass"); + if project_config.is_dir() && !graph_healthy { + record_attempt(Path::new("graph.json")); + notes.push(format!( + "[compass health] project configuration is present at {} but the graph snapshot is missing or invalid; ensure is rebuilding it", + project_config.display() + )); + } + + for (platform, relative) in [ + ("Claude", Path::new(".claude/skills/compass/SKILL.md")), + ("Agents", Path::new(".agents/skills/compass/SKILL.md")), + ] { + let managed_directory = root.join(relative).parent().map(Path::to_path_buf); + let skill = root.join(relative); + let configured = install_commands::managed_skill_is_configured(&skill); + let drifted = configured && !install_commands::managed_skill_is_healthy(&skill); + let missing_in_existing_directory = + managed_directory.as_deref().is_some_and(Path::is_dir) && !skill.is_file(); + if drifted || missing_in_existing_directory { + record_attempt(relative); + notes.push(format!( + "[compass health] {platform} managed skill is missing or modified at {}; repair with `compass install --platform {}`", + skill.display(), + platform.to_ascii_lowercase() + )); + } + } + + let snapshots = output_directory.join("snapshots"); + if snapshots.is_dir() { + let current = output_directory.join("current-snapshot"); + if !current.is_file() { + let has_entries = fs::read_dir(&snapshots) + .ok() + .and_then(|entries| entries.take(1).next()) + .is_some(); + if has_entries { + record_attempt(Path::new("current-snapshot")); + notes.push(format!( + "[compass health] output snapshots exist under {} but current-snapshot is missing; ensure will publish a fresh pointer", + snapshots.display() + )); + } + } else if let Err(error) = + compass_files::BuildGuard::resolve_current_snapshot_directory(output_directory) + { + record_attempt(Path::new("current-snapshot")); + notes.push(format!( + "[compass health] current snapshot is invalid or incomplete ({}); ensure will repair it", + error + )); + } + let has_incomplete = fs::read_dir(&snapshots) + .ok() + .into_iter() + .flat_map(|entries| entries.filter_map(Result::ok)) + .take(1_025) + .any(|entry| entry.path().join("build-incomplete").is_file()); + if has_incomplete { + record_attempt(Path::new("snapshots")); + notes.push(format!( + "[compass health] incomplete output snapshots were found under {}; ensure will discard or replace them", + snapshots.display() + )); + } + } else if output_directory.join("current-snapshot").is_file() { + record_attempt(Path::new("current-snapshot")); + notes.push(format!( + "[compass health] current-snapshot exists without its snapshots directory at {}; ensure will repair the orphaned pointer", + output_directory.display() + )); + } + notes +} + fn command_build_with_validation_inner( frontend: Frontend, args: &[String], @@ -2183,9 +2361,16 @@ fn command_build_with_validation_inner( .map(absolute_cli_path) .unwrap_or_else(|| root.clone()) .join(output_name); - let graph_existed_before = - compass_files::BuildGuard::resolve_artifact(&output_container, "graph.json") - .is_ok_and(|path| path.is_file()); + let graph_health_path = + compass_files::BuildGuard::resolve_artifact(&output_container, "graph.json").ok(); + let graph_existed_before = graph_health_path + .as_ref() + .is_some_and(|path| path.is_file()); + let graph_healthy = graph_health_path + .as_deref() + .filter(|path| path.is_file()) + .is_some_and(|path| GraphDocument::load(path).is_ok()); + let health_notes = collect_state_health_notes(&root, &output_container, graph_healthy); let extract_incremental = extract && !force && compass_files::BuildGuard::resolve_artifact(&output_container, "graph.json") @@ -2319,8 +2504,17 @@ fn command_build_with_validation_inner( .map(|result| (result, Vec::new(), Duration::ZERO)) .map_err(|error| error.to_string()) }; + let health_repair_needed = !health_notes.is_empty(); match built { Ok((result, mut notes, _semantic_elapsed)) => { + if health_repair_needed { + let _ = compass_files::BuildGuard::record_state_event( + &output_container, + "repair_succeeded", + Path::new("current-snapshot"), + ); + } + notes.extend(health_notes); if let Some(tiebreaker) = dedup_tiebreaker.as_mut() { notes.extend(tiebreaker.take_warnings()); } @@ -2417,6 +2611,13 @@ fn command_build_with_validation_inner( outcome } Err(error) => { + if health_repair_needed { + let _ = compass_files::BuildGuard::record_state_event( + &output_container, + "repair_failed", + Path::new("current-snapshot"), + ); + } let mut message = format!("error: {error}"); if document_ocr_mode != compass_ocr::OcrMode::Off && error.contains("compass models install pp-ocrv6-") @@ -5207,7 +5408,14 @@ pub(crate) fn command_natural_query(frontend: Frontend, args: &[String]) -> Outc { return Outcome::success(query_help(frontend)); } - let (selection, args) = match parse_graph_selection(args) { + let format_was_provided = args + .iter() + .any(|argument| argument == "--format" || argument.starts_with("--format=")); + let (shared_format, args) = match parse_shared_output_format(args, "query") { + Ok(parsed) => parsed, + Err(error) => return Outcome::failure(format!("error: {error}")), + }; + let (selection, args) = match parse_graph_selection(&args) { Ok(parsed) => parsed, Err(error) => return Outcome::failure(format!("error: {error}")), }; @@ -5219,7 +5427,7 @@ pub(crate) fn command_natural_query(frontend: Frontend, args: &[String]) -> Outc let mut page = 1_usize; let mode = TraversalMode::Bfs; let mut legacy_requested = false; - let mut discovery_requested = false; + let mut discovery_requested = format_was_provided; let mut discovery_text_budget = DEFAULT_DISCOVERY_TEXT_TOKEN_BUDGET; let mut discovery_cursor = None::; let mut discovery_evidence = false; @@ -5229,7 +5437,12 @@ pub(crate) fn command_natural_query(frontend: Frontend, args: &[String]) -> Outc let mut discovery_traversal = DiscoveryTraversal::Bfs; let mut discovery_include_heuristic = false; let mut discovery_limits = DiscoveryLimits::default(); - let mut discovery_format = "text".to_owned(); + let mut discovery_format = match shared_format { + SharedOutputFormat::Text => "text", + SharedOutputFormat::Json => "json", + SharedOutputFormat::AgentJson => "agent-json", + } + .to_owned(); let mut discovery_result_envelope = false; let mut seen_discovery_options = HashSet::new(); let mut index = 1; @@ -5295,7 +5508,7 @@ pub(crate) fn command_natural_query(frontend: Frontend, args: &[String]) -> Outc discovery_requested = true; index += 2; } - "--direction" | "--scope" | "--format" => { + "--direction" | "--scope" => { let name = args[index].as_str(); let Some(value) = args.get(index + 1) else { return Outcome::failure(format!("error: {name} requires a value")); @@ -5393,7 +5606,7 @@ pub(crate) fn command_natural_query(frontend: Frontend, args: &[String]) -> Outc index += 1; } value - if ["--direction=", "--scope=", "--format="] + if ["--direction=", "--scope="] .iter() .any(|prefix| value.starts_with(prefix)) => { @@ -5765,7 +5978,11 @@ fn command_path(frontend: Frontend, args: &[String]) -> Outcome { { return Outcome::success(path_help(frontend)); } - let (selection, args) = match parse_graph_selection(args) { + let (format, args) = match parse_shared_output_format(args, "path") { + Ok(parsed) => parsed, + Err(error) => return Outcome::failure(format!("error: {error}")), + }; + let (selection, args) = match parse_graph_selection(&args) { Ok(parsed) => parsed, Err(error) => return Outcome::failure(format!("error: {error}")), }; @@ -5816,12 +6033,179 @@ fn command_path(frontend: Frontend, args: &[String]) -> Outcome { match render_shortest_path_with_limit(&loaded.graph, source, target, max_depth) { Ok(output) => { touch_selected_query_stamp(&selection); - Outcome::success(output) + render_shared_output(format, "path", output) } Err(error) => Outcome::failure(error), } } +fn command_architecture(_frontend: Frontend, args: &[String]) -> Outcome { + if args + .iter() + .any(|argument| matches!(argument.as_str(), "-h" | "--help")) + { + return Outcome::success("Usage: compass architecture [--graph PATH] [--labels PATH] [--format text|json|agent-json]".to_owned()); + } + let (format, args) = match parse_shared_output_format(args, "architecture") { + Ok(parsed) => parsed, + Err(error) => return Outcome::failure(format!("error: {error}")), + }; + let mut graph_path = default_graph_path(); + let mut labels_path = None; + let mut index = 0; + while index < args.len() { + match args[index].as_str() { + "--graph" => { + let Some(value) = args.get(index + 1) else { + return Outcome::failure("error: --graph requires a path".to_owned()); + }; + graph_path = PathBuf::from(value); + index += 2; + } + value if value.starts_with("--graph=") => { + graph_path = PathBuf::from(&value[8..]); + index += 1; + } + "--labels" => { + let Some(value) = args.get(index + 1) else { + return Outcome::failure("error: --labels requires a path".to_owned()); + }; + labels_path = Some(PathBuf::from(value)); + index += 2; + } + value if value.starts_with("--labels=") => { + labels_path = Some(PathBuf::from(&value[9..])); + index += 1; + } + value if !value.starts_with('-') && index == 0 => { + graph_path = PathBuf::from(value); + index += 1; + } + value => { + return Outcome::failure(format!( + "error: unexpected architecture argument {value}" + )); + } + } + } + let graph_path = match compass_files::BuildGuard::resolve_requested_artifact(&graph_path) { + Ok(path) => path, + Err(error) => return Outcome::failure(format!("error: could not resolve graph: {error}")), + }; + let mut inputs = match ExportInputs::load(&graph_path) { + Ok(inputs) => inputs, + Err(GraphError::NotFound(_)) => { + return Outcome::failure(format!( + "error: graph not found: {}. Run `compass ensure` first.", + graph_path.display() + )); + } + Err(error) => return Outcome::failure(format!("error: {error}")), + }; + if let Some(labels_path) = labels_path { + match load_usize_string_map(&labels_path) { + Ok(labels) => inputs.labels = labels, + Err(error) => return Outcome::failure(error), + } + } + let title = export_project_title(&inputs, &graph_path); + let model = match architecture_view_model(&inputs, &graph_path, &title) { + Ok(model) => model, + Err(error) => return Outcome::failure(format!("error: {error}")), + }; + let text = render_architecture_text(&model); + match format { + SharedOutputFormat::Text => Outcome::success(text), + SharedOutputFormat::Json => serde_json::to_string_pretty(&model).map_or_else( + |error| { + Outcome::failure(format!( + "error: could not render architecture JSON: {error}" + )) + }, + Outcome::success, + ), + SharedOutputFormat::AgentJson => { + let mut value = match serde_json::to_value(&model) { + Ok(serde_json::Value::Object(value)) => value, + Ok(_) => { + return Outcome::failure( + "error: architecture model is not an object".to_owned(), + ); + } + Err(error) => { + return Outcome::failure(format!( + "error: could not render architecture agent JSON: {error}" + )); + } + }; + value.insert( + "schema".to_owned(), + serde_json::Value::String("compass.architecture.agent-view/1".to_owned()), + ); + value.insert("answer".to_owned(), serde_json::Value::String(text)); + value.insert( + "nextActions".to_owned(), + serde_json::Value::Array(Vec::new()), + ); + serde_json::to_string_pretty(&serde_json::Value::Object(value)).map_or_else( + |error| { + Outcome::failure(format!( + "error: could not render architecture agent JSON: {error}" + )) + }, + Outcome::success, + ) + } + } +} + +fn render_architecture_text(model: &compass_output::ArchitectureViewModel) -> String { + let mut lines = vec![ + format!("Architecture: {}", model.title), + format!( + "Graph: {} nodes, {} relationships, {} communities", + model.statistics.nodes, model.statistics.relationships, model.statistics.communities + ), + ]; + for projection in &model.projections { + lines.push(format!( + "Scope {:?}: {} groups, {} routes", + projection.scope, + projection.groups.len(), + projection.routes.len() + )); + for group in projection.groups.iter().take(24) { + lines.push(format!( + "- {} [{}] nodes={} relationships={} cohesion={:.2}", + group.name.value, + group.id, + group.node_count, + group.relationship_count, + group.cohesion + )); + } + if projection.omissions.omitted_groups > 0 { + lines.push(format!( + " Omitted {} groups ({} shown); witnesses: {}", + projection.omissions.omitted_groups, + projection.omissions.shown_groups, + if projection.omissions.witness_group_ids.is_empty() { + "none".to_owned() + } else { + projection.omissions.witness_group_ids.join(", ") + } + )); + } + for diagnostic in projection.quality.diagnostics.iter().take(8) { + lines.push(format!( + " Diagnostic [{}]: {}", + diagnostic.code, diagnostic.message + )); + } + } + lines.join("\n") +} + fn command_explain(frontend: Frontend, args: &[String]) -> Outcome { if args .iter() @@ -5829,7 +6213,11 @@ fn command_explain(frontend: Frontend, args: &[String]) -> Outcome { { return Outcome::success(explain_help(frontend)); } - let (selection, args) = match parse_graph_selection(args) { + let (format, args) = match parse_shared_output_format(args, "explain") { + Ok(parsed) => parsed, + Err(error) => return Outcome::failure(format!("error: {error}")), + }; + let (selection, args) = match parse_graph_selection(&args) { Ok(parsed) => parsed, Err(error) => return Outcome::failure(format!("error: {error}")), }; @@ -5893,7 +6281,7 @@ fn command_explain(frontend: Frontend, args: &[String]) -> Outcome { Err(error) => return Outcome::failure(format!("error: {error}")), }; touch_selected_query_stamp(&selection); - Outcome::success(output) + render_shared_output(format, "explain", output) } fn validate_text_pagination(token_budget: usize, page: usize) -> Result<(), String> { @@ -5907,9 +6295,13 @@ fn validate_text_pagination(token_budget: usize, page: usize) -> Result<(), Stri } fn command_affected(args: &[String]) -> Outcome { + let (format, args) = match parse_shared_output_format(args, "affected") { + Ok(parsed) => parsed, + Err(error) => return Outcome::failure(format!("error: {error}")), + }; let Some(query) = args.first() else { return Outcome::failure( - "Usage: compass affected \"\" [--relation R] [--depth N] [--graph path]" + "Usage: compass affected \"\" [--relation R] [--depth N] [--graph path] [--format text|json|agent-json]" .to_owned(), ); }; @@ -5967,11 +6359,137 @@ fn command_affected(args: &[String]) -> Outcome { .map(|relation| (*relation).to_owned()) .collect(); } + if let Some(output) = command_affected_typed(query, &graph_path, depth, &relations, format) { + return output; + } let loaded = match load_affected(&graph_path) { Ok(loaded) => loaded, Err(outcome) => return outcome, }; - Outcome::success(format_affected(&loaded.graph, query, &relations, depth)) + render_shared_output( + format, + "affected", + format_affected(&loaded.graph, query, &relations, depth), + ) +} + +/// Use the typed resolver for v1 code graphs so the compatibility `affected` +/// command shares import/reference recall with callers and impact. Legacy +/// node-link graphs still use the bounded compatibility traversal below. +fn command_affected_typed( + query: &str, + requested_graph: &Path, + depth: usize, + relations: &[String], + format: SharedOutputFormat, +) -> Option { + let resolved_graph = + match compass_files::BuildGuard::resolve_requested_artifact(requested_graph) { + Ok(path) => path, + Err(_) => return None, + }; + let (document, identity) = match GraphDocument::load_with_artifact_digest(&resolved_graph) { + Ok(document) => document, + Err(_) => return None, + }; + let cache_root = requested_graph + .parent() + .unwrap_or_else(|| Path::new(".")) + .join("cache"); + let engine = + match open_with_verified_document(document, identity, &resolved_graph, None, &cache_root) { + Ok(engine) => engine, + Err(error) => return Some(Outcome::failure(format!("error: {error}"))), + }; + let relation_kinds = relations + .iter() + .filter_map(|relation| affected_relation_kind(relation)) + .collect::>(); + if relation_kinds.is_empty() { + return Some(render_shared_output( + format, + "affected", + format!("No supported relationships were requested for {query:?}"), + )); + } + let max_depth = u32::try_from(depth).unwrap_or(u32::MAX); + let limits = CodeQueryLimits { + max_depth: max_depth.max(1), + ..CodeQueryLimits::default() + }; + let response = match engine.affected( + ImpactRequest { + symbol: query.to_owned(), + include_heuristic: false, + limits, + }, + &relation_kinds, + ) { + Ok(response) => response, + Err(error) => return Some(Outcome::failure(format!("error: {error}"))), + }; + let mut context = AgentQueryContext::new( + response.operation.into(), + engine.graph_identity().to_owned(), + engine.build_generation_identity().to_owned(), + ) + .with_operand(AgentOperandRole::Symbol, query.to_owned()); + context = context.with_question(format!("affected {query}")); + match format { + SharedOutputFormat::Text => Some( + build_code_query_view(&response, context) + .and_then(|view| render_agent_query_text(&view)) + .map_or_else( + |error| Outcome::failure(format!("error: {error}")), + Outcome::success, + ), + ), + SharedOutputFormat::Json => Some(serde_json::to_string_pretty(&response).map_or_else( + |error| Outcome::failure(format!("error: {error}")), + Outcome::success, + )), + SharedOutputFormat::AgentJson => Some( + build_code_query_view(&response, context) + .and_then(|view| serde_json::to_string_pretty(&view).map_err(Into::into)) + .map_or_else( + |error| Outcome::failure(format!("error: {error}")), + Outcome::success, + ), + ), + } +} + +fn affected_relation_kind(relation: &str) -> Option { + match relation + .trim() + .to_ascii_lowercase() + .replace('-', "_") + .as_str() + { + "calls" | "indirect_call" => Some(EdgeKind::Calls), + "imports" | "imports_from" => Some(EdgeKind::Imports), + "exports" | "re_exports" => Some(EdgeKind::Exports), + "references" => Some(EdgeKind::References), + "aliases" => Some(EdgeKind::Aliases), + "inherits" | "extends" => Some(EdgeKind::Extends), + "implements" => Some(EdgeKind::Implements), + "uses" => Some(EdgeKind::DependsOn), + "mixes_in" => Some(EdgeKind::MixesIn), + "embeds" => Some(EdgeKind::Embeds), + "routes_to" => Some(EdgeKind::RoutesTo), + "renders" => Some(EdgeKind::Renders), + "depends_on" => Some(EdgeKind::DependsOn), + "reads" => Some(EdgeKind::Reads), + "writes" => Some(EdgeKind::Writes), + "publishes" => Some(EdgeKind::Publishes), + "subscribes" => Some(EdgeKind::Subscribes), + "produces" => Some(EdgeKind::Produces), + "consumes" => Some(EdgeKind::Consumes), + "schedules" => Some(EdgeKind::Schedules), + "triggers" => Some(EdgeKind::Triggers), + "maps_to" => Some(EdgeKind::MapsTo), + _ => None, + } } pub(crate) fn parse_graph_selection( @@ -6086,7 +6604,7 @@ fn touch_selected_query_stamp(selection: &GraphSelection) { fn query_help(frontend: Frontend) -> String { let prefix = frontend_name(frontend); let help = format!( - "Usage: {prefix} query \"\" [--direction auto|incoming|outgoing|both] [--scope KIND:VALUE] [--context VALUE] [--dfs] [--evidence] [--format text|json] [--graph PATH|--at REV]\n\nNatural discovery options (default for a typed graph):\n --direction Direction: auto, incoming, outgoing, or both [default: auto]\n --scope Repeatable OR scope; KIND is community, source, package, or node\n --context Repeatable strict relationship-context filter\n --dfs Use depth-first expansion [default: breadth-first]\n --include-heuristic Include heuristic evidence [default: excluded]\n --evidence Include full provenance and typed detail in text\n --format Discovery output [default: text]\n --text-budget Approximate tokens in one text page [default: 8000]\n --cursor Continue the same immutable semantic result (text only)\n --max-depth Traversal depth [default: 2; hard maximum: 8]\n --max-seeds Ranked seed count [default: 3; hard maximum: 3]\n --max-candidates Ranked candidate count [default/hard maximum: 256]\n --max-nodes Returned node count [default/hard maximum: 500]\n --max-edges Returned edge count [default/hard maximum: 1000]\n --max-expanded-relationships Examined relationships [default/hard maximum: 10000]\n --max-response-bytes Serialized response bytes [default/hard maximum: 8388608]\n --timeout-ms Discovery deadline in milliseconds [default/hard maximum: 30000]\n\nLegacy traversal options:\n --traverse Force legacy relevance traversal\n --budget Approximate tokens per page [default: 2000]\n --page Result page, starting at 1 [default: 1]\n\nGraph selection:\n --graph Read a graph JSON file\n --at Resolve REV once to an immutable typed realization; conflicts with --graph\n\nCompassQL options:\n --cql Use CompassQL mode\n --timeout-ms CompassQL execution timeout\n --max-expanded-relationships CompassQL relationship expansion limit\n Run `{prefix} help query` for all CompassQL controls and examples.\n\nDiscovery limits must be positive; values above a hard maximum are rejected rather than clamped. JSON rejects text-only pagination/evidence controls. Legacy --traverse, --budget, and --page cannot be mixed with discovery controls." + "Usage: {prefix} query \"\" [--direction auto|incoming|outgoing|both] [--scope KIND:VALUE] [--context VALUE] [--dfs] [--evidence] [--format text|agent-json|json] [--graph PATH|--at REV]\n\nNatural discovery options (default for a typed graph):\n --direction Direction: auto, incoming, outgoing, or both [default: auto]\n --scope Repeatable OR scope; KIND is community, source, package, or node\n --context Repeatable strict relationship-context filter\n --dfs Use depth-first expansion [default: breadth-first]\n --include-heuristic Include heuristic evidence [default: excluded]\n --evidence Include full provenance and typed detail in text\n --format Discovery output [default: text]\n --text-budget Approximate tokens in one text page [default: 8000]\n --cursor Continue the same immutable semantic result (text only)\n --max-depth Traversal depth [default: 2; hard maximum: 8]\n --max-seeds Ranked seed count [default: 3; hard maximum: 3]\n --max-candidates Ranked candidate count [default/hard maximum: 256]\n --max-nodes Returned node count [default/hard maximum: 500]\n --max-edges Returned edge count [default/hard maximum: 1000]\n --max-expanded-relationships Examined relationships [default/hard maximum: 10000]\n --max-response-bytes Serialized response bytes [default/hard maximum: 8388608]\n --timeout-ms Discovery deadline in milliseconds [default/hard maximum: 30000]\n\nLegacy traversal options:\n --traverse Force legacy relevance traversal\n --budget Approximate tokens per page [default: 2000]\n --page Result page, starting at 1 [default: 1]\n\nGraph selection:\n --graph Read a graph JSON file\n --at Resolve REV once to an immutable typed realization; conflicts with --graph\n\nCompassQL options:\n --cql Use CompassQL mode\n --timeout-ms CompassQL execution timeout\n --max-expanded-relationships CompassQL relationship expansion limit\n Run `{prefix} help query` for all CompassQL controls and examples.\n\nDiscovery limits must be positive; values above a hard maximum are rejected rather than clamped. JSON rejects text-only pagination/evidence controls. Legacy --traverse, --budget, and --page cannot be mixed with discovery controls." ); let help = help .replace( @@ -6105,13 +6623,15 @@ fn query_help(frontend: Frontend) -> String { fn path_help(frontend: Frontend) -> String { let prefix = frontend_name(frontend); format!( - "Usage: {prefix} path \"\" \"\" [--max-depth N] [--graph PATH|--at REV]" + "Usage: {prefix} path \"\" \"\" [--max-depth N] [--format text|json|agent-json] [--graph PATH|--at REV]" ) } fn explain_help(frontend: Frontend) -> String { let prefix = frontend_name(frontend); - format!("Usage: {prefix} explain \"\" [--budget N] [--page N] [--graph PATH|--at REV]") + format!( + "Usage: {prefix} explain \"\" [--budget N] [--page N] [--format text|json|agent-json] [--graph PATH|--at REV]" + ) } fn frontend_name(frontend: Frontend) -> &'static str { diff --git a/crates/compass-cli/tests/code_query_cli.rs b/crates/compass-cli/tests/code_query_cli.rs index 12a139652..01441fb31 100644 --- a/crates/compass-cli/tests/code_query_cli.rs +++ b/crates/compass-cli/tests/code_query_cli.rs @@ -7,7 +7,7 @@ use compass_cli::{Frontend, run}; use compass_files::BuildGuard; use compass_graph::GraphSnapshotBuilder; use compass_model::code_graph::{EdgeKind, GraphDocument}; -use compass_output::AgentQueryView; +use compass_output::{AgentOperation, AgentQueryView}; use compass_store::{STORE_FILE_NAME, STORE_REF_FILE_NAME, SqliteStore}; use serde_json::Value; @@ -101,6 +101,60 @@ fn typed_query_commands_share_the_versioned_json_contract() -> Result<(), Box Result<(), Box> { + let directory = tempfile::tempdir()?; + let graph = support::write_typed_graph(directory.path())?; + let graph = graph.into_os_string(); + for format in ["text", "json", "agent-json"] { + let outcome = run( + Frontend::Compass, + [ + OsString::from("affected"), + OsString::from("Target"), + OsString::from("--relation"), + OsString::from("calls"), + OsString::from("--graph"), + graph.clone(), + OsString::from("--format"), + OsString::from(format), + ], + ); + assert_eq!(outcome.code, 0, "{format}: {}", outcome.stderr); + if format == "json" { + let value: Value = serde_json::from_str(&outcome.stdout)?; + assert_eq!(value["operation"], "impact"); + } else if format == "agent-json" { + let view = AgentQueryView::from_json(outcome.stdout.as_bytes())?; + assert_eq!(view.request.operation, AgentOperation::Impact); + } else { + assert!(outcome.stdout.contains("Target"), "{}", outcome.stdout); + } + } + Ok(()) +} + +#[test] +fn architecture_command_is_bounded_and_agent_readable() -> Result<(), Box> { + let directory = tempfile::tempdir()?; + let graph = support::write_typed_graph(directory.path())?; + let output = run( + Frontend::Compass, + [ + OsString::from("architecture"), + OsString::from("--graph"), + graph.into_os_string(), + OsString::from("--format"), + OsString::from("agent-json"), + ], + ); + assert_eq!(output.code, 0, "{}", output.stderr); + let value: Value = serde_json::from_str(&output.stdout)?; + assert_eq!(value["schema"], "compass.architecture.agent-view/1"); + assert!(value["answer"].as_str().is_some()); + Ok(()) +} + #[test] fn typed_ask_rejects_conflicting_current_and_revision_graph_sources() -> Result<(), Box> { diff --git a/crates/compass-cli/tests/history_cli.rs b/crates/compass-cli/tests/history_cli.rs index c9431bfad..e3ab96b87 100644 --- a/crates/compass-cli/tests/history_cli.rs +++ b/crates/compass-cli/tests/history_cli.rs @@ -424,8 +424,7 @@ fn explicit_build_uses_the_enabled_repository_profile_when_no_profile_options_ar } #[test] -fn lazy_materialization_uses_the_retained_profile_after_eager_history_is_disabled() --> Result<(), Box> { +fn uncached_history_reads_require_an_explicit_build() -> Result<(), Box> { let directory = tempfile::tempdir()?; git(directory.path(), &["init", "--quiet"])?; git(directory.path(), &["config", "user.name", "Compass Test"])?; @@ -464,6 +463,24 @@ fn lazy_materialization_uses_the_retained_profile_after_eager_history_is_disable directory.path(), &["query", "DisabledProfileService", "--at", "HEAD"], )?; + assert!(!query.status.success()); + assert!(String::from_utf8_lossy(&query.stderr).contains("not materialized")); + + let built = run( + compass, + directory.path(), + &["history", "build", "HEAD", "--code-only"], + )?; + assert!( + built.status.success(), + "{}", + String::from_utf8_lossy(&built.stderr) + ); + let query = run( + compass, + directory.path(), + &["query", "DisabledProfileService", "--at", "HEAD"], + )?; assert!( query.status.success(), "{}", @@ -1867,7 +1884,8 @@ fn change_counts_report_structure_instead_of_shifted_source_coordinates() } #[test] -fn missing_code_only_commit_is_built_on_first_query() -> Result<(), Box> { +fn missing_code_only_commit_requires_an_explicit_build_before_query() +-> Result<(), Box> { let directory = tempfile::tempdir()?; git(directory.path(), &["init", "--quiet"])?; git(directory.path(), &["config", "user.name", "Compass Test"])?; @@ -1894,11 +1912,26 @@ fn missing_code_only_commit_is_built_on_first_query() -> Result<(), Box Result<(), Box Result<(), Box> { let directory = tempfile::tempdir()?; git(directory.path(), &["init", "--quiet"])?; @@ -2097,6 +2130,26 @@ fn build_rebuild_and_unseen_diff_publish_complete_realizations() ], )?; assert!(enabled.status.success()); + for revision in ["HEAD~1", "HEAD"] { + let built = run( + compass, + directory.path(), + &[ + "history", + "build", + revision, + "--code-only", + "--exclude", + "generated/**", + "--format=json", + ], + )?; + assert!( + built.status.success(), + "{revision}: {}", + String::from_utf8_lossy(&built.stderr) + ); + } let diff = run( compass, directory.path(), @@ -2138,8 +2191,8 @@ fn build_rebuild_and_unseen_diff_publish_complete_realizations() })); drop(history); let progress = String::from_utf8_lossy(&diff.stderr); - assert!(progress.contains("building complete graph")); - assert!(progress.contains("publishing immutable realization")); + assert!(!progress.contains("building complete graph")); + assert!(!progress.contains("publishing immutable realization")); let first = run( compass, @@ -2236,6 +2289,18 @@ fn semantic_diff_end_to_end_languages() -> Result<(), Box &["history", "enable", "--code-only"], )?; assert!(enabled.status.success()); + for revision in ["HEAD~1", "HEAD"] { + let built = run( + compass, + directory.path(), + &["history", "build", revision, "--code-only", "--format=json"], + )?; + assert!( + built.status.success(), + "{file} {revision}: {}", + String::from_utf8_lossy(&built.stderr) + ); + } let diff = run( compass, directory.path(), diff --git a/crates/compass-files/src/build_guard.rs b/crates/compass-files/src/build_guard.rs index 1de17cea9..bb9d3a68f 100644 --- a/crates/compass-files/src/build_guard.rs +++ b/crates/compass-files/src/build_guard.rs @@ -1,4 +1,5 @@ use std::fs::{self, OpenOptions}; +use std::io::Write; use std::path::{Component, Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -12,6 +13,8 @@ const INCOMPLETE_MARKER: &str = "build-incomplete"; const ROOT_ARTIFACTS_COMPLETE: &str = "root-artifacts-complete"; const RETAINED_COMPLETE_SNAPSHOTS: usize = 2; const MAX_SNAPSHOT_DIRECTORY_ENTRIES: usize = 1_024; +const STATE_EVENTS_FILE: &str = "state-events.jsonl"; +const STATE_EVENTS_MAX_BYTES: u64 = 1_048_576; static SNAPSHOT_SEQUENCE: AtomicU64 = AtomicU64::new(0); /// Owns an unpublished output snapshot until every authoritative artifact is sealed. @@ -178,6 +181,17 @@ impl BuildGuard { } } + /// Append one bounded, metadata-only managed-state audit event. Callers + /// use this for health-check repair attempts and outcomes; snapshot + /// publication and pruning record their own events internally. + pub fn record_state_event( + output_directory: &Path, + event: &str, + path: &Path, + ) -> Result<(), FileError> { + append_state_event(output_directory, event, path) + } + /// Return the stable output container that owns a generated artifact. /// /// Paths inside the current immutable snapshot map back to their public @@ -334,7 +348,16 @@ fn profile_internal_duration(label: &str, elapsed: Duration) { fn remove_file_if_exists(path: &Path) -> Result<(), FileError> { match fs::remove_file(path) { - Ok(()) => sync_directory(path.parent().unwrap_or_else(|| Path::new("."))), + Ok(()) => { + let parent = path.parent().unwrap_or_else(|| Path::new(".")); + let result = sync_directory(parent); + if result.is_ok() + && path.file_name().and_then(|name| name.to_str()) != Some(STATE_EVENTS_FILE) + { + let _ = append_state_event(parent, "remove_file", path); + } + result + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(error) => Err(io_error(path, error)), } @@ -363,12 +386,69 @@ fn prune_complete_snapshots(snapshots: &Path, current: &str) -> Result<(), FileE .collect::>(); for entry in complete { if !retained.contains(&entry.file_name()) { - fs::remove_dir_all(entry.path()).map_err(|source| io_error(entry.path(), source))?; + let path = entry.path(); + fs::remove_dir_all(&path).map_err(|source| io_error(path.clone(), source))?; + if let Some(output) = snapshots.parent() { + let _ = append_state_event(output, "prune_snapshot", &path); + } } } sync_directory(snapshots) } +fn append_state_event(output_directory: &Path, event: &str, path: &Path) -> Result<(), FileError> { + fs::create_dir_all(output_directory).map_err(|source| io_error(output_directory, source))?; + let log_path = output_directory.join(STATE_EVENTS_FILE); + let relative = path + .strip_prefix(output_directory) + .unwrap_or(path) + .to_string_lossy() + .replace('\\', "/"); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let record = serde_json::json!({ + "schema": "compass.state-event/1", + "timestamp": timestamp, + "event": event, + "path": relative, + }); + let line = serde_json::to_string(&record).map_err(|source| FileError::Json { + path: log_path.clone(), + source, + })?; + let line_bytes = u64::try_from(line.len()) + .unwrap_or(u64::MAX) + .saturating_add(1); + if line_bytes > STATE_EVENTS_MAX_BYTES { + return Err(FileError::InvalidSnapshotArtifact(log_path)); + } + let current_bytes = fs::metadata(&log_path) + .map(|metadata| metadata.len()) + .unwrap_or(0); + if current_bytes.saturating_add(line_bytes) > STATE_EVENTS_MAX_BYTES { + remove_file_if_exists_unlogged(&log_path)?; + } + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(&log_path) + .map_err(|source| io_error(&log_path, source))?; + file.write_all(line.as_bytes()) + .and_then(|_| file.write_all(b"\n")) + .and_then(|_| file.sync_all()) + .map_err(|source| io_error(&log_path, source)) +} + +fn remove_file_if_exists_unlogged(path: &Path) -> Result<(), FileError> { + match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(io_error(path, error)), + } +} + impl Drop for BuildGuard { fn drop(&mut self) { if !self.committed { @@ -471,4 +551,37 @@ mod tests { ); Ok(()) } + + #[test] + fn state_events_are_bounded_and_record_managed_removals() -> Result<(), FileError> { + let directory = tempfile::tempdir().map_err(|source| io_error("tempdir", source))?; + let output = directory.path().join("compass-out"); + fs::create_dir_all(&output).map_err(|source| io_error(&output, source))?; + let removed = output.join("old.json"); + fs::write(&removed, b"old").map_err(|source| io_error(&removed, source))?; + remove_file_if_exists(&removed)?; + let log = output.join(STATE_EVENTS_FILE); + let event: serde_json::Value = serde_json::from_str( + fs::read_to_string(&log) + .map_err(|source| io_error(&log, source))? + .trim(), + ) + .map_err(|source| FileError::Json { + path: log.clone(), + source, + })?; + assert_eq!(event["schema"], "compass.state-event/1"); + assert_eq!(event["event"], "remove_file"); + assert_eq!(event["path"], "old.json"); + + let max_bytes = usize::try_from(STATE_EVENTS_MAX_BYTES) + .map_err(|_| FileError::InvalidSnapshotArtifact(log.clone()))?; + fs::write(&log, vec![b'x'; max_bytes]).map_err(|source| io_error(&log, source))?; + append_state_event(&output, "repair_attempt", &output.join("graph.json"))?; + let bytes = fs::metadata(&log) + .map_err(|source| io_error(&log, source))? + .len(); + assert!(bytes <= STATE_EVENTS_MAX_BYTES); + Ok(()) + } } diff --git a/crates/compass-graph/src/snapshot.rs b/crates/compass-graph/src/snapshot.rs index b5a7a5549..586f290b2 100644 --- a/crates/compass-graph/src/snapshot.rs +++ b/crates/compass-graph/src/snapshot.rs @@ -38,6 +38,8 @@ pub const IDENTIFIER_SUBWORD_INDEX_CAPABILITY_V1: &str = "__compass_cap_identifi pub const OPERATION_ROLE_TERM_INDEX_CAPABILITY_V1: &str = "__compass_cap_operation_role_terms_v1__"; pub const DECLARATION_TERM_INDEX_CAPABILITY_V1: &str = "__compass_cap_declaration_terms_v1__"; pub const RELATIONSHIP_TERM_INDEX_CAPABILITY_V1: &str = "__compass_cap_relationship_terms_v1__"; +pub const RELATIONSHIP_SEARCH_TERM_INDEX_CAPABILITY_V1: &str = + "__compass_cap_relationship_search_terms_v1__"; const EDGE_ID_ORDERED_ADJACENCY_CAPABILITY_V1: &str = "compass.edge-id-ordered-adjacency/1"; pub const GRAPH_SNAPSHOT_OBJECT_PARTITION: &str = "graph-snapshot/objects"; pub const GRAPH_SNAPSHOT_CATALOG_PARTITION: &str = "graph-snapshot/catalog"; @@ -2465,6 +2467,28 @@ impl<'a, S: Store + ?Sized> GraphSnapshotReader<'a, S> { Ok(posting.term == capability && posting.node_ids.is_empty()) } + /// Whether this snapshot carries the broad relationship-search postings. + /// Older immutable snapshots remain readable and fall back to their + /// direct-call postings in the query layer. + pub fn supports_relationship_search_terms(&self) -> Result { + let capability = RELATIONSHIP_SEARCH_TERM_INDEX_CAPABILITY_V1; + let posting_prefix = capability.get(..3).unwrap_or(capability); + let key = encode_graph_index_key( + IndexKind::Terms, + &[ + b"relationship_search_source", + posting_prefix.as_bytes(), + capability.as_bytes(), + b"00000000", + ], + )?; + let Some(value) = self.lookup(IndexKind::Terms, &key)? else { + return Ok(false); + }; + let posting = decode_json::(&value)?; + Ok(posting.term == capability && posting.node_ids.is_empty()) + } + /// Return sorted source IDs from one exact direct-caller concept posting. pub fn source_ids_for_exact_relationship_term_bounded_work( &self, @@ -2520,6 +2544,63 @@ impl<'a, S: Store + ?Sized> GraphSnapshotReader<'a, S> { Ok((source_ids.into_iter().collect(), truncated, work)) } + /// Return source IDs from the broader relationship-search posting used by + /// callers, impact, and affected. The legacy direct-call posting above is + /// intentionally kept separate for compatibility with older consumers. + pub fn source_ids_for_exact_relationship_search_term_bounded_work( + &self, + term: &str, + limits: SnapshotReadLimits, + ) -> Result<(Vec, bool, TermPostingWork), SnapshotError> { + let normalized = normalize_search_term(term); + if normalized.is_empty() { + return Ok((Vec::new(), false, TermPostingWork::default())); + } + let chunk_limit = limits.max_items / GRAPH_TERM_POSTING_CHUNK_ITEMS; + if chunk_limit == 0 { + return Ok((Vec::new(), true, TermPostingWork::default())); + } + let posting_prefix = normalized + .get(..normalized.len().min(3)) + .unwrap_or(normalized.as_str()); + let prefix = encode_graph_index_key( + IndexKind::Terms, + &[ + b"relationship_search_source", + posting_prefix.as_bytes(), + normalized.as_bytes(), + ], + )?; + let (values, mut truncated) = self.scan_values_bounded( + IndexKind::Terms, + Some(&prefix), + SnapshotReadLimits { + max_items: chunk_limit, + ..limits + }, + )?; + let mut source_ids = BTreeSet::new(); + let mut work = TermPostingWork::default(); + for value in values { + let posting = decode_json::(&value)?; + work.chunks_decoded = work.chunks_decoded.saturating_add(1); + work.node_ids_decoded = work + .node_ids_decoded + .saturating_add(u64::try_from(posting.node_ids.len()).unwrap_or(u64::MAX)); + if normalize_search_term(&posting.term) != normalized { + continue; + } + for source_id in posting.node_ids { + source_ids.insert(source_id); + if source_ids.len() > limits.max_items { + source_ids.pop_last(); + truncated = true; + } + } + } + Ok((source_ids.into_iter().collect(), truncated, work)) + } + /// Test one exact direct-caller concept membership. pub fn relationship_source_matches_term( &self, @@ -3506,9 +3587,9 @@ fn build_index( node_ids: Vec::new(), }, )?; - let relationship_postings = + let direct_relationship_postings = compass_model::search::direct_call_source_identifier_postings(graph); - for (term, source_ids) in &relationship_postings { + for (term, source_ids) in &direct_relationship_postings { for source_id in source_ids { insert_json( &mut entries, @@ -3580,6 +3661,85 @@ fn build_index( node_ids: Vec::new(), }, )?; + + let relationship_search_postings = + compass_model::search::relationship_source_identifier_postings(graph); + for (term, source_ids) in &relationship_search_postings { + for source_id in source_ids { + insert_json( + &mut entries, + encode_graph_index_key( + IndexKind::Terms, + &[ + b"relationship_search_source_member", + source_id.as_bytes(), + term.as_bytes(), + ], + )?, + &(), + )?; + } + let prefix = term.get(..term.len().min(3)).unwrap_or(term.as_str()); + for (chunk_index, chunk) in source_ids + .chunks(GRAPH_TERM_POSTING_CHUNK_ITEMS) + .enumerate() + { + let chunk_index = format!("{chunk_index:08}"); + insert_json( + &mut entries, + encode_graph_index_key( + IndexKind::Terms, + &[ + b"relationship_search_source", + prefix.as_bytes(), + term.as_bytes(), + chunk_index.as_bytes(), + ], + )?, + &TermPostingChunk { + term: term.clone(), + node_ids: chunk.to_vec(), + }, + )?; + } + } + for (term, source_id, target_id) in + compass_model::search::relationship_source_identifier_targets(graph) + { + insert_json( + &mut entries, + encode_graph_index_key( + IndexKind::Terms, + &[ + b"relationship_search_source_target", + source_id.as_bytes(), + term.as_bytes(), + target_id.as_bytes(), + ], + )?, + &(), + )?; + } + let relationship_search_capability = RELATIONSHIP_SEARCH_TERM_INDEX_CAPABILITY_V1; + let relationship_search_prefix = relationship_search_capability + .get(..3) + .unwrap_or(relationship_search_capability); + insert_json( + &mut entries, + encode_graph_index_key( + IndexKind::Terms, + &[ + b"relationship_search_source", + relationship_search_prefix.as_bytes(), + relationship_search_capability.as_bytes(), + b"00000000", + ], + )?, + &TermPostingChunk { + term: relationship_search_capability.to_owned(), + node_ids: Vec::new(), + }, + )?; for node in &graph.nodes { for (kind, value, canonical) in compass_model::query_contract::discovery_scope_postings(node) diff --git a/crates/compass-model/src/query_contract.rs b/crates/compass-model/src/query_contract.rs index 5e2b30205..3a87f30cd 100644 --- a/crates/compass-model/src/query_contract.rs +++ b/crates/compass-model/src/query_contract.rs @@ -469,7 +469,7 @@ impl Default for CodeQueryLimits { max_nodes: 500, max_edges: 1_000, max_paths: 100, - max_candidates: 20, + max_candidates: 64, max_source_bytes: 1_048_576, max_response_bytes: 8_388_608, } @@ -652,6 +652,7 @@ pub struct QueryDiagnostic { pub enum QueryDiagnosticCode { NoMatch, AmbiguousMatch, + RelationshipInconsistency, DirectionMismatch, UnresolvedHandler, IncompleteCoverage, diff --git a/crates/compass-model/src/search.rs b/crates/compass-model/src/search.rs index 1a4560d87..39c4da463 100644 --- a/crates/compass-model/src/search.rs +++ b/crates/compass-model/src/search.rs @@ -10,6 +10,20 @@ pub const OPERATION_ROLE_TOKENS: &[&str] = &[ "builder", "factory", "handler", "manager", "provider", "service", ]; +/// Structural relationships that can establish a source-backed dependency +/// on a named target. The structural relationship commands use the bounded +/// postings derived from these kinds so importer recall does not depend on a +/// narrower direct-call-only index. +pub const RELATIONSHIP_SEARCH_EDGE_KINDS: &[EdgeKind] = &[ + EdgeKind::Calls, + EdgeKind::Imports, + EdgeKind::Exports, + EdgeKind::References, + EdgeKind::Aliases, + EdgeKind::RoutesTo, + EdgeKind::DependsOn, +]; + /// Return deterministic normalized full and identifier-subword terms. /// /// The full tokens preserve compatibility with existing search indexes while @@ -93,6 +107,96 @@ pub fn direct_call_source_identifier_targets( targets } +/// Return exact source postings for all source-backed dependency +/// relationships, not only direct calls. Existing callers use the direct +/// call helpers for compatibility; relationship commands use this broader +/// index to recover import/reference consumers whose canonical edge points at +/// a file or module owner rather than the resolved declaration. +#[must_use] +pub fn relationship_source_identifier_postings( + graph: &GraphDocument, +) -> BTreeMap> { + let mut postings = BTreeMap::>::new(); + for (concept, source_id, _) in relationship_source_identifier_targets(graph) { + postings.entry(concept).or_default().insert(source_id); + } + postings + .into_iter() + .map(|(concept, source_ids)| (concept, source_ids.into_iter().collect())) + .collect() +} + +/// Return deterministic `(concept, source ID, target ID)` evidence for all +/// trusted source-backed dependency relationships. +#[must_use] +pub fn relationship_source_identifier_targets( + graph: &GraphDocument, +) -> BTreeSet<(String, String, String)> { + let nodes = graph + .nodes + .iter() + .map(|node| (node.id.as_str(), node)) + .collect::>(); + let mut aliases_by_target = BTreeMap::<&str, BTreeSet<&str>>::new(); + for edge in &graph.links { + if edge.kind == EdgeKind::Aliases + && let Some(alias) = nodes.get(edge.source.as_str()) + { + aliases_by_target + .entry(edge.target.as_str()) + .or_default() + .insert(alias.name.as_str()); + } + } + let mut targets = BTreeSet::new(); + for edge in &graph.links { + if !RELATIONSHIP_SEARCH_EDGE_KINDS.contains(&edge.kind) + || !is_exact_nonheuristic_relationship(edge) + { + continue; + } + let (Some(source), Some(target)) = ( + nodes.get(edge.source.as_str()), + nodes.get(edge.target.as_str()), + ) else { + continue; + }; + if source + .source_file() + .is_none_or(|source_file| source_file.is_empty()) + { + continue; + } + let mut terms = identifier_search_terms(&target.name); + terms.extend(identifier_search_terms(&target.qualified_name)); + if let Some(source_file) = target.source_file() { + terms.extend(identifier_search_terms(source_file)); + } + for alias in aliases_by_target + .get(target.id.as_str()) + .into_iter() + .flat_map(|aliases| aliases.iter()) + { + terms.extend(identifier_search_terms(alias)); + } + for concept in terms { + targets.insert((concept, source.id.clone(), target.id.clone())); + } + } + targets +} + +/// Whether an edge is safe to use as exact relationship-search evidence. +/// Empty evidence is retained for legacy graph documents; explicit heuristic +/// evidence is excluded from the exact postings. +#[must_use] +pub fn is_exact_nonheuristic_relationship(edge: &crate::code_graph::EdgeRecord) -> bool { + edge.evidence.iter().all(|evidence| { + evidence.origin != EvidenceOrigin::Heuristic + && evidence.confidence == EvidenceConfidence::Exact + }) +} + /// Whether an occurrence is trusted as an exact direct call for relationship /// discovery. Empty evidence remains accepted for legacy structural graphs; /// any explicit evidence must be exact and nonheuristic. @@ -134,7 +238,7 @@ mod tests { use super::{ direct_call_source_identifier_postings, direct_call_source_identifier_targets, - identifier_search_terms, + identifier_search_terms, relationship_source_identifier_postings, }; #[test] @@ -272,5 +376,25 @@ mod tests { 1, "parallel calls must not duplicate supporting target identity" ); + + let mut aliased_importer = + source("aliased-importer", NodeKind::Variable, Some("src/app.ts")); + aliased_importer.name = "pkg_import".to_owned(); + let mut alias_edge = edge("alias-edge", "aliased-importer", None); + alias_edge.target = "target".to_owned(); + alias_edge.kind = EdgeKind::Aliases; + graph.nodes.push(aliased_importer); + graph.links.push(alias_edge); + let relationship_postings = relationship_source_identifier_postings(&graph); + assert!( + relationship_postings + .get("namespace") + .is_some_and(|sources| sources.contains(&"caller".to_owned())) + ); + assert!( + relationship_postings + .get("pkg") + .is_some_and(|sources| sources.contains(&"aliased-importer".to_owned())) + ); } } diff --git a/crates/compass-output/assets/viewer/graph.js b/crates/compass-output/assets/viewer/graph.js index a8c548c52..e282571b5 100644 --- a/crates/compass-output/assets/viewer/graph.js +++ b/crates/compass-output/assets/viewer/graph.js @@ -69,7 +69,7 @@ Error generating stack: `+C.message+` `)}v.write("payload.value = newResult;"),v.write("return payload;");const S=v.compile();return(_,B)=>S(m,_,B)};let r;const A=Lr,I=!ic.jitless,c=I&&LN.value,h=e.catchall;let p;n._zod.parse=(m,v)=>{p??(p=i.value);const x=m.value;return A(x)?I&&c&&v?.async===!1&&v.jitless!==!0?(r||(r=o(e.shape)),m=r(m,v),h?Im([],x,m,v,p,n):m):t(m,v):(m.issues.push({expected:"object",code:"invalid_type",input:x,inst:n}),m)}});function lm(n,e,t,i){for(const r of n)if(r.issues.length===0)return e.value=r.value,e;const o=n.filter(r=>!ls(r));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(r=>r.issues.map(A=>Xi(A,i,Qi())))}),e)}const cm=$("$ZodUnion",(n,e)=>{Mt.init(n,e),It(n._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),It(n._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),It(n._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),It(n._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){const i=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>sc(o.source)).join("|")})$`)}});const t=e.options.length===1?e.options[0]._zod.run:null;n._zod.parse=(i,o)=>{if(t)return t(i,o);let r=!1;const A=[];for(const I of e.options){const l=I._zod.run({value:i.value,issues:[]},o);if(l instanceof Promise)A.push(l),r=!0;else{if(l.issues.length===0)return l;A.push(l)}}return r?Promise.all(A).then(I=>lm(I,i,n,o)):lm(A,i,n,o)}}),Ok=$("$ZodDiscriminatedUnion",(n,e)=>{e.inclusive=!1,cm.init(n,e);const t=n._zod.parse;It(n._zod,"propValues",()=>{const o={};for(const r of e.options){const A=r._zod.propValues;if(!A||Object.keys(A).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(const[I,l]of Object.entries(A)){o[I]||(o[I]=new Set);for(const c of l)o[I].add(c)}}return o});const i=UA(()=>{const o=e.options,r=new Map;for(const A of o){const I=A._zod.propValues?.[e.discriminator];if(!I||I.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(A)}"`);for(const l of I){if(r.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);r.set(l,A)}}return r});n._zod.parse=(o,r)=>{const A=o.value;if(!Lr(A))return o.issues.push({code:"invalid_type",expected:"object",input:A,inst:n}),o;const I=i.value.get(A?.[e.discriminator]);return I?I._zod.run(o,r):e.unionFallback||r.direction==="backward"?t(o,r):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(i.value.keys()),input:A,path:[e.discriminator],inst:n}),o)}}),Nk=$("$ZodIntersection",(n,e)=>{Mt.init(n,e),n._zod.parse=(t,i)=>{const o=t.value,r=e.left._zod.run({value:o,issues:[]},i),A=e.right._zod.run({value:o,issues:[]},i);return r instanceof Promise||A instanceof Promise?Promise.all([r,A]).then(([l,c])=>dm(t,l,c)):dm(t,r,A)}});function Ic(n,e){if(n===e)return{valid:!0,data:n};if(n instanceof Date&&e instanceof Date&&+n==+e)return{valid:!0,data:n};if(Cs(n)&&Cs(e)){const t=Object.keys(e),i=Object.keys(n).filter(r=>t.indexOf(r)!==-1),o={...n,...e};for(const r of i){const A=Ic(n[r],e[r]);if(!A.valid)return{valid:!1,mergeErrorPath:[r,...A.mergeErrorPath]};o[r]=A.data}return{valid:!0,data:o}}if(Array.isArray(n)&&Array.isArray(e)){if(n.length!==e.length)return{valid:!1,mergeErrorPath:[]};const t=[];for(let i=0;iI.l&&I.r).map(([I])=>I);if(r.length&&o&&n.issues.push({...o,keys:r}),ls(n))return n;const A=Ic(e.value,t.value);if(!A.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(A.mergeErrorPath)}`);return n.value=A.data,n}const Dk=$("$ZodRecord",(n,e)=>{Mt.init(n,e),n._zod.parse=(t,i)=>{const o=t.value;if(!Cs(o))return t.issues.push({expected:"record",code:"invalid_type",input:o,inst:n}),t;const r=[],A=e.keyType._zod.values;if(A){t.value={};const I=new Set;for(const c of A)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){I.add(typeof c=="number"?c.toString():c);const h=e.keyType._zod.run({value:c,issues:[]},i);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){t.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(v=>Xi(v,i,Qi())),input:c,path:[c],inst:n});continue}const p=h.value,m=e.valueType._zod.run({value:o[c],issues:[]},i);m instanceof Promise?r.push(m.then(v=>{v.issues.length&&t.issues.push(...cs(c,v.issues)),t.value[p]=v.value})):(m.issues.length&&t.issues.push(...cs(c,m.issues)),t.value[p]=m.value)}let l;for(const c in o)I.has(c)||(l=l??[],l.push(c));l&&l.length>0&&t.issues.push({code:"unrecognized_keys",input:o,inst:n,keys:l})}else{t.value={};for(const I of Reflect.ownKeys(o)){if(I==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,I))continue;let l=e.keyType._zod.run({value:I,issues:[]},i);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof I=="string"&&im.test(I)&&l.issues.length){const p=e.keyType._zod.run({value:Number(I),issues:[]},i);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(l=p)}if(l.issues.length){e.mode==="loose"?t.value[I]=o[I]:t.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(p=>Xi(p,i,Qi())),input:I,path:[I],inst:n});continue}const h=e.valueType._zod.run({value:o[I],issues:[]},i);h instanceof Promise?r.push(h.then(p=>{p.issues.length&&t.issues.push(...cs(I,p.issues)),t.value[l.value]=p.value})):(h.issues.length&&t.issues.push(...cs(I,h.issues)),t.value[l.value]=h.value)}}return r.length?Promise.all(r).then(()=>t):t}}),kk=$("$ZodEnum",(n,e)=>{Mt.init(n,e);const t=Yp(e.entries),i=new Set(t);n._zod.values=i,n._zod.pattern=new RegExp(`^(${t.filter(o=>GN.has(typeof o)).map(o=>typeof o=="string"?Is(o):o.toString()).join("|")})$`),n._zod.parse=(o,r)=>{const A=o.value;return i.has(A)||o.issues.push({code:"invalid_value",values:t,input:A,inst:n}),o}}),Mk=$("$ZodLiteral",(n,e)=>{if(Mt.init(n,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");const t=new Set(e.values);n._zod.values=t,n._zod.pattern=new RegExp(`^(${e.values.map(i=>typeof i=="string"?Is(i):i?Is(i.toString()):String(i)).join("|")})$`),n._zod.parse=(i,o)=>{const r=i.value;return t.has(r)||i.issues.push({code:"invalid_value",values:e.values,input:r,inst:n}),i}}),Rk=$("$ZodTransform",(n,e)=>{Mt.init(n,e),n._zod.optin="optional",n._zod.parse=(t,i)=>{if(i.direction==="backward")throw new Up(n.constructor.name);const o=e.transform(t.value,t);if(i.async)return(o instanceof Promise?o:Promise.resolve(o)).then(A=>(t.value=A,t.fallback=!0,t));if(o instanceof Promise)throw new As;return t.value=o,t.fallback=!0,t}});function um(n,e){return e===void 0&&(n.issues.length||n.fallback)?{issues:[],value:void 0}:n}const hm=$("$ZodOptional",(n,e)=>{Mt.init(n,e),n._zod.optin="optional",n._zod.optout="optional",It(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),It(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${sc(t.source)})?$`):void 0}),n._zod.parse=(t,i)=>{if(e.innerType._zod.optin==="optional"){const o=t.value,r=e.innerType._zod.run(t,i);return r instanceof Promise?r.then(A=>um(A,o)):um(r,o)}return t.value===void 0?t:e.innerType._zod.run(t,i)}}),zk=$("$ZodExactOptional",(n,e)=>{hm.init(n,e),It(n._zod,"values",()=>e.innerType._zod.values),It(n._zod,"pattern",()=>e.innerType._zod.pattern),n._zod.parse=(t,i)=>e.innerType._zod.run(t,i)}),_k=$("$ZodNullable",(n,e)=>{Mt.init(n,e),It(n._zod,"optin",()=>e.innerType._zod.optin),It(n._zod,"optout",()=>e.innerType._zod.optout),It(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${sc(t.source)}|null)$`):void 0}),It(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),n._zod.parse=(t,i)=>t.value===null?t:e.innerType._zod.run(t,i)}),jk=$("$ZodDefault",(n,e)=>{Mt.init(n,e),n._zod.optin="optional",It(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,i)=>{if(i.direction==="backward")return e.innerType._zod.run(t,i);if(t.value===void 0)return t.value=e.defaultValue,t;const o=e.innerType._zod.run(t,i);return o instanceof Promise?o.then(r=>fm(r,e)):fm(o,e)}});function fm(n,e){return n.value===void 0&&(n.value=e.defaultValue),n}const Pk=$("$ZodPrefault",(n,e)=>{Mt.init(n,e),n._zod.optin="optional",It(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,i)=>(i.direction==="backward"||t.value===void 0&&(t.value=e.defaultValue),e.innerType._zod.run(t,i))}),Bk=$("$ZodNonOptional",(n,e)=>{Mt.init(n,e),It(n._zod,"values",()=>{const t=e.innerType._zod.values;return t?new Set([...t].filter(i=>i!==void 0)):void 0}),n._zod.parse=(t,i)=>{const o=e.innerType._zod.run(t,i);return o instanceof Promise?o.then(r=>pm(r,n)):pm(o,n)}});function pm(n,e){return!n.issues.length&&n.value===void 0&&n.issues.push({code:"invalid_type",expected:"nonoptional",input:n.value,inst:e}),n}const Zk=$("$ZodCatch",(n,e)=>{Mt.init(n,e),n._zod.optin="optional",It(n._zod,"optout",()=>e.innerType._zod.optout),It(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,i)=>{if(i.direction==="backward")return e.innerType._zod.run(t,i);const o=e.innerType._zod.run(t,i);return o instanceof Promise?o.then(r=>(t.value=r.value,r.issues.length&&(t.value=e.catchValue({...t,error:{issues:r.issues.map(A=>Xi(A,i,Qi()))},input:t.value}),t.issues=[],t.fallback=!0),t)):(t.value=o.value,o.issues.length&&(t.value=e.catchValue({...t,error:{issues:o.issues.map(r=>Xi(r,i,Qi()))},input:t.value}),t.issues=[],t.fallback=!0),t)}}),Lk=$("$ZodPipe",(n,e)=>{Mt.init(n,e),It(n._zod,"values",()=>e.in._zod.values),It(n._zod,"optin",()=>e.in._zod.optin),It(n._zod,"optout",()=>e.out._zod.optout),It(n._zod,"propValues",()=>e.in._zod.propValues),n._zod.parse=(t,i)=>{if(i.direction==="backward"){const r=e.out._zod.run(t,i);return r instanceof Promise?r.then(A=>XA(A,e.in,i)):XA(r,e.in,i)}const o=e.in._zod.run(t,i);return o instanceof Promise?o.then(r=>XA(r,e.out,i)):XA(o,e.out,i)}});function XA(n,e,t){return n.issues.length?(n.aborted=!0,n):e._zod.run({value:n.value,issues:n.issues,fallback:n.fallback},t)}const Gk=$("$ZodReadonly",(n,e)=>{Mt.init(n,e),It(n._zod,"propValues",()=>e.innerType._zod.propValues),It(n._zod,"values",()=>e.innerType._zod.values),It(n._zod,"optin",()=>e.innerType?._zod?.optin),It(n._zod,"optout",()=>e.innerType?._zod?.optout),n._zod.parse=(t,i)=>{if(i.direction==="backward")return e.innerType._zod.run(t,i);const o=e.innerType._zod.run(t,i);return o instanceof Promise?o.then(mm):mm(o)}});function mm(n){return n.value=Object.freeze(n.value),n}const Fk=$("$ZodCustom",(n,e)=>{_n.init(n,e),Mt.init(n,e),n._zod.parse=(t,i)=>t,n._zod.check=t=>{const i=t.value,o=e.fn(i);if(o instanceof Promise)return o.then(r=>vm(r,t,i,n));vm(o,t,i,n)}});function vm(n,e,t,i){if(!n){const o={code:"custom",input:t,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(o.params=i._zod.def.params),e.issues.push(Gr(o))}}var bm;class Vk{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const i=t[0];return this._map.set(e,i),i&&typeof i=="object"&&"id"in i&&this._idmap.set(i.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const i={...this.get(t)??{}};delete i.id;const o={...i,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Uk(){return new Vk}(bm=globalThis).__zod_globalRegistry??(bm.__zod_globalRegistry=Uk());const Fr=globalThis.__zod_globalRegistry;function Yk(n,e){return new n({type:"string",...we(e)})}function Hk(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...we(e)})}function ym(n,e){return new n({type:"string",format:"guid",check:"string_format",abort:!1,...we(e)})}function Kk(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,...we(e)})}function Wk(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...we(e)})}function Qk(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...we(e)})}function Xk(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...we(e)})}function $k(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...we(e)})}function qk(n,e){return new n({type:"string",format:"emoji",check:"string_format",abort:!1,...we(e)})}function Jk(n,e){return new n({type:"string",format:"nanoid",check:"string_format",abort:!1,...we(e)})}function eM(n,e){return new n({type:"string",format:"cuid",check:"string_format",abort:!1,...we(e)})}function tM(n,e){return new n({type:"string",format:"cuid2",check:"string_format",abort:!1,...we(e)})}function nM(n,e){return new n({type:"string",format:"ulid",check:"string_format",abort:!1,...we(e)})}function iM(n,e){return new n({type:"string",format:"xid",check:"string_format",abort:!1,...we(e)})}function gM(n,e){return new n({type:"string",format:"ksuid",check:"string_format",abort:!1,...we(e)})}function oM(n,e){return new n({type:"string",format:"ipv4",check:"string_format",abort:!1,...we(e)})}function sM(n,e){return new n({type:"string",format:"ipv6",check:"string_format",abort:!1,...we(e)})}function rM(n,e){return new n({type:"string",format:"cidrv4",check:"string_format",abort:!1,...we(e)})}function aM(n,e){return new n({type:"string",format:"cidrv6",check:"string_format",abort:!1,...we(e)})}function AM(n,e){return new n({type:"string",format:"base64",check:"string_format",abort:!1,...we(e)})}function CM(n,e){return new n({type:"string",format:"base64url",check:"string_format",abort:!1,...we(e)})}function IM(n,e){return new n({type:"string",format:"e164",check:"string_format",abort:!1,...we(e)})}function lM(n,e){return new n({type:"string",format:"jwt",check:"string_format",abort:!1,...we(e)})}function cM(n,e){return new n({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...we(e)})}function dM(n,e){return new n({type:"string",format:"date",check:"string_format",...we(e)})}function uM(n,e){return new n({type:"string",format:"time",check:"string_format",precision:null,...we(e)})}function hM(n,e){return new n({type:"string",format:"duration",check:"string_format",...we(e)})}function fM(n,e){return new n({type:"number",checks:[],...we(e)})}function pM(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...we(e)})}function mM(n,e){return new n({type:"boolean",...we(e)})}function vM(n){return new n({type:"unknown"})}function bM(n,e){return new n({type:"never",...we(e)})}function wm(n,e){return new om({check:"less_than",...we(e),value:n,inclusive:!1})}function lc(n,e){return new om({check:"less_than",...we(e),value:n,inclusive:!0})}function xm(n,e){return new sm({check:"greater_than",...we(e),value:n,inclusive:!1})}function cc(n,e){return new sm({check:"greater_than",...we(e),value:n,inclusive:!0})}function Sm(n,e){return new jD({check:"multiple_of",...we(e),value:n})}function Em(n,e){return new BD({check:"max_length",...we(e),maximum:n})}function $A(n,e){return new ZD({check:"min_length",...we(e),minimum:n})}function Tm(n,e){return new LD({check:"length_equals",...we(e),length:n})}function yM(n,e){return new GD({check:"string_format",format:"regex",...we(e),pattern:n})}function wM(n){return new FD({check:"string_format",format:"lowercase",...we(n)})}function xM(n){return new VD({check:"string_format",format:"uppercase",...we(n)})}function SM(n,e){return new UD({check:"string_format",format:"includes",...we(e),includes:n})}function EM(n,e){return new YD({check:"string_format",format:"starts_with",...we(e),prefix:n})}function TM(n,e){return new HD({check:"string_format",format:"ends_with",...we(e),suffix:n})}function ds(n){return new KD({check:"overwrite",tx:n})}function OM(n){return ds(e=>e.normalize(n))}function NM(){return ds(n=>n.trim())}function DM(){return ds(n=>n.toLowerCase())}function kM(){return ds(n=>n.toUpperCase())}function MM(){return ds(n=>ZN(n))}function RM(n,e,t){return new n({type:"array",element:e,...we(t)})}function zM(n,e,t){return new n({type:"custom",check:"custom",fn:e,...we(t)})}function _M(n,e){const t=jM(i=>(i.addIssue=o=>{if(typeof o=="string")i.issues.push(Gr(o,i.value,t._zod.def));else{const r=o;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=i.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),i.issues.push(Gr(r))}},n(i.value,i)),e);return t}function jM(n,e){const t=new _n({check:"custom",...we(e)});return t._zod.check=n,t}function Om(n){let e=n?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:n.processors??{},metadataRegistry:n?.metadata??Fr,target:e,unrepresentable:n?.unrepresentable??"throw",override:n?.override??(()=>{}),io:n?.io??"output",counter:0,seen:new Map,cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0}}function Xt(n,e,t={path:[],schemaPath:[]}){var i;const o=n._zod.def,r=e.seen.get(n);if(r)return r.count++,t.schemaPath.includes(n)&&(r.cycle=t.path),r.schema;const A={schema:{},count:1,cycle:void 0,path:t.path};e.seen.set(n,A);const I=n._zod.toJSONSchema?.();if(I)A.schema=I;else{const h={...t,schemaPath:[...t.schemaPath,n],path:t.path};if(n._zod.processJSONSchema)n._zod.processJSONSchema(e,A.schema,h);else{const m=A.schema,v=e.processors[o.type];if(!v)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);v(n,e,m,h)}const p=n._zod.parent;p&&(A.ref||(A.ref=p),Xt(p,e,h),e.seen.get(p).isParent=!0)}const l=e.metadataRegistry.get(n);return l&&Object.assign(A.schema,l),e.io==="input"&&Nn(n)&&(delete A.schema.examples,delete A.schema.default),e.io==="input"&&"_prefault"in A.schema&&((i=A.schema).default??(i.default=A.schema._prefault)),delete A.schema._prefault,e.seen.get(n).schema}function Nm(n,e){const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=new Map;for(const A of n.seen.entries()){const I=n.metadataRegistry.get(A[0])?.id;if(I){const l=i.get(I);if(l&&l!==A[0])throw new Error(`Duplicate schema id "${I}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(I,A[0])}}const o=A=>{const I=n.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const p=n.external.registry.get(A[0])?.id,m=n.external.uri??(x=>x);if(p)return{ref:m(p)};const v=A[1].defId??A[1].schema.id??`schema${n.counter++}`;return A[1].defId=v,{defId:v,ref:`${m("__shared")}#/${I}/${v}`}}if(A[1]===t)return{ref:"#"};const c=`#/${I}/`,h=A[1].schema.id??`__schema${n.counter++}`;return{defId:h,ref:c+h}},r=A=>{if(A[1].schema.$ref)return;const I=A[1],{ref:l,defId:c}=o(A);I.def={...I.schema},c&&(I.defId=c);const h=I.schema;for(const p in h)delete h[p];h.$ref=l};if(n.cycles==="throw")for(const A of n.seen.entries()){const I=A[1];if(I.cycle)throw new Error(`Cycle detected: #/${I.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const A of n.seen.entries()){const I=A[1];if(e===A[0]){r(A);continue}if(n.external){const c=n.external.registry.get(A[0])?.id;if(e!==A[0]&&c){r(A);continue}}if(n.metadataRegistry.get(A[0])?.id){r(A);continue}if(I.cycle){r(A);continue}if(I.count>1&&n.reused==="ref"){r(A);continue}}}function Dm(n,e){const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=I=>{const l=n.seen.get(I);if(l.ref===null)return;const c=l.def??l.schema,h={...c},p=l.ref;if(l.ref=null,p){i(p);const v=n.seen.get(p),x=v.schema;if(x.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(x)):Object.assign(c,x),Object.assign(c,h),I._zod.parent===p)for(const y in c)y==="$ref"||y==="allOf"||y in h||delete c[y];if(x.$ref&&v.def)for(const y in c)y==="$ref"||y==="allOf"||y in v.def&&JSON.stringify(c[y])===JSON.stringify(v.def[y])&&delete c[y]}const m=I._zod.parent;if(m&&m!==p){i(m);const v=n.seen.get(m);if(v?.schema.$ref&&(c.$ref=v.schema.$ref,v.def))for(const x in c)x==="$ref"||x==="allOf"||x in v.def&&JSON.stringify(c[x])===JSON.stringify(v.def[x])&&delete c[x]}n.override({zodSchema:I,jsonSchema:c,path:l.path??[]})};for(const I of[...n.seen.entries()].reverse())i(I[0]);const o={};if(n.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":n.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":n.target,n.external?.uri){const I=n.external.registry.get(e)?.id;if(!I)throw new Error("Schema is missing an `id` property");o.$id=n.external.uri(I)}Object.assign(o,t.def??t.schema);const r=n.metadataRegistry.get(e)?.id;r!==void 0&&o.id===r&&delete o.id;const A=n.external?.defs??{};for(const I of n.seen.entries()){const l=I[1];l.def&&l.defId&&(l.def.id===l.defId&&delete l.def.id,A[l.defId]=l.def)}n.external||Object.keys(A).length>0&&(n.target==="draft-2020-12"?o.$defs=A:o.definitions=A);try{const I=JSON.parse(JSON.stringify(o));return Object.defineProperty(I,"~standard",{value:{...e["~standard"],jsonSchema:{input:qA(e,"input",n.processors),output:qA(e,"output",n.processors)}},enumerable:!1,writable:!1}),I}catch{throw new Error("Error converting schema to JSON.")}}function Nn(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const i=n._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Nn(i.element,t);if(i.type==="set")return Nn(i.valueType,t);if(i.type==="lazy")return Nn(i.getter(),t);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Nn(i.innerType,t);if(i.type==="intersection")return Nn(i.left,t)||Nn(i.right,t);if(i.type==="record"||i.type==="map")return Nn(i.keyType,t)||Nn(i.valueType,t);if(i.type==="pipe")return n._zod.traits.has("$ZodCodec")?!0:Nn(i.in,t)||Nn(i.out,t);if(i.type==="object"){for(const o in i.shape)if(Nn(i.shape[o],t))return!0;return!1}if(i.type==="union"){for(const o of i.options)if(Nn(o,t))return!0;return!1}if(i.type==="tuple"){for(const o of i.items)if(Nn(o,t))return!0;return!!(i.rest&&Nn(i.rest,t))}return!1}const PM=(n,e={})=>t=>{const i=Om({...t,processors:e});return Xt(n,i),Nm(i,n),Dm(i,n)},qA=(n,e,t={})=>i=>{const{libraryOptions:o,target:r}=i??{},A=Om({...o??{},target:r,io:e,processors:t});return Xt(n,A),Nm(A,n),Dm(A,n)},BM={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ZM=(n,e,t,i)=>{const o=t;o.type="string";const{minimum:r,maximum:A,format:I,patterns:l,contentEncoding:c}=n._zod.bag;if(typeof r=="number"&&(o.minLength=r),typeof A=="number"&&(o.maxLength=A),I&&(o.format=BM[I]??I,o.format===""&&delete o.format,I==="time"&&delete o.format),c&&(o.contentEncoding=c),l&&l.size>0){const h=[...l];h.length===1?o.pattern=h[0].source:h.length>1&&(o.allOf=[...h.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},LM=(n,e,t,i)=>{const o=t,{minimum:r,maximum:A,format:I,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:h}=n._zod.bag;typeof I=="string"&&I.includes("int")?o.type="integer":o.type="number";const p=typeof h=="number"&&h>=(r??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(A??Number.POSITIVE_INFINITY),v=e.target==="draft-04"||e.target==="openapi-3.0";p?v?(o.minimum=h,o.exclusiveMinimum=!0):o.exclusiveMinimum=h:typeof r=="number"&&(o.minimum=r),m?v?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c:typeof A=="number"&&(o.maximum=A),typeof l=="number"&&(o.multipleOf=l)},GM=(n,e,t,i)=>{t.type="boolean"},FM=(n,e,t,i)=>{t.not={}},VM=(n,e,t,i)=>{},UM=(n,e,t,i)=>{const o=n._zod.def,r=Yp(o.entries);r.every(A=>typeof A=="number")&&(t.type="number"),r.every(A=>typeof A=="string")&&(t.type="string"),t.enum=r},YM=(n,e,t,i)=>{const o=n._zod.def,r=[];for(const A of o.values)if(A===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof A=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(A))}else r.push(A);if(r.length!==0)if(r.length===1){const A=r[0];t.type=A===null?"null":typeof A,e.target==="draft-04"||e.target==="openapi-3.0"?t.enum=[A]:t.const=A}else r.every(A=>typeof A=="number")&&(t.type="number"),r.every(A=>typeof A=="string")&&(t.type="string"),r.every(A=>typeof A=="boolean")&&(t.type="boolean"),r.every(A=>A===null)&&(t.type="null"),t.enum=r},HM=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},KM=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},WM=(n,e,t,i)=>{const o=t,r=n._zod.def,{minimum:A,maximum:I}=n._zod.bag;typeof A=="number"&&(o.minItems=A),typeof I=="number"&&(o.maxItems=I),o.type="array",o.items=Xt(r.element,e,{...i,path:[...i.path,"items"]})},QM=(n,e,t,i)=>{const o=t,r=n._zod.def;o.type="object",o.properties={};const A=r.shape;for(const c in A)o.properties[c]=Xt(A[c],e,{...i,path:[...i.path,"properties",c]});const I=new Set(Object.keys(A)),l=new Set([...I].filter(c=>{const h=r.shape[c]._zod;return e.io==="input"?h.optin===void 0:h.optout===void 0}));l.size>0&&(o.required=Array.from(l)),r.catchall?._zod.def.type==="never"?o.additionalProperties=!1:r.catchall?r.catchall&&(o.additionalProperties=Xt(r.catchall,e,{...i,path:[...i.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},XM=(n,e,t,i)=>{const o=n._zod.def,r=o.inclusive===!1,A=o.options.map((I,l)=>Xt(I,e,{...i,path:[...i.path,r?"oneOf":"anyOf",l]}));r?t.oneOf=A:t.anyOf=A},$M=(n,e,t,i)=>{const o=n._zod.def,r=Xt(o.left,e,{...i,path:[...i.path,"allOf",0]}),A=Xt(o.right,e,{...i,path:[...i.path,"allOf",1]}),I=c=>"allOf"in c&&Object.keys(c).length===1,l=[...I(r)?r.allOf:[r],...I(A)?A.allOf:[A]];t.allOf=l},qM=(n,e,t,i)=>{const o=t,r=n._zod.def;o.type="object";const A=r.keyType,l=A._zod.bag?.patterns;if(r.mode==="loose"&&l&&l.size>0){const h=Xt(r.valueType,e,{...i,path:[...i.path,"patternProperties","*"]});o.patternProperties={};for(const p of l)o.patternProperties[p.source]=h}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Xt(r.keyType,e,{...i,path:[...i.path,"propertyNames"]})),o.additionalProperties=Xt(r.valueType,e,{...i,path:[...i.path,"additionalProperties"]});const c=A._zod.values;if(c){const h=[...c].filter(p=>typeof p=="string"||typeof p=="number");h.length>0&&(o.required=h)}},JM=(n,e,t,i)=>{const o=n._zod.def,r=Xt(o.innerType,e,i),A=e.seen.get(n);e.target==="openapi-3.0"?(A.ref=o.innerType,t.nullable=!0):t.anyOf=[r,{type:"null"}]},eR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType},tR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType,t.default=JSON.parse(JSON.stringify(o.defaultValue))},nR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},iR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType;let A;try{A=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=A},gR=(n,e,t,i)=>{const o=n._zod.def,r=o.in._zod.traits.has("$ZodTransform"),A=e.io==="input"?r?o.out:o.in:o.out;Xt(A,e,i);const I=e.seen.get(n);I.ref=A},oR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType,t.readOnly=!0},km=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType},sR=$("ZodISODateTime",(n,e)=>{rk.init(n,e),zt.init(n,e)});function rR(n){return cM(sR,n)}const aR=$("ZodISODate",(n,e)=>{ak.init(n,e),zt.init(n,e)});function AR(n){return dM(aR,n)}const CR=$("ZodISOTime",(n,e)=>{Ak.init(n,e),zt.init(n,e)});function IR(n){return uM(CR,n)}const lR=$("ZodISODuration",(n,e)=>{Ck.init(n,e),zt.init(n,e)});function cR(n){return hM(lR,n)}const gi=$("ZodError",(n,e)=>{$p.init(n,e),n.name="ZodError",Object.defineProperties(n,{format:{value:t=>JN(n,t)},flatten:{value:t=>qN(n,t)},addIssue:{value:t=>{n.issues.push(t),n.message=JSON.stringify(n.issues,gc,2)}},addIssues:{value:t=>{n.issues.push(...t),n.message=JSON.stringify(n.issues,gc,2)}},isEmpty:{get(){return n.issues.length===0}}})},{Parent:Error}),dR=ac(gi),uR=Ac(gi),hR=HA(gi),fR=KA(gi),pR=nD(gi),mR=iD(gi),vR=gD(gi),bR=oD(gi),yR=sD(gi),wR=rD(gi),xR=aD(gi),SR=AD(gi),Mm=new WeakMap;function Vr(n,e,t){const i=Object.getPrototypeOf(n);let o=Mm.get(i);if(o||(o=new Set,Mm.set(i,o)),!o.has(e)){o.add(e);for(const r in t){const A=t[r];Object.defineProperty(i,r,{configurable:!0,enumerable:!1,get(){const I=A.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:I}),I},set(I){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:I})}})}}}const Rt=$("ZodType",(n,e)=>(Mt.init(n,e),Object.assign(n["~standard"],{jsonSchema:{input:qA(n,"input"),output:qA(n,"output")}}),n.toJSONSchema=PM(n,{}),n.def=e,n.type=e.type,Object.defineProperty(n,"_def",{value:e}),n.parse=(t,i)=>dR(n,t,i,{callee:n.parse}),n.safeParse=(t,i)=>hR(n,t,i),n.parseAsync=async(t,i)=>uR(n,t,i,{callee:n.parseAsync}),n.safeParseAsync=async(t,i)=>fR(n,t,i),n.spa=n.safeParseAsync,n.encode=(t,i)=>pR(n,t,i),n.decode=(t,i)=>mR(n,t,i),n.encodeAsync=async(t,i)=>vR(n,t,i),n.decodeAsync=async(t,i)=>bR(n,t,i),n.safeEncode=(t,i)=>yR(n,t,i),n.safeDecode=(t,i)=>wR(n,t,i),n.safeEncodeAsync=async(t,i)=>xR(n,t,i),n.safeDecodeAsync=async(t,i)=>SR(n,t,i),Vr(n,"ZodType",{check(...t){const i=this.def;return this.clone(Tg(i,{checks:[...i.checks??[],...t.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,i){return Og(this,t,i)},brand(){return this},register(t,i){return t.add(this,i),this},refine(t,i){return this.check(uz(t,i))},superRefine(t,i){return this.check(hz(t,i))},overwrite(t){return this.check(ds(t))},optional(){return Vm(this)},exactOptional(){return nz(this)},nullable(){return Um(this)},nullish(){return Vm(Um(this))},nonoptional(t){return az(this,t)},array(){return Se(this)},or(t){return Lm([this,t])},and(t){return $R(this,t)},transform(t){return Hm(this,ez(t))},default(t){return oz(this,t)},prefault(t){return rz(this,t)},catch(t){return Cz(this,t)},pipe(t){return Hm(this,t)},readonly(){return cz(this)},describe(t){const i=this.clone();return Fr.add(i,{description:t}),i},meta(...t){if(t.length===0)return Fr.get(this);const i=this.clone();return Fr.add(i,t[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t){return t(this)}}),Object.defineProperty(n,"description",{get(){return Fr.get(n)?.description},configurable:!0}),n)),Rm=$("_ZodString",(n,e)=>{Cc.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(i,o,r)=>ZM(n,i,o);const t=n._zod.bag;n.format=t.format??null,n.minLength=t.minimum??null,n.maxLength=t.maximum??null,Vr(n,"_ZodString",{regex(...i){return this.check(yM(...i))},includes(...i){return this.check(SM(...i))},startsWith(...i){return this.check(EM(...i))},endsWith(...i){return this.check(TM(...i))},min(...i){return this.check($A(...i))},max(...i){return this.check(Em(...i))},length(...i){return this.check(Tm(...i))},nonempty(...i){return this.check($A(1,...i))},lowercase(i){return this.check(wM(i))},uppercase(i){return this.check(xM(i))},trim(){return this.check(NM())},normalize(...i){return this.check(OM(...i))},toLowerCase(){return this.check(DM())},toUpperCase(){return this.check(kM())},slugify(){return this.check(MM())}})}),ER=$("ZodString",(n,e)=>{Cc.init(n,e),Rm.init(n,e),n.email=t=>n.check(Hk(TR,t)),n.url=t=>n.check($k(OR,t)),n.jwt=t=>n.check(lM(VR,t)),n.emoji=t=>n.check(qk(NR,t)),n.guid=t=>n.check(ym(zm,t)),n.uuid=t=>n.check(Kk(JA,t)),n.uuidv4=t=>n.check(Wk(JA,t)),n.uuidv6=t=>n.check(Qk(JA,t)),n.uuidv7=t=>n.check(Xk(JA,t)),n.nanoid=t=>n.check(Jk(DR,t)),n.guid=t=>n.check(ym(zm,t)),n.cuid=t=>n.check(eM(kR,t)),n.cuid2=t=>n.check(tM(MR,t)),n.ulid=t=>n.check(nM(RR,t)),n.base64=t=>n.check(AM(LR,t)),n.base64url=t=>n.check(CM(GR,t)),n.xid=t=>n.check(iM(zR,t)),n.ksuid=t=>n.check(gM(_R,t)),n.ipv4=t=>n.check(oM(jR,t)),n.ipv6=t=>n.check(sM(PR,t)),n.cidrv4=t=>n.check(rM(BR,t)),n.cidrv6=t=>n.check(aM(ZR,t)),n.e164=t=>n.check(IM(FR,t)),n.datetime=t=>n.check(rR(t)),n.date=t=>n.check(AR(t)),n.time=t=>n.check(IR(t)),n.duration=t=>n.check(cR(t))});function D(n){return Yk(ER,n)}const zt=$("ZodStringFormat",(n,e)=>{Ot.init(n,e),Rm.init(n,e)}),TR=$("ZodEmail",(n,e)=>{qD.init(n,e),zt.init(n,e)}),zm=$("ZodGUID",(n,e)=>{XD.init(n,e),zt.init(n,e)}),JA=$("ZodUUID",(n,e)=>{$D.init(n,e),zt.init(n,e)}),OR=$("ZodURL",(n,e)=>{JD.init(n,e),zt.init(n,e)}),NR=$("ZodEmoji",(n,e)=>{ek.init(n,e),zt.init(n,e)}),DR=$("ZodNanoID",(n,e)=>{tk.init(n,e),zt.init(n,e)}),kR=$("ZodCUID",(n,e)=>{nk.init(n,e),zt.init(n,e)}),MR=$("ZodCUID2",(n,e)=>{ik.init(n,e),zt.init(n,e)}),RR=$("ZodULID",(n,e)=>{gk.init(n,e),zt.init(n,e)}),zR=$("ZodXID",(n,e)=>{ok.init(n,e),zt.init(n,e)}),_R=$("ZodKSUID",(n,e)=>{sk.init(n,e),zt.init(n,e)}),jR=$("ZodIPv4",(n,e)=>{Ik.init(n,e),zt.init(n,e)}),PR=$("ZodIPv6",(n,e)=>{lk.init(n,e),zt.init(n,e)}),BR=$("ZodCIDRv4",(n,e)=>{ck.init(n,e),zt.init(n,e)}),ZR=$("ZodCIDRv6",(n,e)=>{dk.init(n,e),zt.init(n,e)}),LR=$("ZodBase64",(n,e)=>{uk.init(n,e),zt.init(n,e)}),GR=$("ZodBase64URL",(n,e)=>{fk.init(n,e),zt.init(n,e)}),FR=$("ZodE164",(n,e)=>{pk.init(n,e),zt.init(n,e)}),VR=$("ZodJWT",(n,e)=>{vk.init(n,e),zt.init(n,e)}),_m=$("ZodNumber",(n,e)=>{am.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(i,o,r)=>LM(n,i,o),Vr(n,"ZodNumber",{gt(i,o){return this.check(xm(i,o))},gte(i,o){return this.check(cc(i,o))},min(i,o){return this.check(cc(i,o))},lt(i,o){return this.check(wm(i,o))},lte(i,o){return this.check(lc(i,o))},max(i,o){return this.check(lc(i,o))},int(i){return this.check(jm(i))},safe(i){return this.check(jm(i))},positive(i){return this.check(xm(0,i))},nonnegative(i){return this.check(cc(0,i))},negative(i){return this.check(wm(0,i))},nonpositive(i){return this.check(lc(0,i))},multipleOf(i,o){return this.check(Sm(i,o))},step(i,o){return this.check(Sm(i,o))},finite(){return this}});const t=n._zod.bag;n.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),n.isFinite=!0,n.format=t.format??null});function j(n){return fM(_m,n)}const UR=$("ZodNumberFormat",(n,e)=>{bk.init(n,e),_m.init(n,e)});function jm(n){return pM(UR,n)}const YR=$("ZodBoolean",(n,e)=>{yk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>GM(n,t,i)});function In(n){return mM(YR,n)}const HR=$("ZodUnknown",(n,e)=>{wk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>VM()});function $i(){return vM(HR)}const KR=$("ZodNever",(n,e)=>{xk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>FM(n,t,i)});function Pm(n){return bM(KR,n)}const WR=$("ZodArray",(n,e)=>{Sk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>WM(n,t,i,o),n.element=e.element,Vr(n,"ZodArray",{min(t,i){return this.check($A(t,i))},nonempty(t){return this.check($A(1,t))},max(t,i){return this.check(Em(t,i))},length(t,i){return this.check(Tm(t,i))},unwrap(){return this.element}})});function Se(n,e){return RM(WR,n,e)}const Bm=$("ZodObject",(n,e)=>{Tk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>QM(n,t,i,o),It(n,"shape",()=>e.shape),Vr(n,"ZodObject",{keyof(){return _e(Object.keys(this._zod.def.shape))},catchall(t){return this.clone({...this._zod.def,catchall:t})},passthrough(){return this.clone({...this._zod.def,catchall:$i()})},loose(){return this.clone({...this._zod.def,catchall:$i()})},strict(){return this.clone({...this._zod.def,catchall:Pm()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(t){return HN(this,t)},safeExtend(t){return KN(this,t)},merge(t){return WN(this,t)},pick(t){return UN(this,t)},omit(t){return YN(this,t)},partial(...t){return QN(Fm,this,t[0])},required(...t){return XN(Ym,this,t[0])}})});function He(n,e){const t={type:"object",shape:n??{},...we(e)};return new Bm(t)}function Ie(n,e){return new Bm({type:"object",shape:n,catchall:Pm(),...we(e)})}const Zm=$("ZodUnion",(n,e)=>{cm.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>XM(n,t,i,o),n.options=e.options});function Lm(n,e){return new Zm({type:"union",options:n,...we(e)})}const QR=$("ZodDiscriminatedUnion",(n,e)=>{Zm.init(n,e),Ok.init(n,e)});function Ur(n,e,t){return new QR({type:"union",options:e,discriminator:n,...we(t)})}const XR=$("ZodIntersection",(n,e)=>{Nk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>$M(n,t,i,o)});function $R(n,e){return new XR({type:"intersection",left:n,right:e})}const Gm=$("ZodRecord",(n,e)=>{Dk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>qM(n,t,i,o),n.keyType=e.keyType,n.valueType=e.valueType});function eC(n,e,t){return!e||!e._zod?new Gm({type:"record",keyType:D(),valueType:n,...we(e)}):new Gm({type:"record",keyType:n,valueType:e,...we(t)})}const dc=$("ZodEnum",(n,e)=>{kk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(i,o,r)=>UM(n,i,o),n.enum=e.entries,n.options=Object.values(e.entries);const t=new Set(Object.keys(e.entries));n.extract=(i,o)=>{const r={};for(const A of i)if(t.has(A))r[A]=e.entries[A];else throw new Error(`Key ${A} not found in enum`);return new dc({...e,checks:[],...we(o),entries:r})},n.exclude=(i,o)=>{const r={...e.entries};for(const A of i)if(t.has(A))delete r[A];else throw new Error(`Key ${A} not found in enum`);return new dc({...e,checks:[],...we(o),entries:r})}});function _e(n,e){const t=Array.isArray(n)?Object.fromEntries(n.map(i=>[i,i])):n;return new dc({type:"enum",entries:t,...we(e)})}const qR=$("ZodLiteral",(n,e)=>{Mk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>YM(n,t,i),n.values=new Set(e.values),Object.defineProperty(n,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function qe(n,e){return new qR({type:"literal",values:Array.isArray(n)?n:[n],...we(e)})}const JR=$("ZodTransform",(n,e)=>{Rk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>KM(n,t),n._zod.parse=(t,i)=>{if(i.direction==="backward")throw new Up(n.constructor.name);t.addIssue=r=>{if(typeof r=="string")t.issues.push(Gr(r,t.value,e));else{const A=r;A.fatal&&(A.continue=!1),A.code??(A.code="custom"),A.input??(A.input=t.value),A.inst??(A.inst=n),t.issues.push(Gr(A))}};const o=e.transform(t.value,t);return o instanceof Promise?o.then(r=>(t.value=r,t.fallback=!0,t)):(t.value=o,t.fallback=!0,t)}});function ez(n){return new JR({type:"transform",transform:n})}const Fm=$("ZodOptional",(n,e)=>{hm.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>km(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function Vm(n){return new Fm({type:"optional",innerType:n})}const tz=$("ZodExactOptional",(n,e)=>{zk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>km(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function nz(n){return new tz({type:"optional",innerType:n})}const iz=$("ZodNullable",(n,e)=>{_k.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>JM(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function Um(n){return new iz({type:"nullable",innerType:n})}const gz=$("ZodDefault",(n,e)=>{jk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>tR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});function oz(n,e){return new gz({type:"default",innerType:n,get defaultValue(){return typeof e=="function"?e():Qp(e)}})}const sz=$("ZodPrefault",(n,e)=>{Pk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>nR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function rz(n,e){return new sz({type:"prefault",innerType:n,get defaultValue(){return typeof e=="function"?e():Qp(e)}})}const Ym=$("ZodNonOptional",(n,e)=>{Bk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>eR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function az(n,e){return new Ym({type:"nonoptional",innerType:n,...we(e)})}const Az=$("ZodCatch",(n,e)=>{Zk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>iR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});function Cz(n,e){return new Az({type:"catch",innerType:n,catchValue:typeof e=="function"?e:()=>e})}const Iz=$("ZodPipe",(n,e)=>{Lk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>gR(n,t,i,o),n.in=e.in,n.out=e.out});function Hm(n,e){return new Iz({type:"pipe",in:n,out:e})}const lz=$("ZodReadonly",(n,e)=>{Gk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>oR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function cz(n){return new lz({type:"readonly",innerType:n})}const dz=$("ZodCustom",(n,e)=>{Fk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>HM(n,t)});function uz(n,e={}){return zM(dz,n,e)}function hz(n,e){return _M(n,e)}const fz="compass.query/1",pz=["file","module","package","namespace","class","struct","interface","trait","protocol","enum","enum_member","type_alias","function","method","constructor","property","field","variable","constant","parameter","import","export","macro","annotation","route","component","event","message","topic","queue","job","resource","schema","query","migration","config_key","database","database_schema","database_table","database_view","database_column","database_index","database_constraint","database_procedure","database_trigger"],mz=["contains","calls","imports","exports","extends","implements","references","type_of","returns","instantiates","overrides","decorates","routes_to","reads","writes","aliases","registers","handles","publishes","subscribes","produces","consumes","schedules","triggers","tests","depends_on","documents","maps_to","renders"],vz=["controller","route_handler","middleware","service","resolver","consumer","producer","subscriber","repository","model","test","fixture","generated","ui_component","hook","client_boundary","client_component","server_component","server_function","data_loader"],bz=["search","callers","callees","impact","explore","node_trail"],yz=["middleware","dependency","security","layout","template","loading","default","error_boundary","not_found","boundary","loader","action","handler","data_loader","route_component"],uc=D().min(1).refine(n=>n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/.test(n)?!1:n.split("/").every(e=>e!==""&&e!=="."&&e!==".."),"source path must be a safe repository-relative path"),us=Ie({file:uc,startByte:j().int().nonnegative(),endByte:j().int().nonnegative(),startLine:j().int().positive(),startColumn:j().int().nonnegative(),endLine:j().int().positive(),endColumn:j().int().nonnegative()}).refine(n=>n.endByte>=n.startByte&&(n.endLine>n.startLine||n.endLine===n.startLine&&n.endColumn>=n.startColumn),"source anchor must be ordered"),wz=_e(pz),xz=_e(mz),Sz=_e(vz),Ez=_e(bz),Tz=_e(["structural_graph","program_ir"]),Oz=_e(["ast","config","convention","artifact","heuristic"]),hc=_e(["exact","inferred","ambiguous"]),tC=_e(["exact","ambiguous","unresolved"]),Km=Ie({nodeId:D().min(1),reason:D().min(1),confidence:hc,score:j().finite().nullable().optional(),anchor:us.nullable().optional()}),nC=Ie({layer:Tz,origin:Oz,extractor:D().min(1),confidence:hc,anchor:us.nullable(),rule:D().min(1).nullable(),wiringSite:us.nullable(),resolution:tC,candidates:Se(Km).max(20).default([])}),Nz=Ie({type:qe("file"),data:Ie({contentDigest:D().min(1),byteSize:j().int().nonnegative(),generated:In()})}),Dz=Ie({type:qe("symbol"),data:Ie({signature:D().nullable().optional(),modifiers:Se(D()).default([]),overloadDiscriminator:D().nullable().optional(),declaringType:D().nullable().optional(),signatureDigest:D().nullable().optional(),implementationDigest:D().nullable().optional(),sourceDigest:D().nullable().optional()})}),kz=Ie({type:qe("import_export"),data:Ie({specifier:D(),importedName:D().nullable().optional(),localName:D().nullable().optional(),typeOnly:In()})}),Wm=_e(yz),Mz=Ie({stage:Wm,position:j().int().nonnegative(),reference:D().min(1),resolution:tC,sourceAnchor:us.nullable(),target:D().nullable().optional(),candidates:Se(Km).max(20).default([])}),Rz=Ie({type:qe("route"),data:Ie({operation:D(),path:D(),originalPath:D().nullable().optional(),declaringScope:D(),resolution:tC,middlewareCount:j().int().nonnegative(),stages:Se(Mz).max(256).default([])})}),zz=Ie({type:qe("component"),data:Ie({componentType:D()})}),_z=Ie({type:qe("resource"),data:Ie({resourceKind:_e(["document","paper","image","concept","rationale"]),uri:D().nullable().optional(),mediaType:D().nullable().optional()})}),jz=Ie({type:qe("messaging"),data:Ie({transport:D(),subject:D(),declaringScope:D()})}),Pz=Ie({type:qe("job"),data:Ie({schedule:D().nullable().optional(),queue:D().nullable().optional()})}),Bz=Ie({type:qe("schema"),data:Ie({dialect:D().nullable().optional(),logicalDatabase:D().nullable().optional(),namespace:D().nullable().optional()})}),Zz=Ie({type:qe("query"),data:Ie({dialect:D().nullable().optional(),operation:D().nullable().optional(),textDigest:D().nullable().optional()})}),Lz=Ie({type:qe("config"),data:Ie({format:D(),keyPath:D()})}),Gz=Ie({type:qe("database"),data:Ie({logicalDatabase:D(),databaseSchema:D().nullable().optional()})}),Fz=Ur("type",[Nz,Dz,kz,Rz,zz,_z,jz,Pz,Bz,Zz,Lz,Gz]),Vz=Ie({type:qe("call"),data:Ie({dispatch:_e(["static","virtual","dynamic"]),receiverType:D().nullable().optional(),argumentCount:j().int().nonnegative().nullable().optional()})}),Uz=Ie({type:qe("route"),data:Ie({stage:Wm,position:j().int().nonnegative().nullable().optional(),operation:D().nullable().optional()})}),Yz=Ie({type:qe("messaging"),data:Ie({transport:D(),subject:D()})}),Hz=Ie({type:qe("schedule"),data:Ie({expression:D().nullable().optional()})}),Kz=Ie({type:qe("mapping"),data:Ie({mappingKind:D()})}),Wz=Ie({type:qe("render"),data:Ie({renderKind:_e(["jsx","create_element","root","lazy","dynamic"]),boundary:D().nullable().optional()})}),Qm=Ur("type",[Vz,Uz,Yz,Hz,Kz,Wz]),Qz=Ie({maxDepth:j().int().positive(),maxNodes:j().int().positive(),maxEdges:j().int().positive(),maxPaths:j().int().positive(),maxCandidates:j().int().positive(),maxSourceBytes:j().int().positive(),maxResponseBytes:j().int().positive()}),Xz=Ie({nodeId:D().min(1),score:j().finite(),matchedFields:Se(D())}),$z=Ie({id:D().min(1),kind:wz,roles:Se(Sz),name:D().min(1),qualifiedName:D().min(1),language:D().nullable(),framework:D().nullable(),source:us.nullable(),details:Fz.nullable(),evidence:Se(nC)}),qz=Ie({id:D().min(1),source:D().min(1),target:D().min(1),kind:xz,relationshipSite:us.nullable(),details:Qm.nullable(),evidence:Se(nC)}),Jz=Ie({path:uc,contentDigest:D().min(1),source:D().nullable(),truncated:In()}),e3=Ie({id:D().min(1),nodeIds:Se(D().min(1)),edgeIds:Se(D().min(1)),weakestResolution:tC,weakestConfidence:hc}),t3=Ie({code:_e(["no_match","ambiguous_match","direction_mismatch","unresolved_handler","incomplete_coverage","stale_source_digest","bounded_truncation","program_orphan","program_conflict","program_unavailable"]),message:D().min(1),nodeId:D().nullable(),path:uc.nullable()}),n3=Ie({schema:qe(fz),operation:Ez,results:Se(Xz),nodes:Se($z),edges:Se(qz),files:Se(Jz),paths:Se(e3),diagnostics:Se(t3),limits:Qz,truncated:In()}),i3="compass.viewer.graph/1",fc=He({file:D(),startLine:j().int().positive().optional(),endLine:j().int().positive().optional(),startByte:j().int().nonnegative().optional(),endByte:j().int().nonnegative().optional()}).passthrough(),g3=He({field:D().min(1),before:$i().optional(),after:$i().optional()}),Xm=He({before:eC(D(),$i()).optional(),after:eC(D(),$i()).optional(),fields:Se(g3)}),$m=He({challenge:D().startsWith("challenge:"),targetId:D().min(1),effect:_e(["flag","mask"]),masked:In(),certificateDigest:D().regex(/^[0-9a-f]{64}$/),summary:D()}).strict(),o3=He({total:j().int().nonnegative(),examples:Se(He({kind:_e(["assertion","challenge"]),id:D().min(1),reasonCode:D().min(1),explanation:D(),sequence:j().int().nonnegative()}).strict()),omittedExamples:j().int().nonnegative()}).strict(),qm=eC(D(),$i()),s3=Ur("kind",[He({kind:qe("native")}).passthrough(),He({kind:qe("ocr"),profile:qm,confidence_bps:j().int().min(0).max(1e4)}).passthrough()]),Jm=He({kind:D().min(1)}).passthrough(),r3=He({candidate_id:D().min(1),x:j().int().nonnegative(),y:j().int().nonnegative(),width:j().int().positive(),height:j().int().positive()}).passthrough(),a3=He({schema:qe("compass.document.preview/1"),kind:_e(["page","slide","sheet"]),locator:Jm,label:D().min(1),width:j().int().positive(),height:j().int().positive(),svg:D().min(1).max(512*1024),regions:Se(r3).max(256).default([]),digest:D().regex(/^sha256:[0-9a-f]{64}$/)}).passthrough(),A3=He({role:_e(["root","block"]).optional(),kind:D().optional(),format:D().optional(),text:D().optional(),ordinal:j().int().nonnegative().optional(),complete:In().optional(),visualCoverage:_e(["not_requested","complete","partial","failed"]).optional(),ocrMode:_e(["off","auto","always"]).optional(),origin:s3.optional(),locator:Jm.optional(),ocrProfile:qm.optional(),previews:Se(a3).max(256).optional()}).passthrough(),C3=He({id:D().min(1),label:D(),kind:D().optional(),community:j().int(),communityName:D().optional(),degree:j().int().nonnegative().optional(),language:D().optional(),signature:D().optional(),size:j().positive().optional(),memberCount:j().int().nonnegative().optional(),detailAvailable:In().optional(),learningStatus:D().optional(),learningStale:In().optional(),depth:j().int().nonnegative().optional(),root:In().optional(),agentAssertion:D().startsWith("assertion:").optional(),agentSummary:D().optional(),groundingStatus:qe("GROUNDED").optional(),challenged:In().optional(),challenge:$m.optional(),change:_e(["added","removed","changed","unchanged"]).optional(),evidence:Xm.optional(),codeEvidence:Se(nC).optional(),source:fc.optional(),color:He({background:D(),border:D()}).passthrough().optional(),document:A3.optional()}).passthrough(),I3=He({id:D().min(1),source:D().min(1),target:D().min(1),relation:D(),weight:j().int().positive().optional(),change:_e(["added","removed","changed","unchanged"]).optional(),evidence:Xm.optional(),codeEvidence:Se(nC).optional(),details:Qm.nullable().optional(),relationshipSite:fc.optional(),confidence:_e(["extracted","inferred","ambiguous","aggregated"]).optional(),agentAssertion:D().startsWith("assertion:").optional(),agentSummary:D().optional(),groundingStatus:qe("GROUNDED").optional(),challenged:In().optional(),challenge:$m.optional()}).passthrough(),l3=He({id:j().int(),label:D(),color:D(),hidden:In().default(!1)}).passthrough(),Ng=He({schema:qe(i3),title:D(),stats:He({nodes:j().int().nonnegative(),edges:j().int().nonnegative(),communities:j().int().nonnegative(),aggregated:In()}).passthrough(),nodes:Se(C3),edges:Se(I3),communities:Se(l3),hyperedges:Se($i()).default([]),effectiveGraph:He({effectiveIdentity:D().regex(/^[0-9a-f]{64}$/),baseGeneration:He({generationId:D().min(1),graphDigest:D().regex(/^[0-9a-f]{64}$/)}).strict(),overlayRevision:D().regex(/^[0-9a-f]{64}$/),compositionProfile:_e(["augment","curated"]),retractions:o3,omissions:He({total:j().int().nonnegative(),direct:j().int().nonnegative(),cascaded:j().int().nonnegative(),examples:Se($i()),omittedExamples:j().int().nonnegative()}).strict()}).strict().optional()}).passthrough(),c3=_e(["resolved","inferred","ambiguous","unresolved"]),ev=He({source_file:D(),start_byte:j().int().nonnegative(),end_byte:j().int().nonnegative()}),d3=He({id:D(),symbol:D().nullable(),name:D(),file:D().nullable(),anchor:ev.nullable().optional(),startLine:j().int().positive().nullable().optional(),endLine:j().int().positive().nullable().optional(),startByte:j().int().nonnegative().nullable().optional(),endByte:j().int().nonnegative().nullable().optional(),graphNodeId:D().nullable(),unresolved:In(),evidenceLayer:_e(["structural_graph","program_ir","combined"]).optional()}),u3=Lm([He({anchor:ev,evidence:Se(D())}),He({sourceFile:D().nullable(),line:j().int().positive().nullable(),startByte:j().int().nonnegative().nullable(),endByte:j().int().nonnegative().nullable(),evidence:Se(D())})]),h3=He({id:D(),source:D(),target:D(),callee:D(),resolution:c3,confidence:D().nullable().optional(),callSites:Se(u3),evidenceLayer:_e(["structural_graph","program_ir","combined"]).optional()}),f3=He({schema:_e(["compass.program.call_graph/1","compass.call_graph/1"]),rootSymbol:D(),direction:_e(["callers","callees","both"]),depth:j().int().positive(),nodes:Se(d3),edges:Se(h3),truncated:In(),continuations:Se(He({symbol:D(),direction:_e(["callers","callees","both"]),nextDepth:j().int().positive()})),coverage:He({resolved:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative(),unresolved:j().int().nonnegative(),evidenceLayer:_e(["structural_graph","program_ir","combined"]).optional(),partial:In().optional(),limitations:Se(D()).optional(),warning:D()})}),p3="compass.viewer.architecture/1",m3=_e(["production","all_code"]),tv=_e(["execution","dependency","type","structure","contextual","unknown"]),nv=_e(["architecture","execution","dependency","type","structure","all"]),v3=_e(["owner","subsystem"]),b3=_e(["overview","detail"]),y3=_e(["overlay","persisted","owner","path","declaration","hub","provider","fallback"]),w3=_e(["good","degraded","insufficient"]),x3=_e(["info","warning","error"]),S3=_e(["production","test","generated","vendor","documentation","unknown"]),iv=Ie({production:j().int().nonnegative(),test:j().int().nonnegative(),generated:j().int().nonnegative(),vendor:j().int().nonnegative(),documentation:j().int().nonnegative(),unknown:j().int().nonnegative()}),gv=Ie({execution:j().int().nonnegative(),dependency:j().int().nonnegative(),type:j().int().nonnegative(),structure:j().int().nonnegative(),contextual:j().int().nonnegative(),unknown:j().int().nonnegative()}),E3=Ie({extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()}),T3=Ie({id:D().min(1),label:D(),kind:D(),sourceFile:D().nullable(),sourceScope:S3,scopeReason:D().min(1),community:j().int().nonnegative().nullable()}),O3=Ie({id:D().min(1),source:D().min(1),target:D().min(1),relation:D(),relationClass:tv,confidence:_e(["extracted","inferred","ambiguous"])}),N3=Ie({value:D().min(1),provenance:y3,membershipSignature:D().min(1),quality:j().int().min(0).max(100),evidence:Se(D())}),D3=Ie({id:D().min(1),parentId:D().nullable(),kind:v3,rank:j().int().positive(),name:N3,ownerKey:D().min(1),communityIds:Se(j().int().nonnegative()),nodeCount:j().int().nonnegative(),relationshipCount:j().int().nonnegative(),neighborCount:j().int().nonnegative(),cohesion:j().finite(),sourceScopes:iv,pinned:In()}),k3=Ie({nodeIndex:j().int().nonnegative(),groupIndex:j().int().nonnegative()}),M3=Ie({id:D().min(1),level:b3,ownerId:D().nullable(),sourceGroup:D().min(1),targetGroup:D().min(1),relationshipCount:j().int().nonnegative(),relationClasses:gv,evidence:E3}),R3=Ie({admitted:j().int().nonnegative(),internal:j().int().nonnegative(),crossGroup:j().int().nonnegative(),unassigned:j().int().nonnegative(),relationClasses:gv}),ov=Ie({totalGroups:j().int().nonnegative(),shownGroups:j().int().nonnegative(),omittedGroups:j().int().nonnegative(),representedNodes:j().int().nonnegative(),omittedNodes:j().int().nonnegative(),representedRelationships:j().int().nonnegative(),omittedRelationships:j().int().nonnegative(),witnessGroupIds:Se(D()),maxOverviewGroups:j().int().positive(),maxOverviewRoutes:j().int().positive()}),z3=Ie({code:D().min(1),severity:x3,message:D(),observed:j().nullable(),threshold:j().nullable(),witnesses:Se(D()),recommendedAction:D()}),sv=Ie({status:w3,metrics:Ie({sourceScopes:iv,unknownSourceFraction:j().min(0).max(1),generatedVendorLeakage:j().int().nonnegative(),representedNodeFraction:j().min(0).max(1),representedRelationshipFraction:j().min(0).max(1),duplicateNames:j().int().nonnegative(),fallbackNames:j().int().nonnegative(),largestGroupFraction:j().min(0).max(1),unknownRelations:j().int().nonnegative(),unassignedNodes:j().int().nonnegative(),unassignedRelationships:j().int().nonnegative()}),diagnostics:Se(z3)}),_3=Ie({scope:m3,defaultLens:nv,groups:Se(D3),memberships:Se(k3),routes:Se(M3),overviewGroupIds:Se(D()),overviewRouteIds:Se(D()),coverage:R3,omissions:ov,quality:sv}),j3=Ie({maxNodes:j().int().positive(),maxRelationships:j().int().positive(),maxGroups:j().int().positive(),maxRoutes:j().int().positive(),maxOverviewGroups:j().int().positive(),maxOverviewRoutes:j().int().positive(),maxNameCandidates:j().int().positive(),maxNameEvidence:j().int().positive(),maxDiagnostics:j().int().positive(),maxOmissionWitnesses:j().int().positive()}),P3=Ie({schema:qe(p3),title:D(),nodes:Se(T3),relationships:Se(O3),projections:Se(_3).min(1),statistics:Ie({nodes:j().int().nonnegative(),relationships:j().int().nonnegative(),communities:j().int().nonnegative(),extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()}),provenance:Ie({projectName:D(),builtAtCommit:D().nullable(),generatedAt:D().nullable()}),limits:j3}).superRefine((n,e)=>{const t=new Set(n.nodes.map(i=>i.id));t.size!==n.nodes.length&&e.addIssue({code:"custom",path:["nodes"],message:"node IDs must be unique"});for(const[i,o]of n.relationships.entries())(!t.has(o.source)||!t.has(o.target))&&e.addIssue({code:"custom",path:["relationships",i],message:"relationship endpoints must identify included nodes"});for(const[i,o]of n.projections.entries()){const r=new Set(o.groups.map(A=>A.id));for(const[A,I]of o.memberships.entries())(I.nodeIndex>=n.nodes.length||I.groupIndex>=o.groups.length)&&e.addIssue({code:"custom",path:["projections",i,"memberships",A],message:"membership indexes must identify an included node and group"});for(const[A,I]of o.routes.entries())(!r.has(I.sourceGroup)||!r.has(I.targetGroup))&&e.addIssue({code:"custom",path:["projections",i,"routes",A],message:"route endpoints must identify included groups"})}}),B3=_e(["production","all"]),Z3=_e(["all","extracted","inferred","ambiguous"]),L3=_e(["production","test","generated","vendor","documentation","unknown"]),G3=_e(["extracted","inferred","ambiguous"]),F3=He({production:j().int().nonnegative(),test:j().int().nonnegative(),generated:j().int().nonnegative(),vendor:j().int().nonnegative(),documentation:j().int().nonnegative(),unknown:j().int().nonnegative()}),V3=He({id:D(),name:D(),nodeCount:j().int().nonnegative(),totalNodeCount:j().int().nonnegative(),internalRelationshipCount:j().int().nonnegative(),incomingRelationships:j().int().nonnegative(),outgoingRelationships:j().int().nonnegative(),scopes:F3}),U3=He({id:D(),sourceGroup:D(),targetGroup:D(),relationships:j().int().nonnegative(),extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()});He({title:D(),scope:B3,evidence:Z3,lens:nv,groups:Se(V3),routes:Se(U3),statistics:He({visibleNodes:j().int().nonnegative(),totalNodes:j().int().nonnegative(),visibleRelationships:j().int().nonnegative(),totalRelationships:j().int().nonnegative(),communities:j().int().nonnegative(),extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()}),coverage:He({internal:j().int().nonnegative(),crossGroup:j().int().nonnegative(),unassigned:j().int().nonnegative()}),omissions:ov,quality:sv,provenance:He({projectName:D(),builtAtCommit:D().nullable(),generatedAt:D().nullable()})});const Y3=He({id:D(),label:D(),kind:D(),sourceFile:D().nullable(),scope:L3,groupId:D()}),rv=He({id:D(),source:D(),target:D(),sourceLabel:D(),targetLabel:D(),sourceFile:D().nullable(),targetFile:D().nullable(),sourceGroup:D(),targetGroup:D(),relation:D(),relationClass:tv,confidence:G3}),iC=He({page:j().int().positive(),pageSize:j().int().min(1).max(100),pageCount:j().int().positive(),total:j().int().nonnegative(),start:j().int().nonnegative(),end:j().int().nonnegative()});Ur("kind",[iC.extend({kind:qe("symbols"),groupId:D(),items:Se(Y3)}),iC.extend({kind:qe("relationships"),groupId:D(),items:Se(rv)})]),iC.extend({routeId:D(),sourceGroup:D(),targetGroup:D(),items:Se(rv)});const H3=He({id:D(),kind:_e(["group","symbol","relationship"]),label:D(),detail:D(),groupId:D().nullable(),routeId:D().nullable(),sourceFile:D().nullable()});iC.extend({query:D(),items:Se(H3)});const K3="compass.viewer.workbench/1",W3=Ie({status:_e(["complete","summary","partial"]),truncated:In(),nodes:j().int().nonnegative(),edges:j().int().nonnegative(),limitations:Se(D()).default([])}),yo={id:D().min(1),title:D().min(1),description:D(),coverage:W3},Q3=_e(["dependencies","routes","data","messaging","tests","provenance"]),X3=Ur("kind",[Ie({...yo,kind:qe("code"),model:Ng,communityDetails:eC(D(),Ng).default({})}),Ie({...yo,kind:qe("call"),root:D(),graph:f3}),Ie({...yo,kind:qe("impact"),root:D(),result:n3}),Ie({...yo,kind:qe("architecture"),model:P3}),Ie({...yo,kind:qe("history"),baseRevision:D(),targetRevision:D(),before:Ng,after:Ng}),Ie({...yo,kind:qe("affected"),root:D(),relations:Se(D()),depth:j().int().nonnegative(),model:Ng}),Ie({...yo,kind:qe("artifact"),lens:Q3,relations:Se(D()),model:Ng})]),$3=Ie({schema:qe(K3),title:D(),graphIdentity:D().min(1),defaultView:D(),views:Se(X3).min(1)}).superRefine((n,e)=>{const t=new Set;for(const[i,o]of n.views.entries())t.has(o.id)&&e.addIssue({code:"custom",path:["views",i,"id"],message:`duplicate workbench view id '${o.id}'`}),t.add(o.id);t.has(n.defaultView)||e.addIssue({code:"custom",path:["defaultView"],message:"defaultView must identify one included view"})});var P=tc();const q3=EN({__proto__:null,default:TN(P)},[P]);const J3=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),e_=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase()),av=n=>{const e=e_(n);return e.charAt(0).toUpperCase()+e.slice(1)},Av=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim(),t_=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var n_={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const i_=P.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:o="",children:r,iconNode:A,...I},l)=>P.createElement("svg",{ref:l,...n_,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:Av("lucide",o),...!r&&!t_(I)&&{"aria-hidden":"true"},...I},[...A.map(([c,h])=>P.createElement(c,h)),...Array.isArray(r)?r:[r]]));const Ee=(n,e)=>{const t=P.forwardRef(({className:i,...o},r)=>P.createElement(i_,{ref:r,iconNode:e,className:Av(`lucide-${J3(av(n))}`,`lucide-${n}`,i),...o}));return t.displayName=av(n),t};const Cv=Ee("arrow-down-to-line",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]);const g_=Ee("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);const o_=Ee("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);const s_=Ee("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);const Iv=Ee("arrow-up-from-line",[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]]);const r_=Ee("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const a_=Ee("badge-check",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const A_=Ee("box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);const C_=Ee("boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]);const I_=Ee("braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);const l_=Ee("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);const pc=Ee("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const c_=Ee("circle-check",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const d_=Ee("circle-dot-dashed",[["path",{d:"M10.1 2.18a9.93 9.93 0 0 1 3.8 0",key:"1qdqn0"}],["path",{d:"M17.6 3.71a9.95 9.95 0 0 1 2.69 2.7",key:"1bq7p6"}],["path",{d:"M21.82 10.1a9.93 9.93 0 0 1 0 3.8",key:"1rlaqf"}],["path",{d:"M20.29 17.6a9.95 9.95 0 0 1-2.7 2.69",key:"1xk03u"}],["path",{d:"M13.9 21.82a9.94 9.94 0 0 1-3.8 0",key:"l7re25"}],["path",{d:"M6.4 20.29a9.95 9.95 0 0 1-2.69-2.7",key:"1v18p6"}],["path",{d:"M2.18 13.9a9.93 9.93 0 0 1 0-3.8",key:"xdo6bj"}],["path",{d:"M3.71 6.4a9.95 9.95 0 0 1 2.7-2.69",key:"1jjmaz"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);const lv=Ee("circle-question-mark",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const u_=Ee("compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);const gC=Ee("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);const h_=Ee("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const f_=Ee("file-code-2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);const p_=Ee("file-cog",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m2.305 15.53.923-.382",key:"yfp9st"}],["path",{d:"m3.228 12.852-.924-.383",key:"bckynb"}],["path",{d:"M4.677 21.5a2 2 0 0 0 1.313.5H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2.5",key:"1yo3oz"}],["path",{d:"m4.852 11.228-.383-.923",key:"1j88i9"}],["path",{d:"m4.852 16.772-.383.924",key:"sag1dv"}],["path",{d:"m7.148 11.228.383-.923",key:"rj39hk"}],["path",{d:"m7.53 17.696-.382-.924",key:"1uu5cs"}],["path",{d:"m8.772 12.852.923-.383",key:"13811l"}],["path",{d:"m8.772 15.148.923.383",key:"z1a5l0"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]]);const cv=Ee("file-image",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);const m_=Ee("focus",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);const dv=Ee("git-branch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);const uv=Ee("git-compare-arrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);const mc=Ee("git-fork",[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]]);const v_=Ee("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);const b_=Ee("layout-grid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);const y_=Ee("map-pin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);const w_=Ee("map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);const hv=Ee("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]);const x_=Ee("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const S_=Ee("move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);const vc=Ee("network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);const E_=Ee("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);const T_=Ee("panel-left-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);const fv=Ee("panel-right-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);const O_=Ee("panel-right-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]]);const pv=Ee("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]);const N_=Ee("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]);const mv=Ee("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const D_=Ee("radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);const vv=Ee("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);const bv=Ee("route",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);const yv=Ee("scan-search",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]]);const wv=Ee("scan-text",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 8h8",key:"1jbsf9"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h6",key:"1vyc9m"}]]);const k_=Ee("search-code",[["path",{d:"m13 13.5 2-2.5-2-2.5",key:"1rvxrh"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M9 8.5 7 11l2 2.5",key:"6ffwbx"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);const xv=Ee("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);const M_=Ee("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const R_=Ee("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);const z_=Ee("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const __=Ee("signpost",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M18 6a2 2 0 0 1 1.387.56l2.307 2.22a1 1 0 0 1 0 1.44l-2.307 2.22A2 2 0 0 1 18 13H6a2 2 0 0 1-1.387-.56l-2.306-2.22a1 1 0 0 1 0-1.44l2.306-2.22A2 2 0 0 1 6 6z",key:"gqqp9m"}]]);const j_=Ee("sliders-horizontal",[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]]);const P_=Ee("tags",[["path",{d:"M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z",key:"16rjxf"}],["path",{d:"M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193",key:"178nd4"}],["circle",{cx:"10.5",cy:"6.5",r:".5",fill:"currentColor",key:"12ikhr"}]]);const Yr=Ee("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const B_=Ee("waypoints",[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]]);const Z_=Ee("zoom-in",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);const L_=Ee("zoom-out",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Sv=new Set(["color","change","evidence"]),G_=new Set(["anchor","anchors","columnEnd","columnStart","community","communityName","community_name","degree","endByte","endColumn","endLine","lineEnd","lineStart","line_end","line_start","location","normLabel","norm_label","relationshipSite","relationship_site","size","sourceDigest","sourceFile","sourceHash","source_digest","source_file","source_hash","startByte","startColumn","startLine","wiringSite","wiring_site"]);function oC(n,e){const t=sC(n),i=sC(e);return{...t?{before:t}:{},...i?{after:i}:{},fields:yc(t,i)}}function Ev(n,e,t){const i=sC(n),o=sC(e),r=bc(n,t),A=bc(e,t);return{...i?{before:i}:{},...o?{after:o}:{},fields:yc(r,A)}}function F_(n,e){return bc(n,e)??{}}function V_(n,e=240){const t=n===void 0?"Not recorded":typeof n=="string"?n:JSON.stringify(n,null,Hr(n)?2:void 0)??String(n);return t.length<=e?{text:t,truncated:!1}:{text:`${t.slice(0,Math.max(0,e-1)).trimEnd()}…`,truncated:!0}}function sC(n){if(n)return Nv(n)}function bc(n,e){return n?Ov(n,e==="node"?new Set(["source"]):new Set(["id","key"])):void 0}function Tv(n){return Array.isArray(n)?n.map(Tv):Hr(n)?Ov(n):n}function Ov(n,e=new Set){return Object.fromEntries(Object.keys(n).filter(t=>!Sv.has(t)&&!G_.has(t)&&!e.has(t)).sort((t,i)=>t.localeCompare(i)).map(t=>[t,Tv(n[t])]))}function rC(n){return Array.isArray(n)?n.map(rC):Hr(n)?Nv(n):n}function Nv(n){return Object.fromEntries(Object.keys(n).filter(e=>!Sv.has(e)).sort((e,t)=>e.localeCompare(t)).map(e=>[e,rC(n[e])]))}function yc(n,e,t=""){const i=new Set([...Object.keys(n??{}),...Object.keys(e??{})]),o=[];for(const r of[...i].sort((A,I)=>A.localeCompare(I))){const A=t?`${t}.${r}`:r,I=n?.[r],l=e?.[r];Hr(I)&&Hr(l)?o.push(...yc(I,l,A)):U_(I,l)||o.push({field:A,...I!==void 0?{before:I}:{},...l!==void 0?{after:l}:{}})}return o}function U_(n,e){return JSON.stringify(rC(n))===JSON.stringify(rC(e))}function Hr(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Y_({node:n,edges:e,nodes:t,sourceRevisions:i,onFocus:o,onOpenSource:r}){const A=Mv(n.evidence?.before),I=Mv(n.evidence?.after);return f.jsxs(f.Fragment,{children:[n.evidence?.fields.length?f.jsxs("section",{className:"compass-record-evidence","aria-labelledby":"compass-node-changes-title",children:[f.jsxs("div",{className:"compass-evidence-heading",children:[f.jsx("h3",{id:"compass-node-changes-title",children:H_(n.change)}),f.jsxs("span",{children:[n.evidence.fields.length," fields"]})]}),f.jsx(Dv,{fields:n.evidence.fields}),n.change==="changed"&&(A||I)&&f.jsxs("div",{className:"compass-evidence-source-actions",children:[A&&f.jsxs("button",{type:"button",onClick:()=>r(A,i?.before),children:[f.jsx(gC,{"aria-hidden":"true"}),"Open before"]}),I&&f.jsxs("button",{type:"button",onClick:()=>r(I,i?.after),children:[f.jsx(gC,{"aria-hidden":"true"}),"Open after"]})]})]}):null,f.jsxs("section",{className:"compass-relationship-evidence","aria-labelledby":"compass-relationships-title",children:[f.jsxs("div",{className:"compass-neighbors-heading",children:[f.jsx("span",{id:"compass-relationships-title",children:"Relationships"}),f.jsx("strong",{children:e.length})]}),e.length?f.jsx("div",{className:"compass-relationship-list",children:e.map(l=>{const c=l.source===n.id?l.target:l.source,h=t.get(c);return f.jsxs("details",{children:[f.jsxs("summary",{children:[f.jsx("span",{className:"compass-change-badge","data-change":l.change,children:Rv(l.change)}),f.jsx("span",{className:"compass-relationship-target",children:h?.label??c}),f.jsx("small",{children:l.relation}),l.confidence&&f.jsx("i",{children:l.confidence})]}),f.jsxs("div",{className:"compass-relationship-detail",children:[l.change==="changed"&&l.evidence?.fields.length?f.jsx(Dv,{fields:l.evidence.fields}):f.jsxs("p",{children:[Rv(l.change)," relationship: ",l.source," → ",l.target]}),f.jsxs("button",{type:"button",onClick:()=>o(c),children:["Focus ",h?.label??c]})]})]},l.id)})}):f.jsx("span",{className:"compass-empty",children:"No connected relationships"})]})]})}function Dv({fields:n}){return f.jsx("div",{className:"compass-field-table-wrap",children:f.jsxs("table",{className:"compass-field-table",children:[f.jsx("thead",{children:f.jsxs("tr",{children:[f.jsx("th",{children:"Field"}),f.jsx("th",{children:"Before"}),f.jsx("th",{children:"After"})]})}),f.jsx("tbody",{children:n.map(e=>f.jsxs("tr",{children:[f.jsx("th",{scope:"row",children:e.field}),f.jsx(kv,{value:e.before}),f.jsx(kv,{value:e.after})]},e.field))})]})})}function kv({value:n}){const e=V_(n);return f.jsxs("td",{children:[f.jsx("code",{children:e.text}),e.truncated&&f.jsx("span",{className:"compass-value-truncated",children:"Value shortened"})]})}function Mv(n){const e=fc.safeParse(n?.source);return e.success?e.data:void 0}function Rv(n){return!n||n==="unchanged"?"Context":`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`}function H_(n){return n==="added"?"Added symbol metadata":n==="removed"?"Removed symbol metadata":"What changed"}const zv=100,_v={changed:0,added:1,removed:2,unchanged:3};function K_({nodes:n,query:e,selectedId:t,onFocus:i}){const[o,r]=P.useState(!1),A=e.trim().toLocaleLowerCase(),I=n.filter(c=>c.change&&c.change!=="unchanged").filter(c=>!A||c.label.toLocaleLowerCase().includes(A)||c.kind?.toLocaleLowerCase().includes(A)||c.source?.file.toLocaleLowerCase().includes(A)).sort((c,h)=>_v[c.change??"unchanged"]-_v[h.change??"unchanged"]||c.label.localeCompare(h.label)||c.id.localeCompare(h.id)),l=o?I:I.slice(0,zv);return f.jsxs("section",{className:"compass-changed-symbols","aria-labelledby":"compass-changed-symbols-title",children:[f.jsxs("div",{className:"compass-section-heading",children:[f.jsx("h2",{id:"compass-changed-symbols-title",children:"Changed symbols"}),f.jsx("span",{children:I.length})]}),l.length?f.jsx("div",{className:"compass-changed-symbol-list",children:l.map(c=>f.jsxs("button",{type:"button","aria-pressed":c.id===t,"data-change":c.change,onClick:()=>i(c.id),children:[f.jsx("span",{className:"compass-changed-symbol-status",children:W_(c.change)}),f.jsx("strong",{children:c.label}),f.jsx("small",{children:c.source?.file??c.kind??"Graph symbol"})]},c.id))}):f.jsx("p",{className:"compass-empty",children:A?"No affected symbols match this search.":"No symbol changes."}),!o&&I.length>zv&&f.jsxs("button",{className:"compass-changed-symbol-expand",type:"button",onClick:()=>r(!0),children:["Show all ",I.length.toLocaleString()," affected symbols"]})]})}function W_(n){return!n||n==="unchanged"?"Context":`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`}function jv({evidence:n,diagnostics:e=[],truncated:t=!1,title:i="Trust evidence",onOpenSource:o}){return!n.length&&!e.length&&!t?null:f.jsxs("section",{className:"compass-code-evidence","aria-label":i,children:[f.jsxs("div",{className:"compass-evidence-heading",children:[f.jsx("h3",{children:i}),f.jsxs("span",{children:[n.length," ",n.length===1?"record":"records"]})]}),t&&f.jsxs("p",{className:"compass-code-diagnostic","data-severity":"warning",role:"status",children:[f.jsx(Yr,{"aria-hidden":"true"}),"Results reached a configured limit. Narrow the query or raise one bound."]}),e.map(r=>f.jsxs("p",{className:"compass-code-diagnostic","data-severity":r.code==="no_match"?"info":"warning",role:"status",children:[r.code==="no_match"?f.jsx(lv,{"aria-hidden":"true"}):f.jsx(Yr,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:$_(r.code)}),r.message]})]},`${r.code}:${r.message}`)),f.jsx("div",{className:"compass-code-evidence-ledger",children:n.map((r,A)=>{const I=X_(r),l=r.wiringSite??r.anchor;return f.jsxs("article",{className:"compass-code-evidence-entry","data-status":I.key,children:[f.jsx("span",{className:"compass-code-evidence-icon","aria-hidden":"true",children:f.jsx(Q_,{item:r})}),f.jsxs("div",{className:"compass-code-evidence-copy",children:[f.jsxs("div",{className:"compass-code-evidence-status",children:[f.jsx("strong",{children:I.label}),f.jsx("span",{children:r.layer==="program_ir"?"Program IR":"Code graph"})]}),f.jsxs("dl",{children:[f.jsxs("div",{children:[f.jsx("dt",{children:"Extractor"}),f.jsx("dd",{children:r.extractor})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Confidence"}),f.jsx("dd",{children:r.confidence})]}),r.rule&&f.jsxs("div",{children:[f.jsx("dt",{children:"Rule"}),f.jsx("dd",{children:r.rule})]})]}),l&&(o?f.jsxs("button",{className:"compass-code-evidence-source",type:"button",onClick:()=>o(l),children:[f.jsx(gC,{"aria-hidden":"true"}),Pv(r,l)]}):f.jsx("span",{className:"compass-code-evidence-source",children:Pv(r,l)})),r.candidates.length>0&&f.jsxs("div",{className:"compass-code-candidates",children:[f.jsx("span",{children:"Retained candidates"}),f.jsx("ul",{children:r.candidates.map(c=>f.jsxs("li",{children:[f.jsx("code",{children:c.nodeId}),f.jsx("span",{children:c.reason}),f.jsx("small",{children:c.confidence})]},`${c.nodeId}:${c.reason}`))})]})]})]},`${r.layer}:${r.extractor}:${A}`)})})]})}function Q_({item:n}){return n.resolution==="unresolved"?f.jsx(lv,{}):n.resolution==="ambiguous"||n.confidence==="ambiguous"?f.jsx(Yr,{}):n.origin==="heuristic"?f.jsx(mc,{}):n.origin==="config"?f.jsx(p_,{}):n.origin==="convention"?f.jsx(__,{}):f.jsx(a_,{})}function X_(n){return n.resolution==="unresolved"?{key:"unresolved",label:"Unresolved"}:n.resolution==="ambiguous"||n.confidence==="ambiguous"?{key:"ambiguous",label:"Ambiguous"}:n.origin==="heuristic"?{key:"heuristic",label:"Heuristic"}:n.origin==="config"?{key:"config",label:"Configuration"}:n.origin==="convention"?{key:"convention",label:"Convention"}:{key:"exact",label:"Exact"}}function Pv(n,e){return`${n.origin==="heuristic"?"Wired at":"Evidence at"} ${e.file}:${e.startLine}`}function $_(n){return`${n.replaceAll("_"," ")}: `}const hs=[{id:"combined",label:"Combined"},{id:"native",label:"Native"},{id:"ocr",label:"OCR evidence"}];function q_(n,e){if(!e.document)return;const t=e.source?.file,i=n.nodes.filter(A=>A.document?t===void 0||A.source?.file===t:!1),o=i.find(A=>A.document?.role==="root")??(e.document.role==="root"?e:void 0),r=i.filter(A=>A.document?.role==="block");if(e.document.role==="block"&&!r.some(A=>A.id===e.id)&&r.push(e),!(!o&&r.length===0))return r.sort(oj),{...t!==void 0?{sourceFile:t}:{},...o?{root:o}:{},blocks:r}}function J_({context:n,selectedId:e,onFocus:t}){const[i,o]=P.useState("combined"),r=P.useMemo(()=>n.blocks.filter(wc),[n.blocks]),A=P.useMemo(()=>n.blocks.filter(y=>!wc(y)),[n.blocks]),[I,l]=P.useState(e&&r.some(y=>y.id===e)?e:r[0]?.id);P.useEffect(()=>{o("combined"),l(e&&r.some(y=>y.id===e)?e:r[0]?.id)},[n.sourceFile,r,e]);const c=i==="ocr"?r:i==="native"?A:n.blocks,h=n.root?.document,p=h?.visualCoverage??(r.length>0?"complete":"not_requested"),m=h?.ocrMode??(r.length>0?"auto":"off"),v=Zv(h?.ocrProfile)??r.map(y=>Zv(xc(y)?.profile)).find(Boolean),x=p==="failed"?"failed":p==="partial"?"partial":h?.complete===!1?"incomplete":void 0,O=r.find(y=>y.id===I);return f.jsxs("section",{className:"compass-document-evidence","aria-labelledby":"compass-document-evidence-title",children:[f.jsxs("header",{className:"compass-document-evidence-header",children:[f.jsxs("div",{className:"compass-document-evidence-heading",children:[f.jsx("span",{className:"compass-document-evidence-mark","aria-hidden":"true",children:f.jsx(wv,{})}),f.jsxs("span",{children:[f.jsx("small",{children:"Document evidence"}),f.jsx("h3",{id:"compass-document-evidence-title",children:rj(n.sourceFile,h?.format)})]})]}),f.jsx(ej,{mode:m,coverage:p,...v?{profile:v}:{}})]}),x&&f.jsxs("div",{className:"compass-document-warning","data-status":x,role:"alert",children:[f.jsx(R_,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:x==="failed"?"OCR could not complete":x==="partial"?"OCR coverage is partial":"Document extraction is incomplete"}),f.jsx("small",{children:x==="incomplete"?"Compass retained the available evidence; review the document diagnostics before relying on it as complete.":"Native text is still available. Some visual regions could not be processed."})]})]}),f.jsx("div",{className:"compass-document-tabs",role:"tablist","aria-label":"Document evidence views",children:hs.map((y,T)=>{const S=y.id==="ocr"?r.length:y.id==="native"?A.length:n.blocks.length,_=i===y.id;return f.jsxs("button",{id:`compass-document-tab-${y.id}`,className:"compass-document-tab",type:"button",role:"tab","aria-selected":_,"aria-controls":"compass-document-panel",tabIndex:_?0:-1,onClick:()=>o(y.id),onKeyDown:B=>{const Q=B.key==="ArrowRight"?(T+1)%hs.length:B.key==="ArrowLeft"?(T-1+hs.length)%hs.length:B.key==="Home"?0:B.key==="End"?hs.length-1:void 0;if(Q===void 0)return;B.preventDefault();const te=hs[Q];te&&(o(te.id),document.getElementById(`compass-document-tab-${te.id}`)?.focus())},children:[y.label,f.jsx("span",{children:S})]},y.id)})}),f.jsx("div",{id:"compass-document-panel",className:"compass-document-tab-panel",role:"tabpanel","aria-labelledby":`compass-document-tab-${i}`,tabIndex:0,children:c.length>0?f.jsx("div",{className:"compass-document-block-list",children:c.map(y=>f.jsx(tj,{block:y,active:y.id===e,onClick:()=>{wc(y)&&l(y.id),t(y.id)}},y.id))}):f.jsxs("div",{className:"compass-document-empty",children:[f.jsx(cv,{"aria-hidden":"true"}),f.jsx("strong",{children:i==="ocr"?"No OCR evidence":"No document blocks"}),f.jsx("span",{children:i==="ocr"?"Run extraction with a managed OCR profile to inspect visual text.":"This document did not publish readable native blocks."})]})}),O&&f.jsx(gj,{block:O,siblings:r,...h?.previews?{previews:h.previews}:{},onFocus:y=>{l(y),t(y)}}),!O&&h?.previews&&h.previews.length>0&&f.jsx(ij,{previews:h.previews})]})}function ej({mode:n,coverage:e,profile:t}){const i=e==="complete",o=n!=="off",r=`OCR ${o?Lv(n):"Off"} · ${o?Gv(e):"Native only"}${t?` · ${t}`:""}`;return f.jsxs("span",{className:"compass-ocr-status-chip","data-status":e,role:"status","aria-label":r,title:r,children:[i?f.jsx(c_,{"aria-hidden":"true"}):f.jsx(Yr,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsxs("strong",{children:["OCR ",o?Lv(n):"Off"]}),f.jsx("small",{children:o?Gv(e):"Native only"})]}),t&&f.jsx("em",{children:t})]})}function tj({block:n,active:e,onClick:t}){const i=xc(n),o=n.document?.text??n.label,r=n.document?.locator;return f.jsxs("button",{className:"compass-document-block","data-origin":i?"ocr":"native","data-active":e,type:"button","aria-pressed":e,onClick:t,children:[f.jsxs("span",{className:"compass-document-block-topline",children:[f.jsxs("span",{className:"compass-document-block-kind",children:[i?f.jsx(wv,{"aria-hidden":"true"}):f.jsx(cv,{"aria-hidden":"true"}),i?"OCR evidence":aj(n.document?.kind)]}),i&&f.jsx(nj,{confidence:i.confidence_bps})]}),f.jsx("span",{className:"compass-document-block-text",children:o||"(empty block)"}),f.jsxs("span",{className:"compass-document-block-locator",children:[f.jsx(y_,{"aria-hidden":"true"}),fs(r),i&&f.jsx(h_,{"aria-hidden":"true"})]})]})}function nj({confidence:n}){const e=Math.max(0,Math.min(100,n/100)),t=e>=85?"high":e>=60?"medium":"low";return f.jsxs("span",{className:"compass-ocr-confidence","data-confidence":t,children:[e.toFixed(2),"%"]})}function ij({previews:n}){const[e,t]=P.useState(0);P.useEffect(()=>{t(o=>Math.min(o,Math.max(0,n.length-1)))},[n.length]);const i=n[e];return i?f.jsxs("div",{className:"compass-ocr-preview compass-document-preview-gallery","aria-label":"Document preview",children:[f.jsxs("header",{children:[f.jsxs("span",{children:[f.jsx("strong",{children:i.label}),f.jsxs("small",{children:[fs(i.locator)," · Normalized preview"]})]}),n.length>1&&f.jsxs("span",{className:"compass-document-preview-controls",children:[f.jsx("button",{type:"button","aria-label":"Previous document preview",disabled:e===0,onClick:()=>t(o=>Math.max(0,o-1)),children:f.jsx(l_,{"aria-hidden":"true"})}),f.jsxs("span",{children:[e+1," / ",n.length]}),f.jsx("button",{type:"button","aria-label":"Next document preview",disabled:e===n.length-1,onClick:()=>t(o=>Math.min(n.length-1,o+1)),children:f.jsx(pc,{"aria-hidden":"true"})})]})]}),f.jsx("div",{className:"compass-document-preview-stage",children:f.jsx("img",{className:"compass-document-preview-image",src:Fv(i.svg),alt:`${i.label} document preview`})}),f.jsx("p",{children:"Compass generated a bounded local snapshot. Native text remains the authoritative evidence."})]}):null}function gj({block:n,siblings:e,previews:t,onFocus:i}){const o=n.document.locator,r=aC(o.width),A=aC(o.height),I=o.candidate_id,l=e.filter(h=>{const p=h.document.locator;return p.candidate_id===I&&p.width===o.width&&p.height===o.height});if(!r||!A)return null;const c=Aj(t,o);return f.jsxs("div",{className:"compass-ocr-preview","aria-label":"OCR region preview",children:[f.jsxs("header",{children:[f.jsxs("span",{children:[f.jsx("strong",{children:c?.label??"Visual region"}),f.jsxs("small",{children:[fs(o.owner)," · ",r," × ",A,"px"]})]}),f.jsxs("span",{className:"compass-ocr-preview-key",children:[f.jsx("i",{}),"OCR boxes",c?" · normalized preview":""]})]}),c?f.jsxs("div",{className:"compass-document-preview-stage",children:[f.jsx("img",{className:"compass-document-preview-image",src:Fv(c.svg),alt:`${c.label} document preview`}),f.jsx("svg",{className:"compass-document-preview-overlay",viewBox:`0 0 ${c.width} ${c.height}`,role:"img","aria-label":`OCR bounding boxes over ${c.label}`,preserveAspectRatio:"none",children:l.map(h=>{const p=Cj(h.document.locator,c);return p?Bv(h,p,h.id===n.id,i):null})})]}):f.jsxs("svg",{className:"compass-ocr-preview-canvas",viewBox:`0 0 ${r} ${A}`,role:"img","aria-label":`OCR bounding boxes for ${fs(o.owner)}`,children:[f.jsx("defs",{children:f.jsx("pattern",{id:"compass-ocr-preview-grid",width:"32",height:"32",patternUnits:"userSpaceOnUse",children:f.jsx("path",{d:"M 32 0 L 0 0 0 32",fill:"none",stroke:"currentColor",strokeOpacity:"0.12",strokeWidth:"1"})})}),f.jsx("rect",{width:r,height:A,fill:"var(--compass-ocr-preview-surface)"}),f.jsx("rect",{width:r,height:A,fill:"url(#compass-ocr-preview-grid)"}),l.map(h=>{const p=h.document.locator,m=lj(p.polygon,r,A);return m?Bv(h,m,h.id===n.id,i):null})]}),f.jsx("p",{children:c?"OCR boxes are mapped to the embedded image region. Click a box to inspect its text and confidence.":"Click a highlighted region to inspect its text and confidence."})]})}function Bv(n,e,t,i){return f.jsx("polygon",{className:"compass-ocr-preview-box","data-active":t,points:e,role:"button",tabIndex:0,"aria-label":`${n.document.text??n.label} · ${fs(n.document.locator)}`,onClick:()=>i(n.id),onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),i(n.id))},children:f.jsx("title",{children:n.document.text??n.label})},n.id)}function wc(n){return xc(n)!==void 0&&n.document?.locator?.kind==="ocr"}function xc(n){return n.document?.origin?.kind==="ocr"?n.document.origin:void 0}function oj(n,e){const t=n.document?.ordinal??Number.MAX_SAFE_INTEGER,i=e.document?.ordinal??Number.MAX_SAFE_INTEGER;return t-i||n.id.localeCompare(e.id)}function Zv(n){const e=n?.profile;return typeof e=="string"?sj(e):void 0}function sj(n){return n.replace(/^pp-/,"PP-").replace(/ocrv(\d+)/i,"OCRv$1").replace(/-(small|medium)$/i,(e,t)=>` ${t[0]?.toUpperCase()}${t.slice(1)}`)}function Lv(n){return n.length>0?`${n[0]?.toUpperCase()}${n.slice(1)}`:"Off"}function Gv(n){return{complete:"Complete",partial:"Partial coverage",failed:"Failed",not_requested:"Not requested"}[n]??"Unknown"}function rj(n,e){const t=n?.split(/[\\/]/).pop()??"Document";return e?`${t} · ${e.toUpperCase()}`:t}function aj(n){return n?n.replaceAll("_"," ").replace(/\b\w/g,e=>e.toUpperCase()):"Native text"}function fs(n){if(!n)return"Location unavailable";switch(n.kind){case"ocr":{const e=_t(n,"owner"),t=jn(_t(n,"occurrence"))??0;return`${fs(Vv(e)?e:void 0)} · Region ${t+1}`}case"pdf":return`Page ${jn(_t(n,"page"))??"?"}`;case"page":return`Page ${jn(_t(n,"page"))??"?"}`;case"slide":return`Slide ${jn(_t(n,"slide"))??"?"}${_t(n,"shape")!==void 0?` · Shape ${String(_t(n,"shape"))}`:""}`;case"spreadsheet":{const e=_t(n,"sheet");return`${typeof e=="string"?e:"Sheet"}!${Ij(jn(_t(n,"column"))??1)}${jn(_t(n,"row"))??"?"}`}case"package":{const e=_t(n,"part"),t=_t(n,"path"),i=typeof e=="string"?e:"Package part";if(/\/(?:media|embeddings)\//i.test(i)||/\.(?:avif|bmp|gif|jpe?g|png|tiff?|webp)$/i.test(i))return"Embedded image";const o=i.split(/[\\/]/).pop()||"Package part";return typeof t=="string"&&t.length>0?`${o} · ${t}`:o}case"text_range":{const e=jn(_t(n,"start_line")),t=jn(_t(n,"end_line"));return e!==void 0?`Lines ${e}${t!==void 0&&t!==e?`–${t}`:""}`:"Text range"}default:return"Document location"}}function Aj(n,e){if(!n||n.length===0)return;const t=e.candidate_id;if(t){const o=n.find(r=>r.regions.some(A=>A.candidate_id===t));if(o)return o}const i=e.owner;if(Vv(i)){if(i.kind==="slide"){const o=jn(_t(i,"slide")),r=n.find(A=>A.kind==="slide"&&A.locator.kind==="slide"&&jn(_t(A.locator,"slide"))===o);if(r)return r}if(i.kind==="spreadsheet"){const o=_t(i,"sheet"),r=n.find(A=>A.kind==="sheet"&&A.locator.kind==="spreadsheet"&&_t(A.locator,"sheet")===o);if(r)return r}}return n[0]}function Fv(n){return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`}function Cj(n,e){const t=n.candidate_id,i=t?e.regions.find(I=>I.candidate_id===t):void 0,o=aC(n.width),r=aC(n.height);if(!i||!o||!r||!Array.isArray(n.polygon))return;const A=n.polygon.slice(0,256).flatMap(I=>{if(typeof I!="object"||I===null)return[];const l=jn(_t(I,"x")),c=jn(_t(I,"y"));if(l===void 0||c===void 0)return[];const h=i.x+AC(l/o,0,1)*i.width,p=i.y+AC(c/r,0,1)*i.height;return[`${h},${p}`]});return A.length>=3?A.join(" "):void 0}function _t(n,e){return n[e]}function Vv(n){return typeof n=="object"&&n!==null&&typeof _t(n,"kind")=="string"}function jn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ij(n){let e=Math.max(1,Math.floor(n)),t="";for(;e>0;){const i=(e-1)%26;t=String.fromCharCode(65+i)+t,e=Math.floor((e-1)/26)}return t}function aC(n){return n!==void 0&&Number.isFinite(n)&&n>0&&n<=1e4?n:void 0}function lj(n,e,t){if(!Array.isArray(n))return;const i=n.slice(0,256).flatMap(o=>{if(typeof o!="object"||o===null)return[];const r=jn(_t(o,"x")),A=jn(_t(o,"y"));return r!==void 0&&A!==void 0?[`${AC(r,0,e)},${AC(A,0,t)}`]:[]});return i.length>=3?i.join(" "):void 0}function AC(n,e,t){return Math.max(e,Math.min(t,n))}function Uv(n){return Hv(n.source)}function Yv(n){return Hv(n.relationshipSite)}function Hv(n){return n?.file.trim()&&(n.startLine!==void 0||n.endLine!==void 0||n.startByte!==void 0||n.endByte!==void 0)?n:void 0}const Kv=200;function cj(n,e,t){const i=new Map,o=new Map,r=(I,l,c)=>{const h=t.get(l);if(!h)return;const p=I.get(l);p?p.edges.push(c):I.set(l,{node:h,edges:[c]})};for(const I of e)I.target===n&&r(i,I.source,I),I.source===n&&r(o,I.target,I);const A=I=>[...I.values()].map(l=>({...l,edges:l.edges.sort((c,h)=>c.relation.localeCompare(h.relation)||c.id.localeCompare(h.id))})).sort((l,c)=>l.node.label.localeCompare(c.node.label)||l.node.id.localeCompare(c.node.id));return{incoming:A(i),outgoing:A(o)}}function dj(n){const e=new Map;for(const t of n){const i=t.relation||"related";e.set(i,(e.get(i)??0)+(t.weight??1))}return[...e.entries()].sort(([t],[i])=>t.localeCompare(i)).map(([t,i])=>i>1?`${t} ×${i}`:t).join(" · ")}function Wv({direction:n,groups:e,communityColors:t,onFocus:i}){const o=n==="incoming",r=e.reduce((c,h)=>c+h.edges.length,0),A=o?"Incoming":"Outgoing",I=o?"Nodes that point to this node":"Nodes this node points to",l=o?Cv:Iv;return f.jsxs("section",{className:"compass-direction-group","data-direction":n,children:[f.jsxs("div",{className:"compass-direction-heading",children:[f.jsx("span",{className:"compass-direction-icon","aria-hidden":"true",children:f.jsx(l,{})}),f.jsxs("span",{className:"compass-direction-copy",children:[f.jsx("strong",{children:A}),f.jsx("small",{children:I})]}),f.jsxs("span",{className:"compass-direction-count",children:[f.jsx("strong",{children:e.length}),f.jsxs("small",{children:[r," ",r===1?"edge":"edges"]})]})]}),f.jsx("div",{className:"compass-direction-list",children:e.length?e.map(c=>{const h=dj(c.edges);return f.jsxs("button",{type:"button",className:"compass-direction-link",title:`Focus ${c.node.label}`,"aria-label":`Focus ${c.node.label}; ${A.toLocaleLowerCase()}; ${h}`,onClick:()=>i(c.node.id),children:[f.jsx("span",{className:"compass-neighbor-dot","aria-hidden":"true",style:{background:c.node.color?.background??t.get(c.node.community)??"var(--border)"}}),f.jsxs("span",{className:"compass-direction-node",children:[f.jsx("strong",{children:c.node.label}),f.jsx("small",{children:h})]}),f.jsx(pc,{"aria-hidden":"true"})]},c.node.id)}):f.jsx("span",{className:"compass-direction-empty",children:o?"No incoming relationships":"No outgoing relationships"})})]})}function uj(n,e){const t=e.trim().toLocaleLowerCase();return(t?n.filter(o=>o.label.toLocaleLowerCase().includes(t)||String(o.id).includes(t)):n).slice(0,Kv)}function hj(n){const e=n.source?.startLine,t=n.source?.endLine;if(e!==void 0)return t!==void 0&&t!==e?`${e}–${t}`:String(e)}function Qv(n){const e=n.source?.startLine,t=n.source?.endLine;if(e!==void 0)return t!==void 0&&t!==e?{text:`Lines ${e}–${t}`,action:`at lines ${e}–${t}`}:{text:`Line ${e}`,action:`at line ${e}`};const i=n.source?.startByte,o=n.source?.endByte;if(i!==void 0)return o!==void 0&&o!==i?{text:`Bytes ${i}–${o}`,action:`at bytes ${i}–${o}`}:{text:`Byte ${i}`,action:`at byte ${i}`}}function Xv(n,e){const t=Qv(n);return`Open source ${e.file}${t?` ${t.action}`:""}`}function $v(n){return n==="unchanged"?"Context":n?`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`:void 0}function fj(n){if(n)return{added:"var(--vscode-gitDecoration-addedResourceForeground, #2ea043)",removed:"var(--vscode-gitDecoration-deletedResourceForeground, #f85149)",changed:"var(--vscode-gitDecoration-modifiedResourceForeground, #d29922)",unchanged:"var(--vscode-descriptionForeground, #6e7781)"}[n]}function pj({model:n,selected:e,neighbors:t,connectedEdges:i,query:o,matches:r,hiddenCommunities:A,comparisonMode:I,sourceRevisions:l,queryResult:c,renderedEdgeCount:h,showHeader:p,onQueryChange:m,onFocus:v,onOpenSource:x,onOpenCommunity:O,onQueryNode:y,onToggleCommunity:T,onSetAllVisible:S,collapsed:_,onToggleCollapsed:B}){const[Q,te]=P.useState(0),V=e?Uv(e):void 0,U=e?hj(e):void 0,Ce=e?Qv(e):void 0,Te=P.useMemo(()=>{const E=new Map;for(const G of n.nodes)E.set(G.community,(E.get(G.community)??0)+1);return E},[n.nodes]),Ze=A.size===0,ye=P.useMemo(()=>new Map(n.nodes.map(E=>[E.id,E])),[n.nodes]),Fe=P.useMemo(()=>new Map(n.communities.map(E=>[E.id,E.color])),[n.communities]),Ge=P.useMemo(()=>e?cj(e.id,i,ye):{incoming:[],outgoing:[]},[i,ye,e?.id]),le=e?c?.nodes.find(E=>E.id===e.id):void 0,M=e?q_(n,e):void 0,W=le?.evidence??e?.codeEvidence??[],oe=e?c?c.edges.filter(E=>E.source===e.id||E.target===e.id).flatMap(E=>E.evidence):i.flatMap(E=>E.codeEvidence??[]):[],se=E=>{v(E.id),m(""),te(0)},J=E=>{!r.length&&E.key!=="Escape"||(E.key==="ArrowDown"?(E.preventDefault(),te((Q+1)%r.length)):E.key==="ArrowUp"?(E.preventDefault(),te((Q-1+r.length)%r.length)):E.key==="Enter"&&r[Q]?(E.preventDefault(),se(r[Q])):E.key==="Escape"&&(m(""),te(0)))};return _?f.jsxs("aside",{className:"compass-graph-inspector compass-graph-inspector-collapsed","aria-label":"Graph inspector",children:[f.jsx("button",{className:"compass-inspector-disclosure compass-inspector-expand",type:"button","aria-label":"Expand graph inspector",title:"Expand graph inspector",onClick:B,children:f.jsx(O_,{"aria-hidden":"true"})}),f.jsx("span",{className:"compass-inspector-rail-label","aria-hidden":"true",children:"Inspector"})]}):f.jsxs("aside",{className:"compass-graph-inspector","aria-label":"Graph inspector",children:[p&&f.jsxs("header",{className:"compass-inspector-header",children:[f.jsx("span",{className:"compass-product-mark","aria-hidden":"true",children:f.jsx(u_,{})}),f.jsxs("span",{className:"compass-inspector-title",children:[f.jsx("strong",{children:"Compass"}),f.jsx("small",{children:n.title})]}),f.jsx("button",{className:"compass-inspector-disclosure",type:"button","aria-label":"Collapse graph inspector",title:"Collapse graph inspector",onClick:B,children:f.jsx(fv,{"aria-hidden":"true"})})]}),f.jsxs("div",{className:"compass-inspector-search",role:"search",children:[f.jsx("label",{className:"sr-only",htmlFor:"compass-node-search",children:"Search graph nodes"}),f.jsxs("div",{className:"compass-inspector-search-row",children:[f.jsxs("div",{className:"compass-search-field",children:[f.jsx(xv,{"aria-hidden":"true"}),f.jsx("input",{id:"compass-node-search",type:"search",role:"combobox",value:o,placeholder:"Search nodes and files",autoComplete:"off","aria-controls":"compass-search-results","aria-autocomplete":"list","aria-expanded":r.length>0,"aria-activedescendant":r[Q]?`compass-search-result-${Q}`:void 0,onChange:E=>{m(E.target.value),te(0)},onKeyDown:J})]}),!p&&f.jsx("button",{className:"compass-inspector-disclosure compass-inspector-search-disclosure",type:"button","aria-label":"Collapse graph inspector",title:"Collapse graph inspector",onClick:B,children:f.jsx(fv,{"aria-hidden":"true"})})]}),r.length>0&&f.jsx("div",{id:"compass-search-results",className:"compass-search-results",role:"listbox","aria-label":"Matching nodes",children:r.map((E,G)=>f.jsxs("button",{id:`compass-search-result-${G}`,type:"button",role:"option","aria-selected":G===Q,className:"compass-search-item",onMouseEnter:()=>te(G),onClick:()=>se(E),children:[f.jsx("strong",{children:E.label}),f.jsx("span",{children:E.source?.file??E.kind??"Graph node"})]},E.id))})]}),f.jsxs("section",{className:"compass-info-panel","aria-labelledby":"compass-info-title",children:[f.jsxs("div",{className:"compass-section-heading",children:[f.jsx("h2",{id:"compass-info-title",children:"Inspector"}),f.jsx("span",{children:e?"Pinned":"Node details"})]}),e?f.jsxs("div",{className:"compass-info-content",children:[f.jsxs("div",{className:"compass-node-identity",children:[f.jsx("span",{className:"compass-node-swatch","aria-hidden":"true",style:{background:fj(e.change)??e.color?.background??Fe.get(e.community)}}),f.jsxs("span",{children:[f.jsx("strong",{children:e.label}),f.jsx("small",{children:e.kind??"Symbol"})]}),$v(e.change)&&f.jsx("span",{className:"compass-change-badge","data-change":e.change,children:$v(e.change)})]}),f.jsxs("dl",{className:"compass-metadata-grid",children:[f.jsxs("div",{children:[f.jsx("dt",{children:"Community"}),f.jsx("dd",{children:e.communityName??n.communities.find(E=>E.id===e.community)?.label??e.community})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Degree"}),f.jsx("dd",{children:e.degree??t.length})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Incoming"}),f.jsx("dd",{children:Ge.incoming.length})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Outgoing"}),f.jsx("dd",{children:Ge.outgoing.length})]}),e.language&&f.jsxs("div",{children:[f.jsx("dt",{children:"Language"}),f.jsx("dd",{children:e.language})]}),U&&f.jsxs("div",{children:[f.jsx("dt",{children:"Lines"}),f.jsx("dd",{children:U})]}),f.jsx("div",{className:"compass-metadata-wide compass-source-metadata","data-interactive":V!==void 0,children:V?f.jsxs(f.Fragment,{children:[f.jsx("dt",{className:"sr-only",children:"Source"}),f.jsx("dd",{children:f.jsxs("button",{className:"compass-source-card",type:"button","aria-label":Xv(e,V),title:Xv(e,V),onClick:()=>x(V,e.change==="removed"?l?.before:l?.after),children:[f.jsxs("span",{className:"compass-source-copy",children:[f.jsx("span",{className:"compass-source-eyebrow","aria-hidden":"true",children:"Source"}),f.jsx("span",{className:"compass-source-path",children:V.file}),Ce&&f.jsx("span",{className:"compass-source-range",children:Ce.text})]}),f.jsx(gC,{"aria-hidden":"true"})]})})]}):f.jsxs(f.Fragment,{children:[f.jsx("dt",{children:"Source"}),f.jsx("dd",{title:e.source?.file??"Not recorded",children:e.source?.file??"Not recorded"})]})})]}),e.signature&&f.jsx("code",{className:"compass-signature-block",children:e.signature}),M&&f.jsx(J_,{context:M,selectedId:e.id,onFocus:v}),y&&f.jsxs("section",{className:"compass-node-actions","aria-labelledby":"compass-node-actions-title",children:[f.jsxs("div",{className:"compass-inspector-subheading",children:[f.jsx("h3",{id:"compass-node-actions-title",children:"Actions"}),f.jsx("span",{children:"3 available"})]}),f.jsxs("div",{className:"compass-code-query-actions","aria-label":"Code graph queries",children:[f.jsxs("button",{type:"button",title:"Find code that calls this node",onClick:()=>y("callers",e.id),children:[f.jsx(Cv,{"aria-hidden":"true"}),f.jsx("span",{children:"Callers"})]}),f.jsxs("button",{type:"button",title:"Find code called by this node",onClick:()=>y("callees",e.id),children:[f.jsx(Iv,{"aria-hidden":"true"}),f.jsx("span",{children:"Callees"})]}),f.jsxs("button",{type:"button",title:"Trace code affected by this node",onClick:()=>y("impact",e.id),children:[f.jsx(D_,{"aria-hidden":"true"}),f.jsx("span",{children:"Impact"})]})]})]}),f.jsx(jv,{evidence:W,diagnostics:c?.diagnostics,truncated:c?.truncated,title:"Node evidence",onOpenSource:x}),f.jsx(jv,{evidence:oe,title:"Relationship evidence",onOpenSource:x}),n.stats.aggregated&&e.memberCount!==void 0&&e.detailAvailable!==!1&&O&&f.jsxs("button",{className:"compass-inspector-action",type:"button",onClick:()=>O(e.community),children:[f.jsx("span",{className:"compass-inspector-action-icon","aria-hidden":"true",children:f.jsx(A_,{})}),f.jsxs("span",{className:"compass-inspector-action-copy",children:[f.jsx("strong",{children:I?"Inspect changes":"Open community"}),f.jsxs("small",{children:[e.memberCount.toLocaleString()," ",I?"current symbols":"members"]})]}),f.jsx(pc,{"aria-hidden":"true"})]}),n.stats.aggregated&&e.memberCount!==void 0&&e.detailAvailable===!1&&f.jsx("p",{className:"compass-empty",children:"This community detail was omitted to keep the standalone HTML export bounded. Open the graph in VS Code or export this community as JSON for full inspection."}),I?f.jsx(Y_,{node:e,edges:i,nodes:ye,sourceRevisions:l,onFocus:v,onOpenSource:x}):f.jsxs("section",{className:"compass-relationships","aria-labelledby":"compass-relationships-title",children:[f.jsxs("div",{className:"compass-inspector-subheading",children:[f.jsx("h3",{id:"compass-relationships-title",children:"Relationships"}),f.jsxs("span",{children:[i.length," ",i.length===1?"edge":"edges"]})]}),f.jsxs("div",{className:"compass-relationship-directions",children:[f.jsx(Wv,{direction:"incoming",groups:Ge.incoming,communityColors:Fe,onFocus:v}),f.jsx(Wv,{direction:"outgoing",groups:Ge.outgoing,communityColors:Fe,onFocus:v})]})]})]}):f.jsx("p",{className:"compass-empty",children:"Select a node to inspect its relationships."})]}),I&&!n.stats.aggregated&&f.jsx(K_,{nodes:n.nodes,query:o,selectedId:e?.id,onFocus:v}),n.effectiveGraph&&f.jsxs("section",{className:"compass-info-panel","aria-labelledby":"compass-agent-overlay-title",children:[f.jsxs("div",{className:"compass-section-heading",children:[f.jsx("h2",{id:"compass-agent-overlay-title",children:"Agent overlay"}),f.jsx("span",{children:"Exact revision"})]}),f.jsxs("dl",{className:"compass-metadata-grid",children:[f.jsxs("div",{children:[f.jsx("dt",{children:"Pinned profile"}),f.jsx("dd",{children:n.effectiveGraph.compositionProfile})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Retractions"}),f.jsx("dd",{children:n.effectiveGraph.retractions.total.toLocaleString()})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Omissions"}),f.jsx("dd",{children:n.effectiveGraph.omissions.total.toLocaleString()})]}),f.jsxs("div",{className:"compass-metadata-wide",children:[f.jsx("dt",{children:"Overlay revision"}),f.jsx("dd",{title:n.effectiveGraph.overlayRevision,children:f.jsx("code",{children:n.effectiveGraph.overlayRevision.slice(0,12)})})]})]}),n.effectiveGraph.retractions.examples.length>0&&f.jsxs("details",{children:[f.jsxs("summary",{children:["Retraction history",f.jsx("span",{children:n.effectiveGraph.retractions.examples.length})]}),f.jsx("ul",{children:n.effectiveGraph.retractions.examples.map(E=>f.jsxs("li",{children:[f.jsx("strong",{children:E.kind})," ",f.jsx("code",{children:E.id})," — ",E.reasonCode,": ",E.explanation]},`${E.kind}:${E.id}`))}),n.effectiveGraph.retractions.omittedExamples>0&&f.jsxs("p",{className:"compass-empty",children:[n.effectiveGraph.retractions.omittedExamples.toLocaleString()," additional Retractions omitted by the response bound."]})]}),f.jsx("p",{className:"compass-empty",children:"Changing augment or curated profile requires a new exact Effective Graph read; this viewer never relabels one identity as another."})]}),f.jsx("section",{className:"compass-community-panel","aria-labelledby":"compass-communities-title","data-secondary":I,children:I?f.jsxs("details",{children:[f.jsxs("summary",{id:"compass-communities-title",children:["Communities",f.jsx("span",{children:n.communities.length})]}),f.jsx(qv,{model:n,communityCounts:Te,hiddenCommunities:A,allVisible:Ze,onSetAllVisible:S,onToggleCommunity:T})]}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{id:"compass-communities-title",children:"Communities"}),f.jsx(qv,{model:n,communityCounts:Te,hiddenCommunities:A,allVisible:Ze,onSetAllVisible:S,onToggleCommunity:T})]})}),f.jsxs("footer",{className:"compass-graph-stats",children:[n.stats.nodes.toLocaleString()," nodes · ",n.stats.edges.toLocaleString()," edges",huj(n.communities,A),[n.communities,A]),c=P.useMemo(()=>{const h=A.trim().toLocaleLowerCase();return h?n.communities.filter(p=>p.label.toLocaleLowerCase().includes(h)||String(p.id).includes(h)).length:n.communities.length},[n.communities,A]);return f.jsxs("div",{className:"compass-community-controls",children:[f.jsxs("label",{className:"compass-community-control",children:[f.jsx("input",{type:"checkbox",checked:i,onChange:h=>o(h.target.checked)}),f.jsx("span",{children:"Select all"})]}),n.communities.length>Kv&&f.jsxs("label",{className:"compass-community-search",children:[f.jsx("span",{className:"sr-only",children:"Filter communities"}),f.jsx(xv,{"aria-hidden":"true"}),f.jsx("input",{type:"search",value:A,placeholder:"Filter communities",onChange:h=>I(h.target.value)})]}),f.jsx("div",{className:"compass-community-list",children:l.map(h=>{const p=!t.has(h.id);return f.jsxs("label",{className:"compass-community-item","data-hidden":!p,children:[f.jsx("input",{type:"checkbox",checked:p,onChange:()=>r(h.id)}),f.jsx("span",{className:"compass-community-dot","aria-hidden":"true",style:{background:h.color}}),f.jsx("span",{className:"compass-community-label",children:h.label}),f.jsx("small",{children:e.get(h.id)??0})]},h.id)})}),c>l.length&&f.jsxs("p",{className:"compass-community-limit",role:"status",children:["Showing ",l.length.toLocaleString()," of"," ",c.toLocaleString()," communities. Filter to find another community."]})]})}function mj({className:n="compass-load-logo"}){return f.jsx("svg",{className:n,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:f.jsx("path",{fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd",d:"M3.554 21.529c1.797 1.221 4.943-.038 11.236-2.554 1.342-.537 2.013-.806 2.54-1.267q.201-.177.378-.378c.461-.527.73-1.198 1.267-2.54 2.515-6.293 3.775-9.44 2.554-11.236a4.1 4.1 0 0 0-1.083-1.083c-1.797-1.221-4.944.037-11.236 2.554-1.342.537-2.013.806-2.54 1.267q-.201.177-.378.378c-.461.527-.73 1.198-1.267 2.54-2.517 6.292-3.775 9.439-2.554 11.236.29.426.657.793 1.083 1.083M8.25 12a3.75 3.75 0 1 1 7.5 0 3.75 3.75 0 0 1-7.5 0m1.5 0a2.25 2.25 0 1 1 4.5 0 2.25 2.25 0 0 1-4.5 0"})})}const vj=1e4;function Jv(n){const[e,t]=P.useState(!1);P.useEffect(()=>{if(n.kind!=="layout"){t(!1);return}const A=window.setTimeout(()=>{t(!0)},vj);return()=>window.clearTimeout(A)},[n.kind]);const i=n.kind==="community",o=i?`Opening ${n.communityLabel}`:e?"Still arranging this graph":"Arranging graph layout",r=i?"Fetching symbols and relationships for this community.":e?"This graph is taking longer than expected. You can open the current layout now.":"Positioning nodes and relationships for a readable first view.";return f.jsxs("section",{className:"compass-graph-transition","data-kind":n.kind,role:"status","aria-live":"polite","aria-atomic":"true",children:[f.jsxs("div",{className:"compass-load-visual","data-state":"loading","aria-hidden":"true",children:[f.jsx("span",{className:"compass-load-mark",children:f.jsx(mj,{})}),f.jsx("span",{className:"compass-load-progress",children:f.jsx("i",{})})]}),f.jsxs("div",{className:"compass-load-copy",children:[f.jsx("span",{className:"compass-load-eyebrow",children:"Compass graph"}),f.jsx("h1",{children:o}),f.jsx("p",{className:"compass-graph-transition-description",children:r}),!i&&e&&f.jsx("div",{className:"compass-load-actions",children:f.jsx("button",{className:"compass-load-action compass-load-action-primary",type:"button",onClick:n.onShowGraph,children:"Show graph now"})})]})]})}function bj(n){return n instanceof HTMLElement&&(n.isContentEditable||n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.tagName==="SELECT")}function yj({status:n,physicsRunning:e,layoutStyle:t,forceLabels:i,showEdgeLabels:o,hasSelection:r,isolateSelection:A,neighborhoodDepth:I,edgeDirection:l,layoutSpacing:c,showMinimap:h,leadingControls:p,leadingPanel:m,leadingPanelOpen:v,onLeadingPanelClose:x,onTogglePhysics:O,onLayoutChange:y,onZoomOut:T,onResetZoom:S,onZoomIn:_,onFit:B,onFitSelection:Q,onReset:te,onToggleLabels:V,onToggleEdgeLabels:U,onToggleIsolation:Ce,onNeighborhoodDepthChange:Te,onEdgeDirectionChange:Ze,onLayoutSpacingChange:ye,onToggleMinimap:Fe,onBack:Ge}){const[le,M]=P.useState(!1),W=P.useId(),oe=P.useRef(null),se=P.useRef(null),J=P.useRef(!1);return P.useEffect(()=>{v&&M(!1)},[v]),P.useEffect(()=>{le||!J.current||(J.current=!1,se.current?.focus())},[le]),P.useEffect(()=>{const E=ne=>{if(ne.key==="Escape"){le&&(J.current=!0,M(!1));return}ne.key!=="?"||bj(ne.target)||(ne.preventDefault(),x?.(),M(!0))},G=ne=>{oe.current?.contains(ne.target)||M(!1)};return document.addEventListener("keydown",E),document.addEventListener("pointerdown",G),()=>{document.removeEventListener("keydown",E),document.removeEventListener("pointerdown",G)}},[x,le]),f.jsxs("div",{ref:oe,className:"compass-graph-toolbar compass-glass-panel",role:"toolbar","aria-label":"Graph controls",children:[f.jsxs("div",{className:"compass-viewer-status","data-state":e?"running":"paused",role:"status","aria-live":"polite",children:[f.jsx("span",{className:"compass-viewer-status-dot","aria-hidden":"true"}),f.jsx("span",{className:"compass-viewer-status-text",children:n})]}),f.jsxs("div",{className:"compass-toolbar-actions",children:[Ge&&f.jsxs("button",{className:"compass-tool-button",type:"button","aria-label":"Back to community overview",onClick:Ge,children:[f.jsx(o_,{}),f.jsx("span",{children:"Overview"})]}),f.jsxs("label",{className:"compass-layout-picker",children:[f.jsx(b_,{"aria-hidden":"true"}),f.jsx("span",{className:"sr-only",children:"Graph layout"}),f.jsxs("select",{"aria-label":"Graph layout",value:t,onChange:E=>y(E.target.value),children:[f.jsx("option",{value:"automatic",children:"Automatic"}),f.jsx("option",{value:"circle",children:"Circle"}),f.jsx("option",{value:"concentric",children:"Concentric"}),f.jsx("option",{value:"spiral",children:"Spiral"}),f.jsx("option",{value:"grid",children:"Square grid"})]})]}),f.jsxs("button",{className:"compass-tool-button compass-physics-button",type:"button","aria-label":e?"Stop layout":t==="automatic"?"Run layout":"Fixed layout","aria-pressed":e,disabled:t!=="automatic",title:t==="automatic"?e?"Stop layout":"Run layout":"Physics is available in Automatic layout",onClick:O,children:[e?f.jsx(pv,{}):t==="automatic"?f.jsx(N_,{}):f.jsx(pv,{}),f.jsx("span",{children:e?"Stop":t==="automatic"?"Layout":"Fixed"})]}),f.jsx("span",{className:"compass-toolbar-separator","aria-hidden":"true"}),f.jsxs("div",{className:"compass-zoom-controls",role:"group","aria-label":"Zoom controls",children:[f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Zoom out",title:"Zoom out",onClick:T,children:f.jsx(L_,{})}),f.jsx("button",{className:"compass-tool-button compass-zoom-reset",type:"button","aria-label":"Reset zoom to 100%",title:"Reset zoom to 100%",onClick:S,children:"100%"}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Zoom in",title:"Zoom in",onClick:_,children:f.jsx(Z_,{})})]}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Fit graph in view",title:"Fit graph in view",onClick:B,children:f.jsx(hv,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Fit selected neighborhood",title:r?`Fit the selected node and its ${I}-hop neighborhood`:"Select a node to fit its neighborhood",disabled:!r,onClick:Q,children:f.jsx(m_,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Reset graph view",title:"Reset graph view",onClick:te,children:f.jsx(vv,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":i?"Hide labels":"Show labels","aria-pressed":i,title:i?"Hide node labels":"Show all node labels",onClick:V,children:f.jsx(P_,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":o?"Hide relationship labels":"Show relationship labels","aria-pressed":o,title:o?"Hide relationship labels":"Show relationship labels",onClick:U,children:f.jsx(bv,{})}),f.jsx("button",{ref:se,className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Graph settings","aria-expanded":le,"aria-controls":W,title:"Graph settings (?)",onClick:()=>M(E=>{const G=!E;return G&&x?.(),G}),children:f.jsx(M_,{})}),p?f.jsx("div",{className:"compass-toolbar-leading",children:p}):null]}),m,le?f.jsxs("div",{id:W,className:"compass-explore-panel compass-glass-panel",role:"region","aria-label":"Graph exploration controls",children:[f.jsxs("div",{className:"compass-explore-heading",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Graph settings"}),f.jsx("span",{children:r?"Tune the selected neighborhood and canvas":"Set the next neighborhood, then select a node"})]}),f.jsx("kbd",{children:"?"})]}),r?null:f.jsxs("div",{className:"compass-selection-prompt",role:"note",children:[f.jsx(yv,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Select a node to isolate it"}),f.jsx("small",{children:"Use the canvas or node search. Depth and direction can be set now."})]})]}),f.jsxs("button",{className:"compass-explore-toggle",type:"button","aria-label":"Isolate selection","aria-pressed":A,disabled:!r,onClick:Ce,children:[f.jsx(yv,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Isolate selection"}),f.jsx("small",{children:"Hide everything outside the traversal"})]}),f.jsx("i",{"aria-hidden":"true"})]}),f.jsxs("fieldset",{className:"compass-explore-field",children:[f.jsx("legend",{children:"Neighborhood depth"}),f.jsx("div",{className:"compass-segmented-control","aria-label":"Neighborhood depth",children:[1,2,3,4].map(E=>f.jsx("button",{type:"button","aria-label":`${E} hop${E===1?"":"s"}`,"aria-pressed":I===E,onClick:()=>Te(E),children:E},E))})]}),f.jsxs("fieldset",{className:"compass-explore-field",children:[f.jsx("legend",{children:"Edge direction"}),f.jsx("div",{className:"compass-segmented-control","aria-label":"Edge direction",children:[["both","Both"],["outgoing","Out"],["incoming","In"]].map(([E,G])=>f.jsx("button",{type:"button","aria-label":`${G==="Both"?"Both directions":G==="Out"?"Outgoing edges":"Incoming edges"}`,"aria-pressed":l===E,onClick:()=>Ze(E),children:G},E))})]}),f.jsxs("label",{className:"compass-explore-select",children:[f.jsx("span",{children:"Layout spacing"}),f.jsxs("select",{"aria-label":"Layout spacing",value:c,onChange:E=>ye(Number(E.target.value)),children:[f.jsx("option",{value:.75,children:"Compact · 75%"}),f.jsx("option",{value:1,children:"Default · 100%"}),f.jsx("option",{value:1.25,children:"Airy · 125%"}),f.jsx("option",{value:1.5,children:"Wide · 150%"})]})]}),f.jsxs("button",{className:"compass-explore-toggle",type:"button","aria-label":"Show minimap","aria-pressed":h,onClick:Fe,children:[f.jsx(w_,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Show minimap"}),f.jsx("small",{children:"Track and reposition the visible viewport"})]}),f.jsx("i",{"aria-hidden":"true"})]}),f.jsxs("div",{className:"compass-shortcut-guide","aria-label":"Graph keyboard shortcuts",children:[f.jsxs("div",{className:"compass-shortcut-title",children:[f.jsx(v_,{"aria-hidden":"true"}),f.jsx("strong",{children:"Keyboard"})]}),f.jsxs("dl",{children:[f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"F"})}),f.jsx("dd",{children:"Fit graph"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"⇧ F"})}),f.jsx("dd",{children:"Fit selection"})]}),f.jsxs("div",{children:[f.jsxs("dt",{children:[f.jsx("kbd",{children:"+"})," ",f.jsx("kbd",{children:"−"})]}),f.jsx("dd",{children:"Zoom"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"0"})}),f.jsx("dd",{children:"100% zoom"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"I"})}),f.jsx("dd",{children:"Isolate"})]}),f.jsxs("div",{children:[f.jsxs("dt",{children:[f.jsx("kbd",{children:"["})," ",f.jsx("kbd",{children:"]"})]}),f.jsx("dd",{children:"Depth"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"D"})}),f.jsx("dd",{children:"Direction"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"M"})}),f.jsx("dd",{children:"Minimap"})]})]})]})]}):null]})}const wj=["callable","type","module","boundary","other"],xj=["execution","dependency","structure","flow","other"],Sj=new Set(["closure","constructor","function","lambda","macro","method","procedure","subroutine","database_procedure"]),Ej=new Set(["class","component","enum","interface","annotation","protocol","struct","trait","type","type_alias","union"]),Tj=new Set(["directory","document","export","file","folder","import","migration","module","namespace","package"]),Oj=new Set(["command","config_key","database","database_column","database_constraint","database_index","database_schema","database_table","database_trigger","database_view","endpoint","event","job","message","query","queue","resource","route","schema","table","topic"]),Nj=new Set(["awaits","calls","dispatches","executes","handles","instantiates","invokes","schedules","tests","triggers","spawns"]),Dj=new Set(["depends_on","exports","imports","imports_from","links","re_exports","references","returns","type_of","aliases","uses"]),kj=new Set(["contains","decorates","declares","documents","embeds","extends","implements","inherits","member_of","mixes_in","overrides","renders","owns"]),Mj=new Set(["consumes","emits","maps_to","produces","publishes","reads","receives","registers","routes_to","sends","subscribes","writes"]);function eb(n){return(n??"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function ps(n){const e=eb(n);return Sj.has(e)?"callable":Ej.has(e)?"type":Tj.has(e)?"module":Oj.has(e)?"boundary":"other"}function Sc(n){const e=eb(n);return Nj.has(e)?"execution":Dj.has(e)?"dependency":kj.has(e)?"structure":Mj.has(e)?"flow":"other"}function Rj(n){return n==="type"?"diamond":n==="module"?"square":n==="boundary"?"triangle":"dot"}function zj(n){return n==="callable"?"var(--vscode-symbolIcon-functionForeground, #5fa8ff)":n==="type"?"var(--vscode-symbolIcon-classForeground, #e3b341)":n==="module"?"var(--vscode-symbolIcon-moduleForeground, #56d4b4)":n==="boundary"?"var(--vscode-symbolIcon-eventForeground, #ff9b87)":"var(--vscode-descriptionForeground, #8b949e)"}const _j={callable:"Callable",type:"Type",module:"Module / file",boundary:"Boundary / data",other:"Other"},jj={execution:"Execution",dependency:"Dependency",structure:"Structure",flow:"Data / event flow",other:"Other"};function Pj({model:n}){const e=P.useMemo(()=>{const i=new Map;for(const o of n.nodes){const r=ps(o.kind);i.set(r,(i.get(r)??0)+1)}return i},[n.nodes]),t=P.useMemo(()=>{const i=new Map;for(const o of n.edges){const r=Sc(o.relation);i.set(r,(i.get(r)??0)+1)}return i},[n.edges]);return f.jsxs("aside",{className:"compass-semantic-legend compass-glass-panel","aria-label":"Graph visual legend",children:[f.jsxs("section",{"aria-label":"Node categories",children:[f.jsx("strong",{children:"Nodes"}),wj.filter(i=>(e.get(i)??0)>0).map(i=>f.jsxs("span",{className:"compass-semantic-legend-item",children:[f.jsx("i",{"data-node-category":i,"aria-hidden":"true"}),_j[i],f.jsx("small",{children:e.get(i)})]},i))]}),n.edges.length>0?f.jsxs("section",{"aria-label":"Relationship categories",children:[f.jsx("strong",{children:"Edges"}),xj.filter(i=>(t.get(i)??0)>0).map(i=>f.jsxs("span",{className:"compass-semantic-legend-item",children:[f.jsx("i",{"data-edge-category":i,"aria-hidden":"true"}),jj[i],f.jsx("small",{children:t.get(i)})]},i))]}):null]})}const tb=280,nb=560,ib=24,Ec={width:340,collapsed:!1};function Kr(n){return Number.isFinite(n)?Math.min(nb,Math.max(tb,Math.round(n))):Ec.width}function gb(n){return{width:Kr(n?.width??Ec.width),collapsed:n?.collapsed??Ec.collapsed}}function Bj(n,e){return Kr(n-e)}function Zj(n,e){return Kr(e==="ArrowLeft"?n+ib:e==="ArrowRight"?n-ib:n)}function Lj({width:n,onResize:e}){const t=P.useRef(!1),i=o=>{t.current=!1,o.currentTarget.hasPointerCapture(o.pointerId)&&o.currentTarget.releasePointerCapture(o.pointerId)};return f.jsx("div",{className:"compass-inspector-resizer",role:"separator","aria-label":"Resize graph inspector","aria-orientation":"vertical","aria-valuemin":tb,"aria-valuemax":nb,"aria-valuenow":n,tabIndex:0,onPointerDown:o=>{t.current=!0,o.currentTarget.setPointerCapture(o.pointerId)},onPointerMove:o=>{if(!t.current)return;const r=o.currentTarget.parentElement;r&&e(Bj(r.getBoundingClientRect().right,o.clientX))},onPointerUp:i,onPointerCancel:i,onKeyDown:o=>{o.key!=="ArrowLeft"&&o.key!=="ArrowRight"||(o.preventDefault(),e(Zj(n,o.key)))},children:f.jsx("span",{"aria-hidden":"true"})})}function ob(n,e,t){if(t===void 0&&n.stats.aggregated&&e.memberCount!==void 0&&e.detailAvailable!==!1)return{type:"community",communityId:e.community};const i=Uv(e);return i?{type:"source",source:i}:{type:"none"}}function Gj(n){const e=n.source?.startLine,t=n.source?.endLine;if(e!==void 0)return t!==void 0&&t!==e?`${e}–${t}`:String(e)}function Fj({node:n,hover:e,activation:t}){const i={"--compass-hover-x":`${e.x+18}px`,"--compass-hover-y":`${e.y-42}px`},o=Gj(n);return f.jsxs("div",{className:"compass-node-hover-card",role:"tooltip",style:i,children:[f.jsxs("div",{className:"compass-hover-heading",children:[f.jsx("strong",{children:n.label}),f.jsx("span",{children:(n.kind??"symbol").toLocaleUpperCase()})]}),n.change&&f.jsx("span",{className:"compass-change-badge","data-change":n.change,children:n.change==="unchanged"?"Context":`${n.change[0]?.toLocaleUpperCase()}${n.change.slice(1)}`}),n.groundingStatus==="GROUNDED"&&f.jsx("span",{className:"compass-change-badge","data-grounding":"grounded",children:"GROUNDED · agent-authored"}),n.agentSummary&&f.jsx("p",{children:n.agentSummary}),n.challenge&&f.jsxs("p",{children:["Challenge (",n.challenge.effect,"): ",n.challenge.summary]}),n.challenged&&!n.challenge&&f.jsx("p",{children:"Challenge: this Base Graph fact is disputed."}),n.memberCount!==void 0?f.jsxs("p",{children:[n.memberCount.toLocaleString()," symbols"]}):f.jsxs(f.Fragment,{children:[n.language&&f.jsxs("p",{children:["Language: ",n.language]}),n.source?.file&&f.jsx("p",{className:"compass-hover-source",children:n.source.file}),o&&f.jsxs("p",{children:["Lines: ",o]}),n.signature&&f.jsx("code",{children:n.signature})]}),t.type!=="none"&&f.jsxs("p",{className:"compass-hover-hint",children:[t.type==="community"?f.jsx(vc,{"aria-hidden":"true"}):f.jsx(f_,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Double-click"})," ",t.type==="community"?"to open community subgraph":"to open source code"]})]})]})}const Vj={routes_to:"routes to",publishes:"publishes",subscribes:"subscribes",produces:"produces",consumes:"consumes",schedules:"schedules",triggers:"triggers",handles:"handles",registers:"registers",reads:"reads",writes:"writes",maps_to:"maps to",depends_on:"depends on",renders:"renders"};function Uj(n){const e=n.relation.trim(),t=Vj[e]??e,i=n.details?.type==="route"?n.details.data:void 0,o=i?`${i.stage}${i.position===null||i.position===void 0?"":` ${i.position+1}`}`:void 0;return[t,o,i?.operation].filter(r=>r!==void 0&&r!=="").join(" · ")}function Yj(n){if(!n?.file.trim())return"";const e=n.startLine,t=n.endLine;if(e!==void 0){const i=t!==void 0&&t!==e?`${e}–${t}`:String(e);return`${n.file}:${i}`}return n.startByte!==void 0?`${n.file}:byte ${n.startByte}`:n.file}function Hj(n){const e=n.confidence;return e?`${e[0]?.toLocaleUpperCase()}${e.slice(1)}`:"Unspecified"}function Kj(n){if(n)return n==="unchanged"?"Context":`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`}function Wj({edge:n,sourceNode:e,targetNode:t,hover:i}){const o={"--compass-hover-x":`${i.x+18}px`,"--compass-hover-y":`${i.y-52}px`},r=Yj(n.relationshipSite),A=n.codeEvidence?.[0],I=Kj(n.change),l=Yv(n)!==void 0;return f.jsxs("div",{className:"compass-edge-hover-card",role:"tooltip",style:o,children:[f.jsxs("div",{className:"compass-edge-hover-heading",children:[f.jsxs("span",{className:"compass-edge-hover-eyebrow",children:[f.jsx(dv,{"aria-hidden":"true"}),"Relationship"]}),f.jsx("span",{className:"compass-edge-confidence","data-confidence":n.confidence??"unspecified",children:Hj(n)})]}),f.jsxs("div",{className:"compass-edge-trace","aria-label":`${e.label} to ${t.label}`,children:[f.jsx("strong",{children:e.label}),f.jsx("span",{"aria-hidden":"true",children:f.jsx(s_,{})}),f.jsx("strong",{children:t.label})]}),f.jsxs("div",{className:"compass-edge-relation-row",children:[f.jsx("strong",{children:Uj(n)||"Relationship"}),I&&f.jsx("span",{className:"compass-change-badge","data-change":n.change,children:I}),n.groundingStatus==="GROUNDED"&&f.jsx("span",{className:"compass-change-badge","data-grounding":"grounded",children:"GROUNDED · agent-authored"})]}),n.agentSummary&&f.jsx("p",{children:n.agentSummary}),n.challenge&&f.jsxs("p",{children:["Challenge (",n.challenge.effect,"): ",n.challenge.summary]}),n.challenged&&!n.challenge&&f.jsx("p",{children:"Challenge: this Base Graph relationship is disputed."}),(A||r)&&f.jsxs("div",{className:"compass-edge-metadata",children:[A&&f.jsxs("p",{children:[f.jsx("span",{children:"Evidence"}),f.jsx("code",{children:A.rule??A.origin})]}),r&&f.jsxs("p",{children:[f.jsx("span",{children:"Source"}),f.jsx("code",{children:r})]})]}),l&&f.jsxs("p",{className:"compass-hover-hint",children:[f.jsx(dv,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Double-click"})," to open relationship source"]})]})]})}var Tc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ke(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var CC=function(n){return n&&n.Math===Math&&n},Pt=CC(typeof globalThis=="object"&&globalThis)||CC(typeof window=="object"&&window)||CC(typeof self=="object"&&self)||CC(typeof Tc=="object"&&Tc)||(function(){return this})()||Tc||Function("return this")(),rt=function(n){try{return!!n()}catch{return!0}},Qj=rt,Wr=!Qj(function(){var n=(function(){}).bind();return typeof n!="function"||n.hasOwnProperty("prototype")}),Xj=Wr,sb=Function.prototype,rb=sb.apply,ab=sb.call,IC=typeof Reflect=="object"&&Reflect.apply||(Xj?ab.bind(rb):function(){return ab.apply(rb,arguments)}),Ab=Wr,Cb=Function.prototype,Oc=Cb.call,$j=Ab&&Cb.bind.bind(Oc,Oc),at=Ab?$j:function(n){return function(){return Oc.apply(n,arguments)}},Ib=at,qj=Ib({}.toString),Jj=Ib("".slice),qi=function(n){return Jj(qj(n),8,-1)},e5=qi,t5=at,Nc=function(n){if(e5(n)==="Function")return t5(n)},Dc=typeof document=="object"&&document.all,n5=typeof Dc>"u"&&Dc!==void 0,lb={all:Dc,IS_HTMLDDA:n5},cb=lb,i5=cb.all,fn=cb.IS_HTMLDDA?function(n){return typeof n=="function"||n===i5}:function(n){return typeof n=="function"},Qr={},g5=rt,rn=!g5(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),o5=Wr,lC=Function.prototype.call,bi=o5?lC.bind(lC):function(){return lC.apply(lC,arguments)},Xr={},db={}.propertyIsEnumerable,ub=Object.getOwnPropertyDescriptor,s5=ub&&!db.call({1:2},1);Xr.f=s5?function(e){var t=ub(this,e);return!!t&&t.enumerable}:db;var $r=function(n,e){return{enumerable:!(n&1),configurable:!(n&2),writable:!(n&4),value:e}},r5=at,a5=rt,A5=qi,kc=Object,C5=r5("".split),cC=a5(function(){return!kc("z").propertyIsEnumerable(0)})?function(n){return A5(n)==="String"?C5(n,""):kc(n)}:kc,ms=function(n){return n==null},I5=ms,l5=TypeError,qr=function(n){if(I5(n))throw new l5("Can't call method on "+n);return n},c5=cC,d5=qr,yi=function(n){return c5(d5(n))},hb=fn,fb=lb,u5=fb.all,Tn=fb.IS_HTMLDDA?function(n){return typeof n=="object"?n!==null:hb(n)||n===u5}:function(n){return typeof n=="object"?n!==null:hb(n)},Ct={},Mc=Ct,Rc=Pt,h5=fn,pb=function(n){return h5(n)?n:void 0},wi=function(n,e){return arguments.length<2?pb(Mc[n])||pb(Rc[n]):Mc[n]&&Mc[n][e]||Rc[n]&&Rc[n][e]},f5=at,Bt=f5({}.isPrototypeOf),Jr=typeof navigator<"u"&&String(navigator.userAgent)||"",mb=Pt,zc=Jr,vb=mb.process,bb=mb.Deno,yb=vb&&vb.versions||bb&&bb.version,wb=yb&&yb.v8,xi,dC;wb&&(xi=wb.split("."),dC=xi[0]>0&&xi[0]<4?1:+(xi[0]+xi[1])),!dC&&zc&&(xi=zc.match(/Edge\/(\d+)/),(!xi||xi[1]>=74)&&(xi=zc.match(/Chrome\/(\d+)/),xi&&(dC=+xi[1])));var ea=dC,xb=ea,p5=rt,m5=Pt,v5=m5.String,vs=!!Object.getOwnPropertySymbols&&!p5(function(){var n=Symbol("symbol detection");return!v5(n)||!(Object(n)instanceof Symbol)||!Symbol.sham&&xb&&xb<41}),b5=vs,Sb=b5&&!Symbol.sham&&typeof Symbol.iterator=="symbol",y5=wi,w5=fn,x5=Bt,S5=Sb,E5=Object,ta=S5?function(n){return typeof n=="symbol"}:function(n){var e=y5("Symbol");return w5(e)&&x5(e.prototype,E5(n))},T5=String,na=function(n){try{return T5(n)}catch{return"Object"}},O5=fn,N5=na,D5=TypeError,wo=function(n){if(O5(n))return n;throw new D5(N5(n)+" is not a function")},k5=wo,M5=ms,_c=function(n,e){var t=n[e];return M5(t)?void 0:k5(t)},jc=bi,Pc=fn,Bc=Tn,R5=TypeError,z5=function(n,e){var t,i;if(e==="string"&&Pc(t=n.toString)&&!Bc(i=jc(t,n))||Pc(t=n.valueOf)&&!Bc(i=jc(t,n))||e!=="string"&&Pc(t=n.toString)&&!Bc(i=jc(t,n)))return i;throw new R5("Can't convert object to primitive value")},Eb={exports:{}},Tb=Pt,_5=Object.defineProperty,j5=function(n,e){try{_5(Tb,n,{value:e,configurable:!0,writable:!0})}catch{Tb[n]=e}return e},P5=Pt,B5=j5,Ob="__core-js_shared__",Z5=P5[Ob]||B5(Ob,{}),Zc=Z5,Nb=Zc;(Eb.exports=function(n,e){return Nb[n]||(Nb[n]=e!==void 0?e:{})})("versions",[]).push({version:"3.33.0",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.33.0/LICENSE",source:"https://github.com/zloirock/core-js"});var bs=Eb.exports,L5=qr,G5=Object,Kn=function(n){return G5(L5(n))},F5=at,V5=Kn,U5=F5({}.hasOwnProperty),an=Object.hasOwn||function(e,t){return U5(V5(e),t)},Y5=at,H5=0,K5=Math.random(),W5=Y5(1 .toString),uC=function(n){return"Symbol("+(n===void 0?"":n)+")_"+W5(++H5+K5,36)},Q5=Pt,X5=bs,Db=an,$5=uC,q5=vs,J5=Sb,ys=Q5.Symbol,Lc=X5("wks"),e4=J5?ys.for||ys:ys&&ys.withoutSetter||$5,Yt=function(n){return Db(Lc,n)||(Lc[n]=q5&&Db(ys,n)?ys[n]:e4("Symbol."+n)),Lc[n]},t4=bi,kb=Tn,Mb=ta,n4=_c,i4=z5,g4=Yt,o4=TypeError,s4=g4("toPrimitive"),r4=function(n,e){if(!kb(n)||Mb(n))return n;var t=n4(n,s4),i;if(t){if(e===void 0&&(e="default"),i=t4(t,n,e),!kb(i)||Mb(i))return i;throw new o4("Can't convert object to primitive value")}return e===void 0&&(e="number"),i4(n,e)},a4=r4,A4=ta,hC=function(n){var e=a4(n,"string");return A4(e)?e:e+""},C4=Pt,Rb=Tn,Gc=C4.document,I4=Rb(Gc)&&Rb(Gc.createElement),zb=function(n){return I4?Gc.createElement(n):{}},l4=rn,c4=rt,d4=zb,_b=!l4&&!c4(function(){return Object.defineProperty(d4("div"),"a",{get:function(){return 7}}).a!==7}),u4=rn,h4=bi,f4=Xr,p4=$r,m4=yi,v4=hC,b4=an,y4=_b,jb=Object.getOwnPropertyDescriptor;Qr.f=u4?jb:function(e,t){if(e=m4(e),t=v4(t),y4)try{return jb(e,t)}catch{}if(b4(e,t))return p4(!h4(f4.f,e,t),e[t])};var w4=rt,x4=fn,S4=/#|\.prototype\./,ia=function(n,e){var t=T4[E4(n)];return t===N4?!0:t===O4?!1:x4(e)?w4(e):!!e},E4=ia.normalize=function(n){return String(n).replace(S4,".").toLowerCase()},T4=ia.data={},O4=ia.NATIVE="N",N4=ia.POLYFILL="P",D4=ia,Pb=Nc,k4=wo,M4=Wr,R4=Pb(Pb.bind),ga=function(n,e){return k4(n),e===void 0?n:M4?R4(n,e):function(){return n.apply(e,arguments)}},Wn={},z4=rn,_4=rt,Bb=z4&&_4(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),j4=Tn,P4=String,B4=TypeError,Ji=function(n){if(j4(n))return n;throw new B4(P4(n)+" is not an object")},Z4=rn,L4=_b,G4=Bb,fC=Ji,Zb=hC,F4=TypeError,Fc=Object.defineProperty,V4=Object.getOwnPropertyDescriptor,Vc="enumerable",Uc="configurable",Yc="writable";Wn.f=Z4?G4?function(e,t,i){if(fC(e),t=Zb(t),fC(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Yc in i&&!i[Yc]){var o=V4(e,t);o&&o[Yc]&&(e[t]=i.value,i={configurable:Uc in i?i[Uc]:o[Uc],enumerable:Vc in i?i[Vc]:o[Vc],writable:!1})}return Fc(e,t,i)}:Fc:function(e,t,i){if(fC(e),t=Zb(t),fC(i),L4)try{return Fc(e,t,i)}catch{}if("get"in i||"set"in i)throw new F4("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var U4=rn,Y4=Wn,H4=$r,ws=U4?function(n,e,t){return Y4.f(n,e,H4(1,t))}:function(n,e,t){return n[e]=t,n},pC=Pt,K4=IC,W4=Nc,Q4=fn,X4=Qr.f,$4=D4,xs=Ct,q4=ga,Ss=ws,Lb=an,J4=function(n){var e=function(t,i,o){if(this instanceof e){switch(arguments.length){case 0:return new n;case 1:return new n(t);case 2:return new n(t,i)}return new n(t,i,o)}return K4(n,this,arguments)};return e.prototype=n.prototype,e},je=function(n,e){var t=n.target,i=n.global,o=n.stat,r=n.proto,A=i?pC:o?pC[t]:(pC[t]||{}).prototype,I=i?xs:xs[t]||Ss(xs,t,{})[t],l=I.prototype,c,h,p,m,v,x,O,y,T;for(m in e)c=$4(i?m:t+(o?".":"#")+m,n.forced),h=!c&&A&&Lb(A,m),x=I[m],h&&(n.dontCallGetSet?(T=X4(A,m),O=T&&T.value):O=A[m]),v=h&&O?O:e[m],!(h&&typeof x==typeof v)&&(n.bind&&h?y=q4(v,pC):n.wrap&&h?y=J4(v):r&&Q4(v)?y=W4(v):y=v,(n.sham||v&&v.sham||x&&x.sham)&&Ss(y,"sham",!0),Ss(I,m,y),r&&(p=t+"Prototype",Lb(xs,p)||Ss(xs,p,{}),Ss(xs[p],m,v),n.real&&l&&(c||!l[m])&&Ss(l,m,v)))},eP=Math.ceil,tP=Math.floor,nP=Math.trunc||function(e){var t=+e;return(t>0?tP:eP)(t)},iP=nP,mC=function(n){var e=+n;return e!==e||e===0?0:iP(e)},gP=mC,oP=Math.max,sP=Math.min,oa=function(n,e){var t=gP(n);return t<0?oP(t+e,0):sP(t,e)},rP=mC,aP=Math.min,AP=function(n){return n>0?aP(rP(n),9007199254740991):0},CP=AP,oi=function(n){return CP(n.length)},IP=yi,lP=oa,cP=oi,Gb=function(n){return function(e,t,i){var o=IP(e),r=cP(o),A=lP(i,r),I;if(n&&t!==t){for(;r>A;)if(I=o[A++],I!==I)return!0}else for(;r>A;A++)if((n||A in o)&&o[A]===t)return n||A||0;return!n&&-1}},Hc={includes:Gb(!0),indexOf:Gb(!1)},sa={},dP=at,Kc=an,uP=yi,hP=Hc.indexOf,fP=sa,Fb=dP([].push),Vb=function(n,e){var t=uP(n),i=0,o=[],r;for(r in t)!Kc(fP,r)&&Kc(t,r)&&Fb(o,r);for(;e.length>i;)Kc(t,r=e[i++])&&(~hP(o,r)||Fb(o,r));return o},Wc=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],pP=Vb,mP=Wc,ra=Object.keys||function(e){return pP(e,mP)},aa={};aa.f=Object.getOwnPropertySymbols;var Ub=rn,vP=at,bP=bi,yP=rt,Qc=ra,wP=aa,xP=Xr,SP=Kn,EP=cC,Es=Object.assign,Yb=Object.defineProperty,TP=vP([].concat),OP=!Es||yP(function(){if(Ub&&Es({b:1},Es(Yb({},"a",{enumerable:!0,get:function(){Yb(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var n={},e={},t=Symbol("assign detection"),i="abcdefghijklmnopqrst";return n[t]=7,i.split("").forEach(function(o){e[o]=o}),Es({},n)[t]!==7||Qc(Es({},e)).join("")!==i})?function(e,t){for(var i=SP(e),o=arguments.length,r=1,A=wP.f,I=xP.f;o>r;)for(var l=EP(arguments[r++]),c=A?TP(Qc(l),A(l)):Qc(l),h=c.length,p=0,m;h>p;)m=c[p++],(!Ub||bP(I,l,m))&&(i[m]=l[m]);return i}:Es,NP=je,Hb=OP;NP({target:"Object",stat:!0,forced:Object.assign!==Hb},{assign:Hb});var DP=Ct,kP=DP.Object.assign,MP=kP,RP=MP,zP=RP,Ht=ke(zP),_P=at,vC=_P([].slice),Kb=at,jP=wo,PP=Tn,BP=an,Wb=vC,ZP=Wr,Qb=Function,LP=Kb([].concat),GP=Kb([].join),Xc={},FP=function(n,e,t){if(!BP(Xc,e)){for(var i=[],o=0;o=.1;)x=+r[p++%A],x>h&&(x=h),v=Math.sqrt(x*x/(1+c*c)),v=I<0?-v:v,e+=v,t+=c*v,m===!0?n.lineTo(e,t):n.moveTo(e,t),h-=x,m=!m}function oB(n,e,t,i){n.beginPath();const o=6,r=Math.PI*2/o;n.moveTo(e+i,t);for(let A=1;A1?t-1:0),o=1;o"u")){var i=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",t==="top"&&i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),o.styleSheet?o.styleSheet.cssText=n:o.appendChild(document.createTextNode(n))}}var rB=`.vis-overlay { +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const A of n.seen.entries()){const I=A[1];if(e===A[0]){r(A);continue}if(n.external){const c=n.external.registry.get(A[0])?.id;if(e!==A[0]&&c){r(A);continue}}if(n.metadataRegistry.get(A[0])?.id){r(A);continue}if(I.cycle){r(A);continue}if(I.count>1&&n.reused==="ref"){r(A);continue}}}function Dm(n,e){const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=I=>{const l=n.seen.get(I);if(l.ref===null)return;const c=l.def??l.schema,h={...c},p=l.ref;if(l.ref=null,p){i(p);const v=n.seen.get(p),x=v.schema;if(x.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(x)):Object.assign(c,x),Object.assign(c,h),I._zod.parent===p)for(const y in c)y==="$ref"||y==="allOf"||y in h||delete c[y];if(x.$ref&&v.def)for(const y in c)y==="$ref"||y==="allOf"||y in v.def&&JSON.stringify(c[y])===JSON.stringify(v.def[y])&&delete c[y]}const m=I._zod.parent;if(m&&m!==p){i(m);const v=n.seen.get(m);if(v?.schema.$ref&&(c.$ref=v.schema.$ref,v.def))for(const x in c)x==="$ref"||x==="allOf"||x in v.def&&JSON.stringify(c[x])===JSON.stringify(v.def[x])&&delete c[x]}n.override({zodSchema:I,jsonSchema:c,path:l.path??[]})};for(const I of[...n.seen.entries()].reverse())i(I[0]);const o={};if(n.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":n.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":n.target,n.external?.uri){const I=n.external.registry.get(e)?.id;if(!I)throw new Error("Schema is missing an `id` property");o.$id=n.external.uri(I)}Object.assign(o,t.def??t.schema);const r=n.metadataRegistry.get(e)?.id;r!==void 0&&o.id===r&&delete o.id;const A=n.external?.defs??{};for(const I of n.seen.entries()){const l=I[1];l.def&&l.defId&&(l.def.id===l.defId&&delete l.def.id,A[l.defId]=l.def)}n.external||Object.keys(A).length>0&&(n.target==="draft-2020-12"?o.$defs=A:o.definitions=A);try{const I=JSON.parse(JSON.stringify(o));return Object.defineProperty(I,"~standard",{value:{...e["~standard"],jsonSchema:{input:qA(e,"input",n.processors),output:qA(e,"output",n.processors)}},enumerable:!1,writable:!1}),I}catch{throw new Error("Error converting schema to JSON.")}}function Nn(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const i=n._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Nn(i.element,t);if(i.type==="set")return Nn(i.valueType,t);if(i.type==="lazy")return Nn(i.getter(),t);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Nn(i.innerType,t);if(i.type==="intersection")return Nn(i.left,t)||Nn(i.right,t);if(i.type==="record"||i.type==="map")return Nn(i.keyType,t)||Nn(i.valueType,t);if(i.type==="pipe")return n._zod.traits.has("$ZodCodec")?!0:Nn(i.in,t)||Nn(i.out,t);if(i.type==="object"){for(const o in i.shape)if(Nn(i.shape[o],t))return!0;return!1}if(i.type==="union"){for(const o of i.options)if(Nn(o,t))return!0;return!1}if(i.type==="tuple"){for(const o of i.items)if(Nn(o,t))return!0;return!!(i.rest&&Nn(i.rest,t))}return!1}const PM=(n,e={})=>t=>{const i=Om({...t,processors:e});return Xt(n,i),Nm(i,n),Dm(i,n)},qA=(n,e,t={})=>i=>{const{libraryOptions:o,target:r}=i??{},A=Om({...o??{},target:r,io:e,processors:t});return Xt(n,A),Nm(A,n),Dm(A,n)},BM={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ZM=(n,e,t,i)=>{const o=t;o.type="string";const{minimum:r,maximum:A,format:I,patterns:l,contentEncoding:c}=n._zod.bag;if(typeof r=="number"&&(o.minLength=r),typeof A=="number"&&(o.maxLength=A),I&&(o.format=BM[I]??I,o.format===""&&delete o.format,I==="time"&&delete o.format),c&&(o.contentEncoding=c),l&&l.size>0){const h=[...l];h.length===1?o.pattern=h[0].source:h.length>1&&(o.allOf=[...h.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},LM=(n,e,t,i)=>{const o=t,{minimum:r,maximum:A,format:I,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:h}=n._zod.bag;typeof I=="string"&&I.includes("int")?o.type="integer":o.type="number";const p=typeof h=="number"&&h>=(r??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(A??Number.POSITIVE_INFINITY),v=e.target==="draft-04"||e.target==="openapi-3.0";p?v?(o.minimum=h,o.exclusiveMinimum=!0):o.exclusiveMinimum=h:typeof r=="number"&&(o.minimum=r),m?v?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c:typeof A=="number"&&(o.maximum=A),typeof l=="number"&&(o.multipleOf=l)},GM=(n,e,t,i)=>{t.type="boolean"},FM=(n,e,t,i)=>{t.not={}},VM=(n,e,t,i)=>{},UM=(n,e,t,i)=>{const o=n._zod.def,r=Yp(o.entries);r.every(A=>typeof A=="number")&&(t.type="number"),r.every(A=>typeof A=="string")&&(t.type="string"),t.enum=r},YM=(n,e,t,i)=>{const o=n._zod.def,r=[];for(const A of o.values)if(A===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof A=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(A))}else r.push(A);if(r.length!==0)if(r.length===1){const A=r[0];t.type=A===null?"null":typeof A,e.target==="draft-04"||e.target==="openapi-3.0"?t.enum=[A]:t.const=A}else r.every(A=>typeof A=="number")&&(t.type="number"),r.every(A=>typeof A=="string")&&(t.type="string"),r.every(A=>typeof A=="boolean")&&(t.type="boolean"),r.every(A=>A===null)&&(t.type="null"),t.enum=r},HM=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},KM=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},WM=(n,e,t,i)=>{const o=t,r=n._zod.def,{minimum:A,maximum:I}=n._zod.bag;typeof A=="number"&&(o.minItems=A),typeof I=="number"&&(o.maxItems=I),o.type="array",o.items=Xt(r.element,e,{...i,path:[...i.path,"items"]})},QM=(n,e,t,i)=>{const o=t,r=n._zod.def;o.type="object",o.properties={};const A=r.shape;for(const c in A)o.properties[c]=Xt(A[c],e,{...i,path:[...i.path,"properties",c]});const I=new Set(Object.keys(A)),l=new Set([...I].filter(c=>{const h=r.shape[c]._zod;return e.io==="input"?h.optin===void 0:h.optout===void 0}));l.size>0&&(o.required=Array.from(l)),r.catchall?._zod.def.type==="never"?o.additionalProperties=!1:r.catchall?r.catchall&&(o.additionalProperties=Xt(r.catchall,e,{...i,path:[...i.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},XM=(n,e,t,i)=>{const o=n._zod.def,r=o.inclusive===!1,A=o.options.map((I,l)=>Xt(I,e,{...i,path:[...i.path,r?"oneOf":"anyOf",l]}));r?t.oneOf=A:t.anyOf=A},$M=(n,e,t,i)=>{const o=n._zod.def,r=Xt(o.left,e,{...i,path:[...i.path,"allOf",0]}),A=Xt(o.right,e,{...i,path:[...i.path,"allOf",1]}),I=c=>"allOf"in c&&Object.keys(c).length===1,l=[...I(r)?r.allOf:[r],...I(A)?A.allOf:[A]];t.allOf=l},qM=(n,e,t,i)=>{const o=t,r=n._zod.def;o.type="object";const A=r.keyType,l=A._zod.bag?.patterns;if(r.mode==="loose"&&l&&l.size>0){const h=Xt(r.valueType,e,{...i,path:[...i.path,"patternProperties","*"]});o.patternProperties={};for(const p of l)o.patternProperties[p.source]=h}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Xt(r.keyType,e,{...i,path:[...i.path,"propertyNames"]})),o.additionalProperties=Xt(r.valueType,e,{...i,path:[...i.path,"additionalProperties"]});const c=A._zod.values;if(c){const h=[...c].filter(p=>typeof p=="string"||typeof p=="number");h.length>0&&(o.required=h)}},JM=(n,e,t,i)=>{const o=n._zod.def,r=Xt(o.innerType,e,i),A=e.seen.get(n);e.target==="openapi-3.0"?(A.ref=o.innerType,t.nullable=!0):t.anyOf=[r,{type:"null"}]},eR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType},tR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType,t.default=JSON.parse(JSON.stringify(o.defaultValue))},nR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},iR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType;let A;try{A=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=A},gR=(n,e,t,i)=>{const o=n._zod.def,r=o.in._zod.traits.has("$ZodTransform"),A=e.io==="input"?r?o.out:o.in:o.out;Xt(A,e,i);const I=e.seen.get(n);I.ref=A},oR=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType,t.readOnly=!0},km=(n,e,t,i)=>{const o=n._zod.def;Xt(o.innerType,e,i);const r=e.seen.get(n);r.ref=o.innerType},sR=$("ZodISODateTime",(n,e)=>{rk.init(n,e),zt.init(n,e)});function rR(n){return cM(sR,n)}const aR=$("ZodISODate",(n,e)=>{ak.init(n,e),zt.init(n,e)});function AR(n){return dM(aR,n)}const CR=$("ZodISOTime",(n,e)=>{Ak.init(n,e),zt.init(n,e)});function IR(n){return uM(CR,n)}const lR=$("ZodISODuration",(n,e)=>{Ck.init(n,e),zt.init(n,e)});function cR(n){return hM(lR,n)}const gi=$("ZodError",(n,e)=>{$p.init(n,e),n.name="ZodError",Object.defineProperties(n,{format:{value:t=>JN(n,t)},flatten:{value:t=>qN(n,t)},addIssue:{value:t=>{n.issues.push(t),n.message=JSON.stringify(n.issues,gc,2)}},addIssues:{value:t=>{n.issues.push(...t),n.message=JSON.stringify(n.issues,gc,2)}},isEmpty:{get(){return n.issues.length===0}}})},{Parent:Error}),dR=ac(gi),uR=Ac(gi),hR=HA(gi),fR=KA(gi),pR=nD(gi),mR=iD(gi),vR=gD(gi),bR=oD(gi),yR=sD(gi),wR=rD(gi),xR=aD(gi),SR=AD(gi),Mm=new WeakMap;function Vr(n,e,t){const i=Object.getPrototypeOf(n);let o=Mm.get(i);if(o||(o=new Set,Mm.set(i,o)),!o.has(e)){o.add(e);for(const r in t){const A=t[r];Object.defineProperty(i,r,{configurable:!0,enumerable:!1,get(){const I=A.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:I}),I},set(I){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:I})}})}}}const Rt=$("ZodType",(n,e)=>(Mt.init(n,e),Object.assign(n["~standard"],{jsonSchema:{input:qA(n,"input"),output:qA(n,"output")}}),n.toJSONSchema=PM(n,{}),n.def=e,n.type=e.type,Object.defineProperty(n,"_def",{value:e}),n.parse=(t,i)=>dR(n,t,i,{callee:n.parse}),n.safeParse=(t,i)=>hR(n,t,i),n.parseAsync=async(t,i)=>uR(n,t,i,{callee:n.parseAsync}),n.safeParseAsync=async(t,i)=>fR(n,t,i),n.spa=n.safeParseAsync,n.encode=(t,i)=>pR(n,t,i),n.decode=(t,i)=>mR(n,t,i),n.encodeAsync=async(t,i)=>vR(n,t,i),n.decodeAsync=async(t,i)=>bR(n,t,i),n.safeEncode=(t,i)=>yR(n,t,i),n.safeDecode=(t,i)=>wR(n,t,i),n.safeEncodeAsync=async(t,i)=>xR(n,t,i),n.safeDecodeAsync=async(t,i)=>SR(n,t,i),Vr(n,"ZodType",{check(...t){const i=this.def;return this.clone(Tg(i,{checks:[...i.checks??[],...t.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,i){return Og(this,t,i)},brand(){return this},register(t,i){return t.add(this,i),this},refine(t,i){return this.check(uz(t,i))},superRefine(t,i){return this.check(hz(t,i))},overwrite(t){return this.check(ds(t))},optional(){return Vm(this)},exactOptional(){return nz(this)},nullable(){return Um(this)},nullish(){return Vm(Um(this))},nonoptional(t){return az(this,t)},array(){return Se(this)},or(t){return Lm([this,t])},and(t){return $R(this,t)},transform(t){return Hm(this,ez(t))},default(t){return oz(this,t)},prefault(t){return rz(this,t)},catch(t){return Cz(this,t)},pipe(t){return Hm(this,t)},readonly(){return cz(this)},describe(t){const i=this.clone();return Fr.add(i,{description:t}),i},meta(...t){if(t.length===0)return Fr.get(this);const i=this.clone();return Fr.add(i,t[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t){return t(this)}}),Object.defineProperty(n,"description",{get(){return Fr.get(n)?.description},configurable:!0}),n)),Rm=$("_ZodString",(n,e)=>{Cc.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(i,o,r)=>ZM(n,i,o);const t=n._zod.bag;n.format=t.format??null,n.minLength=t.minimum??null,n.maxLength=t.maximum??null,Vr(n,"_ZodString",{regex(...i){return this.check(yM(...i))},includes(...i){return this.check(SM(...i))},startsWith(...i){return this.check(EM(...i))},endsWith(...i){return this.check(TM(...i))},min(...i){return this.check($A(...i))},max(...i){return this.check(Em(...i))},length(...i){return this.check(Tm(...i))},nonempty(...i){return this.check($A(1,...i))},lowercase(i){return this.check(wM(i))},uppercase(i){return this.check(xM(i))},trim(){return this.check(NM())},normalize(...i){return this.check(OM(...i))},toLowerCase(){return this.check(DM())},toUpperCase(){return this.check(kM())},slugify(){return this.check(MM())}})}),ER=$("ZodString",(n,e)=>{Cc.init(n,e),Rm.init(n,e),n.email=t=>n.check(Hk(TR,t)),n.url=t=>n.check($k(OR,t)),n.jwt=t=>n.check(lM(VR,t)),n.emoji=t=>n.check(qk(NR,t)),n.guid=t=>n.check(ym(zm,t)),n.uuid=t=>n.check(Kk(JA,t)),n.uuidv4=t=>n.check(Wk(JA,t)),n.uuidv6=t=>n.check(Qk(JA,t)),n.uuidv7=t=>n.check(Xk(JA,t)),n.nanoid=t=>n.check(Jk(DR,t)),n.guid=t=>n.check(ym(zm,t)),n.cuid=t=>n.check(eM(kR,t)),n.cuid2=t=>n.check(tM(MR,t)),n.ulid=t=>n.check(nM(RR,t)),n.base64=t=>n.check(AM(LR,t)),n.base64url=t=>n.check(CM(GR,t)),n.xid=t=>n.check(iM(zR,t)),n.ksuid=t=>n.check(gM(_R,t)),n.ipv4=t=>n.check(oM(jR,t)),n.ipv6=t=>n.check(sM(PR,t)),n.cidrv4=t=>n.check(rM(BR,t)),n.cidrv6=t=>n.check(aM(ZR,t)),n.e164=t=>n.check(IM(FR,t)),n.datetime=t=>n.check(rR(t)),n.date=t=>n.check(AR(t)),n.time=t=>n.check(IR(t)),n.duration=t=>n.check(cR(t))});function D(n){return Yk(ER,n)}const zt=$("ZodStringFormat",(n,e)=>{Ot.init(n,e),Rm.init(n,e)}),TR=$("ZodEmail",(n,e)=>{qD.init(n,e),zt.init(n,e)}),zm=$("ZodGUID",(n,e)=>{XD.init(n,e),zt.init(n,e)}),JA=$("ZodUUID",(n,e)=>{$D.init(n,e),zt.init(n,e)}),OR=$("ZodURL",(n,e)=>{JD.init(n,e),zt.init(n,e)}),NR=$("ZodEmoji",(n,e)=>{ek.init(n,e),zt.init(n,e)}),DR=$("ZodNanoID",(n,e)=>{tk.init(n,e),zt.init(n,e)}),kR=$("ZodCUID",(n,e)=>{nk.init(n,e),zt.init(n,e)}),MR=$("ZodCUID2",(n,e)=>{ik.init(n,e),zt.init(n,e)}),RR=$("ZodULID",(n,e)=>{gk.init(n,e),zt.init(n,e)}),zR=$("ZodXID",(n,e)=>{ok.init(n,e),zt.init(n,e)}),_R=$("ZodKSUID",(n,e)=>{sk.init(n,e),zt.init(n,e)}),jR=$("ZodIPv4",(n,e)=>{Ik.init(n,e),zt.init(n,e)}),PR=$("ZodIPv6",(n,e)=>{lk.init(n,e),zt.init(n,e)}),BR=$("ZodCIDRv4",(n,e)=>{ck.init(n,e),zt.init(n,e)}),ZR=$("ZodCIDRv6",(n,e)=>{dk.init(n,e),zt.init(n,e)}),LR=$("ZodBase64",(n,e)=>{uk.init(n,e),zt.init(n,e)}),GR=$("ZodBase64URL",(n,e)=>{fk.init(n,e),zt.init(n,e)}),FR=$("ZodE164",(n,e)=>{pk.init(n,e),zt.init(n,e)}),VR=$("ZodJWT",(n,e)=>{vk.init(n,e),zt.init(n,e)}),_m=$("ZodNumber",(n,e)=>{am.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(i,o,r)=>LM(n,i,o),Vr(n,"ZodNumber",{gt(i,o){return this.check(xm(i,o))},gte(i,o){return this.check(cc(i,o))},min(i,o){return this.check(cc(i,o))},lt(i,o){return this.check(wm(i,o))},lte(i,o){return this.check(lc(i,o))},max(i,o){return this.check(lc(i,o))},int(i){return this.check(jm(i))},safe(i){return this.check(jm(i))},positive(i){return this.check(xm(0,i))},nonnegative(i){return this.check(cc(0,i))},negative(i){return this.check(wm(0,i))},nonpositive(i){return this.check(lc(0,i))},multipleOf(i,o){return this.check(Sm(i,o))},step(i,o){return this.check(Sm(i,o))},finite(){return this}});const t=n._zod.bag;n.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),n.isFinite=!0,n.format=t.format??null});function j(n){return fM(_m,n)}const UR=$("ZodNumberFormat",(n,e)=>{bk.init(n,e),_m.init(n,e)});function jm(n){return pM(UR,n)}const YR=$("ZodBoolean",(n,e)=>{yk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>GM(n,t,i)});function In(n){return mM(YR,n)}const HR=$("ZodUnknown",(n,e)=>{wk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>VM()});function $i(){return vM(HR)}const KR=$("ZodNever",(n,e)=>{xk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>FM(n,t,i)});function Pm(n){return bM(KR,n)}const WR=$("ZodArray",(n,e)=>{Sk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>WM(n,t,i,o),n.element=e.element,Vr(n,"ZodArray",{min(t,i){return this.check($A(t,i))},nonempty(t){return this.check($A(1,t))},max(t,i){return this.check(Em(t,i))},length(t,i){return this.check(Tm(t,i))},unwrap(){return this.element}})});function Se(n,e){return RM(WR,n,e)}const Bm=$("ZodObject",(n,e)=>{Tk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>QM(n,t,i,o),It(n,"shape",()=>e.shape),Vr(n,"ZodObject",{keyof(){return _e(Object.keys(this._zod.def.shape))},catchall(t){return this.clone({...this._zod.def,catchall:t})},passthrough(){return this.clone({...this._zod.def,catchall:$i()})},loose(){return this.clone({...this._zod.def,catchall:$i()})},strict(){return this.clone({...this._zod.def,catchall:Pm()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(t){return HN(this,t)},safeExtend(t){return KN(this,t)},merge(t){return WN(this,t)},pick(t){return UN(this,t)},omit(t){return YN(this,t)},partial(...t){return QN(Fm,this,t[0])},required(...t){return XN(Ym,this,t[0])}})});function He(n,e){const t={type:"object",shape:n??{},...we(e)};return new Bm(t)}function Ie(n,e){return new Bm({type:"object",shape:n,catchall:Pm(),...we(e)})}const Zm=$("ZodUnion",(n,e)=>{cm.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>XM(n,t,i,o),n.options=e.options});function Lm(n,e){return new Zm({type:"union",options:n,...we(e)})}const QR=$("ZodDiscriminatedUnion",(n,e)=>{Zm.init(n,e),Ok.init(n,e)});function Ur(n,e,t){return new QR({type:"union",options:e,discriminator:n,...we(t)})}const XR=$("ZodIntersection",(n,e)=>{Nk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>$M(n,t,i,o)});function $R(n,e){return new XR({type:"intersection",left:n,right:e})}const Gm=$("ZodRecord",(n,e)=>{Dk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>qM(n,t,i,o),n.keyType=e.keyType,n.valueType=e.valueType});function eC(n,e,t){return!e||!e._zod?new Gm({type:"record",keyType:D(),valueType:n,...we(e)}):new Gm({type:"record",keyType:n,valueType:e,...we(t)})}const dc=$("ZodEnum",(n,e)=>{kk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(i,o,r)=>UM(n,i,o),n.enum=e.entries,n.options=Object.values(e.entries);const t=new Set(Object.keys(e.entries));n.extract=(i,o)=>{const r={};for(const A of i)if(t.has(A))r[A]=e.entries[A];else throw new Error(`Key ${A} not found in enum`);return new dc({...e,checks:[],...we(o),entries:r})},n.exclude=(i,o)=>{const r={...e.entries};for(const A of i)if(t.has(A))delete r[A];else throw new Error(`Key ${A} not found in enum`);return new dc({...e,checks:[],...we(o),entries:r})}});function _e(n,e){const t=Array.isArray(n)?Object.fromEntries(n.map(i=>[i,i])):n;return new dc({type:"enum",entries:t,...we(e)})}const qR=$("ZodLiteral",(n,e)=>{Mk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>YM(n,t,i),n.values=new Set(e.values),Object.defineProperty(n,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function qe(n,e){return new qR({type:"literal",values:Array.isArray(n)?n:[n],...we(e)})}const JR=$("ZodTransform",(n,e)=>{Rk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>KM(n,t),n._zod.parse=(t,i)=>{if(i.direction==="backward")throw new Up(n.constructor.name);t.addIssue=r=>{if(typeof r=="string")t.issues.push(Gr(r,t.value,e));else{const A=r;A.fatal&&(A.continue=!1),A.code??(A.code="custom"),A.input??(A.input=t.value),A.inst??(A.inst=n),t.issues.push(Gr(A))}};const o=e.transform(t.value,t);return o instanceof Promise?o.then(r=>(t.value=r,t.fallback=!0,t)):(t.value=o,t.fallback=!0,t)}});function ez(n){return new JR({type:"transform",transform:n})}const Fm=$("ZodOptional",(n,e)=>{hm.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>km(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function Vm(n){return new Fm({type:"optional",innerType:n})}const tz=$("ZodExactOptional",(n,e)=>{zk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>km(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function nz(n){return new tz({type:"optional",innerType:n})}const iz=$("ZodNullable",(n,e)=>{_k.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>JM(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function Um(n){return new iz({type:"nullable",innerType:n})}const gz=$("ZodDefault",(n,e)=>{jk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>tR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});function oz(n,e){return new gz({type:"default",innerType:n,get defaultValue(){return typeof e=="function"?e():Qp(e)}})}const sz=$("ZodPrefault",(n,e)=>{Pk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>nR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function rz(n,e){return new sz({type:"prefault",innerType:n,get defaultValue(){return typeof e=="function"?e():Qp(e)}})}const Ym=$("ZodNonOptional",(n,e)=>{Bk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>eR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function az(n,e){return new Ym({type:"nonoptional",innerType:n,...we(e)})}const Az=$("ZodCatch",(n,e)=>{Zk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>iR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});function Cz(n,e){return new Az({type:"catch",innerType:n,catchValue:typeof e=="function"?e:()=>e})}const Iz=$("ZodPipe",(n,e)=>{Lk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>gR(n,t,i,o),n.in=e.in,n.out=e.out});function Hm(n,e){return new Iz({type:"pipe",in:n,out:e})}const lz=$("ZodReadonly",(n,e)=>{Gk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>oR(n,t,i,o),n.unwrap=()=>n._zod.def.innerType});function cz(n){return new lz({type:"readonly",innerType:n})}const dz=$("ZodCustom",(n,e)=>{Fk.init(n,e),Rt.init(n,e),n._zod.processJSONSchema=(t,i,o)=>HM(n,t)});function uz(n,e={}){return zM(dz,n,e)}function hz(n,e){return _M(n,e)}const fz="compass.query/1",pz=["file","module","package","namespace","class","struct","interface","trait","protocol","enum","enum_member","type_alias","function","method","constructor","property","field","variable","constant","parameter","import","export","macro","annotation","route","component","event","message","topic","queue","job","resource","schema","query","migration","config_key","database","database_schema","database_table","database_view","database_column","database_index","database_constraint","database_procedure","database_trigger"],mz=["contains","calls","imports","exports","extends","implements","references","type_of","returns","instantiates","overrides","decorates","routes_to","reads","writes","aliases","registers","handles","publishes","subscribes","produces","consumes","schedules","triggers","tests","depends_on","documents","maps_to","renders"],vz=["controller","route_handler","middleware","service","resolver","consumer","producer","subscriber","repository","model","test","fixture","generated","ui_component","hook","client_boundary","client_component","server_component","server_function","data_loader"],bz=["search","callers","callees","impact","explore","node_trail"],yz=["middleware","dependency","security","layout","template","loading","default","error_boundary","not_found","boundary","loader","action","handler","data_loader","route_component"],uc=D().min(1).refine(n=>n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/.test(n)?!1:n.split("/").every(e=>e!==""&&e!=="."&&e!==".."),"source path must be a safe repository-relative path"),us=Ie({file:uc,startByte:j().int().nonnegative(),endByte:j().int().nonnegative(),startLine:j().int().positive(),startColumn:j().int().nonnegative(),endLine:j().int().positive(),endColumn:j().int().nonnegative()}).refine(n=>n.endByte>=n.startByte&&(n.endLine>n.startLine||n.endLine===n.startLine&&n.endColumn>=n.startColumn),"source anchor must be ordered"),wz=_e(pz),xz=_e(mz),Sz=_e(vz),Ez=_e(bz),Tz=_e(["structural_graph","program_ir"]),Oz=_e(["ast","config","convention","artifact","heuristic"]),hc=_e(["exact","inferred","ambiguous"]),tC=_e(["exact","ambiguous","unresolved"]),Km=Ie({nodeId:D().min(1),reason:D().min(1),confidence:hc,score:j().finite().nullable().optional(),anchor:us.nullable().optional()}),nC=Ie({layer:Tz,origin:Oz,extractor:D().min(1),confidence:hc,anchor:us.nullable(),rule:D().min(1).nullable(),wiringSite:us.nullable(),resolution:tC,candidates:Se(Km).max(20).default([])}),Nz=Ie({type:qe("file"),data:Ie({contentDigest:D().min(1),byteSize:j().int().nonnegative(),generated:In()})}),Dz=Ie({type:qe("symbol"),data:Ie({signature:D().nullable().optional(),modifiers:Se(D()).default([]),overloadDiscriminator:D().nullable().optional(),declaringType:D().nullable().optional(),signatureDigest:D().nullable().optional(),implementationDigest:D().nullable().optional(),sourceDigest:D().nullable().optional()})}),kz=Ie({type:qe("import_export"),data:Ie({specifier:D(),importedName:D().nullable().optional(),localName:D().nullable().optional(),typeOnly:In()})}),Wm=_e(yz),Mz=Ie({stage:Wm,position:j().int().nonnegative(),reference:D().min(1),resolution:tC,sourceAnchor:us.nullable(),target:D().nullable().optional(),candidates:Se(Km).max(20).default([])}),Rz=Ie({type:qe("route"),data:Ie({operation:D(),path:D(),originalPath:D().nullable().optional(),declaringScope:D(),resolution:tC,middlewareCount:j().int().nonnegative(),stages:Se(Mz).max(256).default([])})}),zz=Ie({type:qe("component"),data:Ie({componentType:D()})}),_z=Ie({type:qe("resource"),data:Ie({resourceKind:_e(["document","paper","image","concept","rationale"]),uri:D().nullable().optional(),mediaType:D().nullable().optional()})}),jz=Ie({type:qe("messaging"),data:Ie({transport:D(),subject:D(),declaringScope:D()})}),Pz=Ie({type:qe("job"),data:Ie({schedule:D().nullable().optional(),queue:D().nullable().optional()})}),Bz=Ie({type:qe("schema"),data:Ie({dialect:D().nullable().optional(),logicalDatabase:D().nullable().optional(),namespace:D().nullable().optional()})}),Zz=Ie({type:qe("query"),data:Ie({dialect:D().nullable().optional(),operation:D().nullable().optional(),textDigest:D().nullable().optional()})}),Lz=Ie({type:qe("config"),data:Ie({format:D(),keyPath:D()})}),Gz=Ie({type:qe("database"),data:Ie({logicalDatabase:D(),databaseSchema:D().nullable().optional()})}),Fz=Ur("type",[Nz,Dz,kz,Rz,zz,_z,jz,Pz,Bz,Zz,Lz,Gz]),Vz=Ie({type:qe("call"),data:Ie({dispatch:_e(["static","virtual","dynamic"]),receiverType:D().nullable().optional(),argumentCount:j().int().nonnegative().nullable().optional()})}),Uz=Ie({type:qe("route"),data:Ie({stage:Wm,position:j().int().nonnegative().nullable().optional(),operation:D().nullable().optional()})}),Yz=Ie({type:qe("messaging"),data:Ie({transport:D(),subject:D()})}),Hz=Ie({type:qe("schedule"),data:Ie({expression:D().nullable().optional()})}),Kz=Ie({type:qe("mapping"),data:Ie({mappingKind:D()})}),Wz=Ie({type:qe("render"),data:Ie({renderKind:_e(["jsx","create_element","root","lazy","dynamic"]),boundary:D().nullable().optional()})}),Qm=Ur("type",[Vz,Uz,Yz,Hz,Kz,Wz]),Qz=Ie({maxDepth:j().int().positive(),maxNodes:j().int().positive(),maxEdges:j().int().positive(),maxPaths:j().int().positive(),maxCandidates:j().int().positive(),maxSourceBytes:j().int().positive(),maxResponseBytes:j().int().positive()}),Xz=Ie({nodeId:D().min(1),score:j().finite(),matchedFields:Se(D())}),$z=Ie({id:D().min(1),kind:wz,roles:Se(Sz),name:D().min(1),qualifiedName:D().min(1),language:D().nullable(),framework:D().nullable(),source:us.nullable(),details:Fz.nullable(),evidence:Se(nC)}),qz=Ie({id:D().min(1),source:D().min(1),target:D().min(1),kind:xz,relationshipSite:us.nullable(),details:Qm.nullable(),evidence:Se(nC)}),Jz=Ie({path:uc,contentDigest:D().min(1),source:D().nullable(),truncated:In()}),e3=Ie({id:D().min(1),nodeIds:Se(D().min(1)),edgeIds:Se(D().min(1)),weakestResolution:tC,weakestConfidence:hc}),t3=Ie({code:_e(["no_match","ambiguous_match","relationship_inconsistency","direction_mismatch","unresolved_handler","incomplete_coverage","stale_source_digest","bounded_truncation","program_orphan","program_conflict","program_unavailable"]),message:D().min(1),nodeId:D().nullable(),path:uc.nullable()}),n3=Ie({schema:qe(fz),operation:Ez,results:Se(Xz),nodes:Se($z),edges:Se(qz),files:Se(Jz),paths:Se(e3),diagnostics:Se(t3),limits:Qz,truncated:In()}),i3="compass.viewer.graph/1",fc=He({file:D(),startLine:j().int().positive().optional(),endLine:j().int().positive().optional(),startByte:j().int().nonnegative().optional(),endByte:j().int().nonnegative().optional()}).passthrough(),g3=He({field:D().min(1),before:$i().optional(),after:$i().optional()}),Xm=He({before:eC(D(),$i()).optional(),after:eC(D(),$i()).optional(),fields:Se(g3)}),$m=He({challenge:D().startsWith("challenge:"),targetId:D().min(1),effect:_e(["flag","mask"]),masked:In(),certificateDigest:D().regex(/^[0-9a-f]{64}$/),summary:D()}).strict(),o3=He({total:j().int().nonnegative(),examples:Se(He({kind:_e(["assertion","challenge"]),id:D().min(1),reasonCode:D().min(1),explanation:D(),sequence:j().int().nonnegative()}).strict()),omittedExamples:j().int().nonnegative()}).strict(),qm=eC(D(),$i()),s3=Ur("kind",[He({kind:qe("native")}).passthrough(),He({kind:qe("ocr"),profile:qm,confidence_bps:j().int().min(0).max(1e4)}).passthrough()]),Jm=He({kind:D().min(1)}).passthrough(),r3=He({candidate_id:D().min(1),x:j().int().nonnegative(),y:j().int().nonnegative(),width:j().int().positive(),height:j().int().positive()}).passthrough(),a3=He({schema:qe("compass.document.preview/1"),kind:_e(["page","slide","sheet"]),locator:Jm,label:D().min(1),width:j().int().positive(),height:j().int().positive(),svg:D().min(1).max(512*1024),regions:Se(r3).max(256).default([]),digest:D().regex(/^sha256:[0-9a-f]{64}$/)}).passthrough(),A3=He({role:_e(["root","block"]).optional(),kind:D().optional(),format:D().optional(),text:D().optional(),ordinal:j().int().nonnegative().optional(),complete:In().optional(),visualCoverage:_e(["not_requested","complete","partial","failed"]).optional(),ocrMode:_e(["off","auto","always"]).optional(),origin:s3.optional(),locator:Jm.optional(),ocrProfile:qm.optional(),previews:Se(a3).max(256).optional()}).passthrough(),C3=He({id:D().min(1),label:D(),kind:D().optional(),community:j().int(),communityName:D().optional(),degree:j().int().nonnegative().optional(),language:D().optional(),signature:D().optional(),size:j().positive().optional(),memberCount:j().int().nonnegative().optional(),detailAvailable:In().optional(),learningStatus:D().optional(),learningStale:In().optional(),depth:j().int().nonnegative().optional(),root:In().optional(),agentAssertion:D().startsWith("assertion:").optional(),agentSummary:D().optional(),groundingStatus:qe("GROUNDED").optional(),challenged:In().optional(),challenge:$m.optional(),change:_e(["added","removed","changed","unchanged"]).optional(),evidence:Xm.optional(),codeEvidence:Se(nC).optional(),source:fc.optional(),color:He({background:D(),border:D()}).passthrough().optional(),document:A3.optional()}).passthrough(),I3=He({id:D().min(1),source:D().min(1),target:D().min(1),relation:D(),weight:j().int().positive().optional(),change:_e(["added","removed","changed","unchanged"]).optional(),evidence:Xm.optional(),codeEvidence:Se(nC).optional(),details:Qm.nullable().optional(),relationshipSite:fc.optional(),confidence:_e(["extracted","inferred","ambiguous","aggregated"]).optional(),agentAssertion:D().startsWith("assertion:").optional(),agentSummary:D().optional(),groundingStatus:qe("GROUNDED").optional(),challenged:In().optional(),challenge:$m.optional()}).passthrough(),l3=He({id:j().int(),label:D(),color:D(),hidden:In().default(!1)}).passthrough(),Ng=He({schema:qe(i3),title:D(),stats:He({nodes:j().int().nonnegative(),edges:j().int().nonnegative(),communities:j().int().nonnegative(),aggregated:In()}).passthrough(),nodes:Se(C3),edges:Se(I3),communities:Se(l3),hyperedges:Se($i()).default([]),effectiveGraph:He({effectiveIdentity:D().regex(/^[0-9a-f]{64}$/),baseGeneration:He({generationId:D().min(1),graphDigest:D().regex(/^[0-9a-f]{64}$/)}).strict(),overlayRevision:D().regex(/^[0-9a-f]{64}$/),compositionProfile:_e(["augment","curated"]),retractions:o3,omissions:He({total:j().int().nonnegative(),direct:j().int().nonnegative(),cascaded:j().int().nonnegative(),examples:Se($i()),omittedExamples:j().int().nonnegative()}).strict()}).strict().optional()}).passthrough(),c3=_e(["resolved","inferred","ambiguous","unresolved"]),ev=He({source_file:D(),start_byte:j().int().nonnegative(),end_byte:j().int().nonnegative()}),d3=He({id:D(),symbol:D().nullable(),name:D(),file:D().nullable(),anchor:ev.nullable().optional(),startLine:j().int().positive().nullable().optional(),endLine:j().int().positive().nullable().optional(),startByte:j().int().nonnegative().nullable().optional(),endByte:j().int().nonnegative().nullable().optional(),graphNodeId:D().nullable(),unresolved:In(),evidenceLayer:_e(["structural_graph","program_ir","combined"]).optional()}),u3=Lm([He({anchor:ev,evidence:Se(D())}),He({sourceFile:D().nullable(),line:j().int().positive().nullable(),startByte:j().int().nonnegative().nullable(),endByte:j().int().nonnegative().nullable(),evidence:Se(D())})]),h3=He({id:D(),source:D(),target:D(),callee:D(),resolution:c3,confidence:D().nullable().optional(),callSites:Se(u3),evidenceLayer:_e(["structural_graph","program_ir","combined"]).optional()}),f3=He({schema:_e(["compass.program.call_graph/1","compass.call_graph/1"]),rootSymbol:D(),direction:_e(["callers","callees","both"]),depth:j().int().positive(),nodes:Se(d3),edges:Se(h3),truncated:In(),continuations:Se(He({symbol:D(),direction:_e(["callers","callees","both"]),nextDepth:j().int().positive()})),coverage:He({resolved:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative(),unresolved:j().int().nonnegative(),evidenceLayer:_e(["structural_graph","program_ir","combined"]).optional(),partial:In().optional(),limitations:Se(D()).optional(),warning:D()})}),p3="compass.viewer.architecture/1",m3=_e(["production","all_code"]),tv=_e(["execution","dependency","type","structure","contextual","unknown"]),nv=_e(["architecture","execution","dependency","type","structure","all"]),v3=_e(["owner","subsystem"]),b3=_e(["overview","detail"]),y3=_e(["overlay","persisted","owner","path","declaration","hub","provider","fallback"]),w3=_e(["good","degraded","insufficient"]),x3=_e(["info","warning","error"]),S3=_e(["production","test","generated","vendor","documentation","unknown"]),iv=Ie({production:j().int().nonnegative(),test:j().int().nonnegative(),generated:j().int().nonnegative(),vendor:j().int().nonnegative(),documentation:j().int().nonnegative(),unknown:j().int().nonnegative()}),gv=Ie({execution:j().int().nonnegative(),dependency:j().int().nonnegative(),type:j().int().nonnegative(),structure:j().int().nonnegative(),contextual:j().int().nonnegative(),unknown:j().int().nonnegative()}),E3=Ie({extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()}),T3=Ie({id:D().min(1),label:D(),kind:D(),sourceFile:D().nullable(),sourceScope:S3,scopeReason:D().min(1),community:j().int().nonnegative().nullable()}),O3=Ie({id:D().min(1),source:D().min(1),target:D().min(1),relation:D(),relationClass:tv,confidence:_e(["extracted","inferred","ambiguous"])}),N3=Ie({value:D().min(1),provenance:y3,membershipSignature:D().min(1),quality:j().int().min(0).max(100),evidence:Se(D())}),D3=Ie({id:D().min(1),parentId:D().nullable(),kind:v3,rank:j().int().positive(),name:N3,ownerKey:D().min(1),communityIds:Se(j().int().nonnegative()),nodeCount:j().int().nonnegative(),relationshipCount:j().int().nonnegative(),neighborCount:j().int().nonnegative(),cohesion:j().finite(),sourceScopes:iv,pinned:In()}),k3=Ie({nodeIndex:j().int().nonnegative(),groupIndex:j().int().nonnegative()}),M3=Ie({id:D().min(1),level:b3,ownerId:D().nullable(),sourceGroup:D().min(1),targetGroup:D().min(1),relationshipCount:j().int().nonnegative(),relationClasses:gv,evidence:E3}),R3=Ie({admitted:j().int().nonnegative(),internal:j().int().nonnegative(),crossGroup:j().int().nonnegative(),unassigned:j().int().nonnegative(),relationClasses:gv}),ov=Ie({totalGroups:j().int().nonnegative(),shownGroups:j().int().nonnegative(),omittedGroups:j().int().nonnegative(),representedNodes:j().int().nonnegative(),omittedNodes:j().int().nonnegative(),representedRelationships:j().int().nonnegative(),omittedRelationships:j().int().nonnegative(),witnessGroupIds:Se(D()),maxOverviewGroups:j().int().positive(),maxOverviewRoutes:j().int().positive()}),z3=Ie({code:D().min(1),severity:x3,message:D(),observed:j().nullable(),threshold:j().nullable(),witnesses:Se(D()),recommendedAction:D()}),sv=Ie({status:w3,metrics:Ie({sourceScopes:iv,unknownSourceFraction:j().min(0).max(1),generatedVendorLeakage:j().int().nonnegative(),representedNodeFraction:j().min(0).max(1),representedRelationshipFraction:j().min(0).max(1),duplicateNames:j().int().nonnegative(),fallbackNames:j().int().nonnegative(),largestGroupFraction:j().min(0).max(1),unknownRelations:j().int().nonnegative(),unassignedNodes:j().int().nonnegative(),unassignedRelationships:j().int().nonnegative()}),diagnostics:Se(z3)}),_3=Ie({scope:m3,defaultLens:nv,groups:Se(D3),memberships:Se(k3),routes:Se(M3),overviewGroupIds:Se(D()),overviewRouteIds:Se(D()),coverage:R3,omissions:ov,quality:sv}),j3=Ie({maxNodes:j().int().positive(),maxRelationships:j().int().positive(),maxGroups:j().int().positive(),maxRoutes:j().int().positive(),maxOverviewGroups:j().int().positive(),maxOverviewRoutes:j().int().positive(),maxNameCandidates:j().int().positive(),maxNameEvidence:j().int().positive(),maxDiagnostics:j().int().positive(),maxOmissionWitnesses:j().int().positive()}),P3=Ie({schema:qe(p3),title:D(),nodes:Se(T3),relationships:Se(O3),projections:Se(_3).min(1),statistics:Ie({nodes:j().int().nonnegative(),relationships:j().int().nonnegative(),communities:j().int().nonnegative(),extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()}),provenance:Ie({projectName:D(),builtAtCommit:D().nullable(),generatedAt:D().nullable()}),limits:j3}).superRefine((n,e)=>{const t=new Set(n.nodes.map(i=>i.id));t.size!==n.nodes.length&&e.addIssue({code:"custom",path:["nodes"],message:"node IDs must be unique"});for(const[i,o]of n.relationships.entries())(!t.has(o.source)||!t.has(o.target))&&e.addIssue({code:"custom",path:["relationships",i],message:"relationship endpoints must identify included nodes"});for(const[i,o]of n.projections.entries()){const r=new Set(o.groups.map(A=>A.id));for(const[A,I]of o.memberships.entries())(I.nodeIndex>=n.nodes.length||I.groupIndex>=o.groups.length)&&e.addIssue({code:"custom",path:["projections",i,"memberships",A],message:"membership indexes must identify an included node and group"});for(const[A,I]of o.routes.entries())(!r.has(I.sourceGroup)||!r.has(I.targetGroup))&&e.addIssue({code:"custom",path:["projections",i,"routes",A],message:"route endpoints must identify included groups"})}}),B3=_e(["production","all"]),Z3=_e(["all","extracted","inferred","ambiguous"]),L3=_e(["production","test","generated","vendor","documentation","unknown"]),G3=_e(["extracted","inferred","ambiguous"]),F3=He({production:j().int().nonnegative(),test:j().int().nonnegative(),generated:j().int().nonnegative(),vendor:j().int().nonnegative(),documentation:j().int().nonnegative(),unknown:j().int().nonnegative()}),V3=He({id:D(),name:D(),nodeCount:j().int().nonnegative(),totalNodeCount:j().int().nonnegative(),internalRelationshipCount:j().int().nonnegative(),incomingRelationships:j().int().nonnegative(),outgoingRelationships:j().int().nonnegative(),scopes:F3}),U3=He({id:D(),sourceGroup:D(),targetGroup:D(),relationships:j().int().nonnegative(),extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()});He({title:D(),scope:B3,evidence:Z3,lens:nv,groups:Se(V3),routes:Se(U3),statistics:He({visibleNodes:j().int().nonnegative(),totalNodes:j().int().nonnegative(),visibleRelationships:j().int().nonnegative(),totalRelationships:j().int().nonnegative(),communities:j().int().nonnegative(),extracted:j().int().nonnegative(),inferred:j().int().nonnegative(),ambiguous:j().int().nonnegative()}),coverage:He({internal:j().int().nonnegative(),crossGroup:j().int().nonnegative(),unassigned:j().int().nonnegative()}),omissions:ov,quality:sv,provenance:He({projectName:D(),builtAtCommit:D().nullable(),generatedAt:D().nullable()})});const Y3=He({id:D(),label:D(),kind:D(),sourceFile:D().nullable(),scope:L3,groupId:D()}),rv=He({id:D(),source:D(),target:D(),sourceLabel:D(),targetLabel:D(),sourceFile:D().nullable(),targetFile:D().nullable(),sourceGroup:D(),targetGroup:D(),relation:D(),relationClass:tv,confidence:G3}),iC=He({page:j().int().positive(),pageSize:j().int().min(1).max(100),pageCount:j().int().positive(),total:j().int().nonnegative(),start:j().int().nonnegative(),end:j().int().nonnegative()});Ur("kind",[iC.extend({kind:qe("symbols"),groupId:D(),items:Se(Y3)}),iC.extend({kind:qe("relationships"),groupId:D(),items:Se(rv)})]),iC.extend({routeId:D(),sourceGroup:D(),targetGroup:D(),items:Se(rv)});const H3=He({id:D(),kind:_e(["group","symbol","relationship"]),label:D(),detail:D(),groupId:D().nullable(),routeId:D().nullable(),sourceFile:D().nullable()});iC.extend({query:D(),items:Se(H3)});const K3="compass.viewer.workbench/1",W3=Ie({status:_e(["complete","summary","partial"]),truncated:In(),nodes:j().int().nonnegative(),edges:j().int().nonnegative(),limitations:Se(D()).default([])}),yo={id:D().min(1),title:D().min(1),description:D(),coverage:W3},Q3=_e(["dependencies","routes","data","messaging","tests","provenance"]),X3=Ur("kind",[Ie({...yo,kind:qe("code"),model:Ng,communityDetails:eC(D(),Ng).default({})}),Ie({...yo,kind:qe("call"),root:D(),graph:f3}),Ie({...yo,kind:qe("impact"),root:D(),result:n3}),Ie({...yo,kind:qe("architecture"),model:P3}),Ie({...yo,kind:qe("history"),baseRevision:D(),targetRevision:D(),before:Ng,after:Ng}),Ie({...yo,kind:qe("affected"),root:D(),relations:Se(D()),depth:j().int().nonnegative(),model:Ng}),Ie({...yo,kind:qe("artifact"),lens:Q3,relations:Se(D()),model:Ng})]),$3=Ie({schema:qe(K3),title:D(),graphIdentity:D().min(1),defaultView:D(),views:Se(X3).min(1)}).superRefine((n,e)=>{const t=new Set;for(const[i,o]of n.views.entries())t.has(o.id)&&e.addIssue({code:"custom",path:["views",i,"id"],message:`duplicate workbench view id '${o.id}'`}),t.add(o.id);t.has(n.defaultView)||e.addIssue({code:"custom",path:["defaultView"],message:"defaultView must identify one included view"})});var P=tc();const q3=EN({__proto__:null,default:TN(P)},[P]);const J3=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),e_=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase()),av=n=>{const e=e_(n);return e.charAt(0).toUpperCase()+e.slice(1)},Av=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim(),t_=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var n_={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const i_=P.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:o="",children:r,iconNode:A,...I},l)=>P.createElement("svg",{ref:l,...n_,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:Av("lucide",o),...!r&&!t_(I)&&{"aria-hidden":"true"},...I},[...A.map(([c,h])=>P.createElement(c,h)),...Array.isArray(r)?r:[r]]));const Ee=(n,e)=>{const t=P.forwardRef(({className:i,...o},r)=>P.createElement(i_,{ref:r,iconNode:e,className:Av(`lucide-${J3(av(n))}`,`lucide-${n}`,i),...o}));return t.displayName=av(n),t};const Cv=Ee("arrow-down-to-line",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]);const g_=Ee("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);const o_=Ee("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);const s_=Ee("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);const Iv=Ee("arrow-up-from-line",[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]]);const r_=Ee("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const a_=Ee("badge-check",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const A_=Ee("box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);const C_=Ee("boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]);const I_=Ee("braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);const l_=Ee("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);const pc=Ee("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);const c_=Ee("circle-check",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const d_=Ee("circle-dot-dashed",[["path",{d:"M10.1 2.18a9.93 9.93 0 0 1 3.8 0",key:"1qdqn0"}],["path",{d:"M17.6 3.71a9.95 9.95 0 0 1 2.69 2.7",key:"1bq7p6"}],["path",{d:"M21.82 10.1a9.93 9.93 0 0 1 0 3.8",key:"1rlaqf"}],["path",{d:"M20.29 17.6a9.95 9.95 0 0 1-2.7 2.69",key:"1xk03u"}],["path",{d:"M13.9 21.82a9.94 9.94 0 0 1-3.8 0",key:"l7re25"}],["path",{d:"M6.4 20.29a9.95 9.95 0 0 1-2.69-2.7",key:"1v18p6"}],["path",{d:"M2.18 13.9a9.93 9.93 0 0 1 0-3.8",key:"xdo6bj"}],["path",{d:"M3.71 6.4a9.95 9.95 0 0 1 2.7-2.69",key:"1jjmaz"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);const lv=Ee("circle-question-mark",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const u_=Ee("compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);const gC=Ee("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);const h_=Ee("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const f_=Ee("file-code-2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);const p_=Ee("file-cog",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m2.305 15.53.923-.382",key:"yfp9st"}],["path",{d:"m3.228 12.852-.924-.383",key:"bckynb"}],["path",{d:"M4.677 21.5a2 2 0 0 0 1.313.5H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2.5",key:"1yo3oz"}],["path",{d:"m4.852 11.228-.383-.923",key:"1j88i9"}],["path",{d:"m4.852 16.772-.383.924",key:"sag1dv"}],["path",{d:"m7.148 11.228.383-.923",key:"rj39hk"}],["path",{d:"m7.53 17.696-.382-.924",key:"1uu5cs"}],["path",{d:"m8.772 12.852.923-.383",key:"13811l"}],["path",{d:"m8.772 15.148.923.383",key:"z1a5l0"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]]);const cv=Ee("file-image",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);const m_=Ee("focus",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);const dv=Ee("git-branch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);const uv=Ee("git-compare-arrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);const mc=Ee("git-fork",[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]]);const v_=Ee("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);const b_=Ee("layout-grid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);const y_=Ee("map-pin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);const w_=Ee("map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);const hv=Ee("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]);const x_=Ee("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);const S_=Ee("move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);const vc=Ee("network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);const E_=Ee("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);const T_=Ee("panel-left-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);const fv=Ee("panel-right-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);const O_=Ee("panel-right-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]]);const pv=Ee("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]);const N_=Ee("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]);const mv=Ee("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const D_=Ee("radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);const vv=Ee("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);const bv=Ee("route",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);const yv=Ee("scan-search",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]]);const wv=Ee("scan-text",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 8h8",key:"1jbsf9"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h6",key:"1vyc9m"}]]);const k_=Ee("search-code",[["path",{d:"m13 13.5 2-2.5-2-2.5",key:"1rvxrh"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M9 8.5 7 11l2 2.5",key:"6ffwbx"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);const xv=Ee("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);const M_=Ee("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const R_=Ee("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);const z_=Ee("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const __=Ee("signpost",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M18 6a2 2 0 0 1 1.387.56l2.307 2.22a1 1 0 0 1 0 1.44l-2.307 2.22A2 2 0 0 1 18 13H6a2 2 0 0 1-1.387-.56l-2.306-2.22a1 1 0 0 1 0-1.44l2.306-2.22A2 2 0 0 1 6 6z",key:"gqqp9m"}]]);const j_=Ee("sliders-horizontal",[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]]);const P_=Ee("tags",[["path",{d:"M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z",key:"16rjxf"}],["path",{d:"M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193",key:"178nd4"}],["circle",{cx:"10.5",cy:"6.5",r:".5",fill:"currentColor",key:"12ikhr"}]]);const Yr=Ee("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);const B_=Ee("waypoints",[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]]);const Z_=Ee("zoom-in",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);const L_=Ee("zoom-out",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Sv=new Set(["color","change","evidence"]),G_=new Set(["anchor","anchors","columnEnd","columnStart","community","communityName","community_name","degree","endByte","endColumn","endLine","lineEnd","lineStart","line_end","line_start","location","normLabel","norm_label","relationshipSite","relationship_site","size","sourceDigest","sourceFile","sourceHash","source_digest","source_file","source_hash","startByte","startColumn","startLine","wiringSite","wiring_site"]);function oC(n,e){const t=sC(n),i=sC(e);return{...t?{before:t}:{},...i?{after:i}:{},fields:yc(t,i)}}function Ev(n,e,t){const i=sC(n),o=sC(e),r=bc(n,t),A=bc(e,t);return{...i?{before:i}:{},...o?{after:o}:{},fields:yc(r,A)}}function F_(n,e){return bc(n,e)??{}}function V_(n,e=240){const t=n===void 0?"Not recorded":typeof n=="string"?n:JSON.stringify(n,null,Hr(n)?2:void 0)??String(n);return t.length<=e?{text:t,truncated:!1}:{text:`${t.slice(0,Math.max(0,e-1)).trimEnd()}…`,truncated:!0}}function sC(n){if(n)return Nv(n)}function bc(n,e){return n?Ov(n,e==="node"?new Set(["source"]):new Set(["id","key"])):void 0}function Tv(n){return Array.isArray(n)?n.map(Tv):Hr(n)?Ov(n):n}function Ov(n,e=new Set){return Object.fromEntries(Object.keys(n).filter(t=>!Sv.has(t)&&!G_.has(t)&&!e.has(t)).sort((t,i)=>t.localeCompare(i)).map(t=>[t,Tv(n[t])]))}function rC(n){return Array.isArray(n)?n.map(rC):Hr(n)?Nv(n):n}function Nv(n){return Object.fromEntries(Object.keys(n).filter(e=>!Sv.has(e)).sort((e,t)=>e.localeCompare(t)).map(e=>[e,rC(n[e])]))}function yc(n,e,t=""){const i=new Set([...Object.keys(n??{}),...Object.keys(e??{})]),o=[];for(const r of[...i].sort((A,I)=>A.localeCompare(I))){const A=t?`${t}.${r}`:r,I=n?.[r],l=e?.[r];Hr(I)&&Hr(l)?o.push(...yc(I,l,A)):U_(I,l)||o.push({field:A,...I!==void 0?{before:I}:{},...l!==void 0?{after:l}:{}})}return o}function U_(n,e){return JSON.stringify(rC(n))===JSON.stringify(rC(e))}function Hr(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Y_({node:n,edges:e,nodes:t,sourceRevisions:i,onFocus:o,onOpenSource:r}){const A=Mv(n.evidence?.before),I=Mv(n.evidence?.after);return f.jsxs(f.Fragment,{children:[n.evidence?.fields.length?f.jsxs("section",{className:"compass-record-evidence","aria-labelledby":"compass-node-changes-title",children:[f.jsxs("div",{className:"compass-evidence-heading",children:[f.jsx("h3",{id:"compass-node-changes-title",children:H_(n.change)}),f.jsxs("span",{children:[n.evidence.fields.length," fields"]})]}),f.jsx(Dv,{fields:n.evidence.fields}),n.change==="changed"&&(A||I)&&f.jsxs("div",{className:"compass-evidence-source-actions",children:[A&&f.jsxs("button",{type:"button",onClick:()=>r(A,i?.before),children:[f.jsx(gC,{"aria-hidden":"true"}),"Open before"]}),I&&f.jsxs("button",{type:"button",onClick:()=>r(I,i?.after),children:[f.jsx(gC,{"aria-hidden":"true"}),"Open after"]})]})]}):null,f.jsxs("section",{className:"compass-relationship-evidence","aria-labelledby":"compass-relationships-title",children:[f.jsxs("div",{className:"compass-neighbors-heading",children:[f.jsx("span",{id:"compass-relationships-title",children:"Relationships"}),f.jsx("strong",{children:e.length})]}),e.length?f.jsx("div",{className:"compass-relationship-list",children:e.map(l=>{const c=l.source===n.id?l.target:l.source,h=t.get(c);return f.jsxs("details",{children:[f.jsxs("summary",{children:[f.jsx("span",{className:"compass-change-badge","data-change":l.change,children:Rv(l.change)}),f.jsx("span",{className:"compass-relationship-target",children:h?.label??c}),f.jsx("small",{children:l.relation}),l.confidence&&f.jsx("i",{children:l.confidence})]}),f.jsxs("div",{className:"compass-relationship-detail",children:[l.change==="changed"&&l.evidence?.fields.length?f.jsx(Dv,{fields:l.evidence.fields}):f.jsxs("p",{children:[Rv(l.change)," relationship: ",l.source," → ",l.target]}),f.jsxs("button",{type:"button",onClick:()=>o(c),children:["Focus ",h?.label??c]})]})]},l.id)})}):f.jsx("span",{className:"compass-empty",children:"No connected relationships"})]})]})}function Dv({fields:n}){return f.jsx("div",{className:"compass-field-table-wrap",children:f.jsxs("table",{className:"compass-field-table",children:[f.jsx("thead",{children:f.jsxs("tr",{children:[f.jsx("th",{children:"Field"}),f.jsx("th",{children:"Before"}),f.jsx("th",{children:"After"})]})}),f.jsx("tbody",{children:n.map(e=>f.jsxs("tr",{children:[f.jsx("th",{scope:"row",children:e.field}),f.jsx(kv,{value:e.before}),f.jsx(kv,{value:e.after})]},e.field))})]})})}function kv({value:n}){const e=V_(n);return f.jsxs("td",{children:[f.jsx("code",{children:e.text}),e.truncated&&f.jsx("span",{className:"compass-value-truncated",children:"Value shortened"})]})}function Mv(n){const e=fc.safeParse(n?.source);return e.success?e.data:void 0}function Rv(n){return!n||n==="unchanged"?"Context":`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`}function H_(n){return n==="added"?"Added symbol metadata":n==="removed"?"Removed symbol metadata":"What changed"}const zv=100,_v={changed:0,added:1,removed:2,unchanged:3};function K_({nodes:n,query:e,selectedId:t,onFocus:i}){const[o,r]=P.useState(!1),A=e.trim().toLocaleLowerCase(),I=n.filter(c=>c.change&&c.change!=="unchanged").filter(c=>!A||c.label.toLocaleLowerCase().includes(A)||c.kind?.toLocaleLowerCase().includes(A)||c.source?.file.toLocaleLowerCase().includes(A)).sort((c,h)=>_v[c.change??"unchanged"]-_v[h.change??"unchanged"]||c.label.localeCompare(h.label)||c.id.localeCompare(h.id)),l=o?I:I.slice(0,zv);return f.jsxs("section",{className:"compass-changed-symbols","aria-labelledby":"compass-changed-symbols-title",children:[f.jsxs("div",{className:"compass-section-heading",children:[f.jsx("h2",{id:"compass-changed-symbols-title",children:"Changed symbols"}),f.jsx("span",{children:I.length})]}),l.length?f.jsx("div",{className:"compass-changed-symbol-list",children:l.map(c=>f.jsxs("button",{type:"button","aria-pressed":c.id===t,"data-change":c.change,onClick:()=>i(c.id),children:[f.jsx("span",{className:"compass-changed-symbol-status",children:W_(c.change)}),f.jsx("strong",{children:c.label}),f.jsx("small",{children:c.source?.file??c.kind??"Graph symbol"})]},c.id))}):f.jsx("p",{className:"compass-empty",children:A?"No affected symbols match this search.":"No symbol changes."}),!o&&I.length>zv&&f.jsxs("button",{className:"compass-changed-symbol-expand",type:"button",onClick:()=>r(!0),children:["Show all ",I.length.toLocaleString()," affected symbols"]})]})}function W_(n){return!n||n==="unchanged"?"Context":`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`}function jv({evidence:n,diagnostics:e=[],truncated:t=!1,title:i="Trust evidence",onOpenSource:o}){return!n.length&&!e.length&&!t?null:f.jsxs("section",{className:"compass-code-evidence","aria-label":i,children:[f.jsxs("div",{className:"compass-evidence-heading",children:[f.jsx("h3",{children:i}),f.jsxs("span",{children:[n.length," ",n.length===1?"record":"records"]})]}),t&&f.jsxs("p",{className:"compass-code-diagnostic","data-severity":"warning",role:"status",children:[f.jsx(Yr,{"aria-hidden":"true"}),"Results reached a configured limit. Narrow the query or raise one bound."]}),e.map(r=>f.jsxs("p",{className:"compass-code-diagnostic","data-severity":r.code==="no_match"?"info":"warning",role:"status",children:[r.code==="no_match"?f.jsx(lv,{"aria-hidden":"true"}):f.jsx(Yr,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:$_(r.code)}),r.message]})]},`${r.code}:${r.message}`)),f.jsx("div",{className:"compass-code-evidence-ledger",children:n.map((r,A)=>{const I=X_(r),l=r.wiringSite??r.anchor;return f.jsxs("article",{className:"compass-code-evidence-entry","data-status":I.key,children:[f.jsx("span",{className:"compass-code-evidence-icon","aria-hidden":"true",children:f.jsx(Q_,{item:r})}),f.jsxs("div",{className:"compass-code-evidence-copy",children:[f.jsxs("div",{className:"compass-code-evidence-status",children:[f.jsx("strong",{children:I.label}),f.jsx("span",{children:r.layer==="program_ir"?"Program IR":"Code graph"})]}),f.jsxs("dl",{children:[f.jsxs("div",{children:[f.jsx("dt",{children:"Extractor"}),f.jsx("dd",{children:r.extractor})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Confidence"}),f.jsx("dd",{children:r.confidence})]}),r.rule&&f.jsxs("div",{children:[f.jsx("dt",{children:"Rule"}),f.jsx("dd",{children:r.rule})]})]}),l&&(o?f.jsxs("button",{className:"compass-code-evidence-source",type:"button",onClick:()=>o(l),children:[f.jsx(gC,{"aria-hidden":"true"}),Pv(r,l)]}):f.jsx("span",{className:"compass-code-evidence-source",children:Pv(r,l)})),r.candidates.length>0&&f.jsxs("div",{className:"compass-code-candidates",children:[f.jsx("span",{children:"Retained candidates"}),f.jsx("ul",{children:r.candidates.map(c=>f.jsxs("li",{children:[f.jsx("code",{children:c.nodeId}),f.jsx("span",{children:c.reason}),f.jsx("small",{children:c.confidence})]},`${c.nodeId}:${c.reason}`))})]})]})]},`${r.layer}:${r.extractor}:${A}`)})})]})}function Q_({item:n}){return n.resolution==="unresolved"?f.jsx(lv,{}):n.resolution==="ambiguous"||n.confidence==="ambiguous"?f.jsx(Yr,{}):n.origin==="heuristic"?f.jsx(mc,{}):n.origin==="config"?f.jsx(p_,{}):n.origin==="convention"?f.jsx(__,{}):f.jsx(a_,{})}function X_(n){return n.resolution==="unresolved"?{key:"unresolved",label:"Unresolved"}:n.resolution==="ambiguous"||n.confidence==="ambiguous"?{key:"ambiguous",label:"Ambiguous"}:n.origin==="heuristic"?{key:"heuristic",label:"Heuristic"}:n.origin==="config"?{key:"config",label:"Configuration"}:n.origin==="convention"?{key:"convention",label:"Convention"}:{key:"exact",label:"Exact"}}function Pv(n,e){return`${n.origin==="heuristic"?"Wired at":"Evidence at"} ${e.file}:${e.startLine}`}function $_(n){return`${n.replaceAll("_"," ")}: `}const hs=[{id:"combined",label:"Combined"},{id:"native",label:"Native"},{id:"ocr",label:"OCR evidence"}];function q_(n,e){if(!e.document)return;const t=e.source?.file,i=n.nodes.filter(A=>A.document?t===void 0||A.source?.file===t:!1),o=i.find(A=>A.document?.role==="root")??(e.document.role==="root"?e:void 0),r=i.filter(A=>A.document?.role==="block");if(e.document.role==="block"&&!r.some(A=>A.id===e.id)&&r.push(e),!(!o&&r.length===0))return r.sort(oj),{...t!==void 0?{sourceFile:t}:{},...o?{root:o}:{},blocks:r}}function J_({context:n,selectedId:e,onFocus:t}){const[i,o]=P.useState("combined"),r=P.useMemo(()=>n.blocks.filter(wc),[n.blocks]),A=P.useMemo(()=>n.blocks.filter(y=>!wc(y)),[n.blocks]),[I,l]=P.useState(e&&r.some(y=>y.id===e)?e:r[0]?.id);P.useEffect(()=>{o("combined"),l(e&&r.some(y=>y.id===e)?e:r[0]?.id)},[n.sourceFile,r,e]);const c=i==="ocr"?r:i==="native"?A:n.blocks,h=n.root?.document,p=h?.visualCoverage??(r.length>0?"complete":"not_requested"),m=h?.ocrMode??(r.length>0?"auto":"off"),v=Zv(h?.ocrProfile)??r.map(y=>Zv(xc(y)?.profile)).find(Boolean),x=p==="failed"?"failed":p==="partial"?"partial":h?.complete===!1?"incomplete":void 0,O=r.find(y=>y.id===I);return f.jsxs("section",{className:"compass-document-evidence","aria-labelledby":"compass-document-evidence-title",children:[f.jsxs("header",{className:"compass-document-evidence-header",children:[f.jsxs("div",{className:"compass-document-evidence-heading",children:[f.jsx("span",{className:"compass-document-evidence-mark","aria-hidden":"true",children:f.jsx(wv,{})}),f.jsxs("span",{children:[f.jsx("small",{children:"Document evidence"}),f.jsx("h3",{id:"compass-document-evidence-title",children:rj(n.sourceFile,h?.format)})]})]}),f.jsx(ej,{mode:m,coverage:p,...v?{profile:v}:{}})]}),x&&f.jsxs("div",{className:"compass-document-warning","data-status":x,role:"alert",children:[f.jsx(R_,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:x==="failed"?"OCR could not complete":x==="partial"?"OCR coverage is partial":"Document extraction is incomplete"}),f.jsx("small",{children:x==="incomplete"?"Compass retained the available evidence; review the document diagnostics before relying on it as complete.":"Native text is still available. Some visual regions could not be processed."})]})]}),f.jsx("div",{className:"compass-document-tabs",role:"tablist","aria-label":"Document evidence views",children:hs.map((y,T)=>{const S=y.id==="ocr"?r.length:y.id==="native"?A.length:n.blocks.length,_=i===y.id;return f.jsxs("button",{id:`compass-document-tab-${y.id}`,className:"compass-document-tab",type:"button",role:"tab","aria-selected":_,"aria-controls":"compass-document-panel",tabIndex:_?0:-1,onClick:()=>o(y.id),onKeyDown:B=>{const Q=B.key==="ArrowRight"?(T+1)%hs.length:B.key==="ArrowLeft"?(T-1+hs.length)%hs.length:B.key==="Home"?0:B.key==="End"?hs.length-1:void 0;if(Q===void 0)return;B.preventDefault();const te=hs[Q];te&&(o(te.id),document.getElementById(`compass-document-tab-${te.id}`)?.focus())},children:[y.label,f.jsx("span",{children:S})]},y.id)})}),f.jsx("div",{id:"compass-document-panel",className:"compass-document-tab-panel",role:"tabpanel","aria-labelledby":`compass-document-tab-${i}`,tabIndex:0,children:c.length>0?f.jsx("div",{className:"compass-document-block-list",children:c.map(y=>f.jsx(tj,{block:y,active:y.id===e,onClick:()=>{wc(y)&&l(y.id),t(y.id)}},y.id))}):f.jsxs("div",{className:"compass-document-empty",children:[f.jsx(cv,{"aria-hidden":"true"}),f.jsx("strong",{children:i==="ocr"?"No OCR evidence":"No document blocks"}),f.jsx("span",{children:i==="ocr"?"Run extraction with a managed OCR profile to inspect visual text.":"This document did not publish readable native blocks."})]})}),O&&f.jsx(gj,{block:O,siblings:r,...h?.previews?{previews:h.previews}:{},onFocus:y=>{l(y),t(y)}}),!O&&h?.previews&&h.previews.length>0&&f.jsx(ij,{previews:h.previews})]})}function ej({mode:n,coverage:e,profile:t}){const i=e==="complete",o=n!=="off",r=`OCR ${o?Lv(n):"Off"} · ${o?Gv(e):"Native only"}${t?` · ${t}`:""}`;return f.jsxs("span",{className:"compass-ocr-status-chip","data-status":e,role:"status","aria-label":r,title:r,children:[i?f.jsx(c_,{"aria-hidden":"true"}):f.jsx(Yr,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsxs("strong",{children:["OCR ",o?Lv(n):"Off"]}),f.jsx("small",{children:o?Gv(e):"Native only"})]}),t&&f.jsx("em",{children:t})]})}function tj({block:n,active:e,onClick:t}){const i=xc(n),o=n.document?.text??n.label,r=n.document?.locator;return f.jsxs("button",{className:"compass-document-block","data-origin":i?"ocr":"native","data-active":e,type:"button","aria-pressed":e,onClick:t,children:[f.jsxs("span",{className:"compass-document-block-topline",children:[f.jsxs("span",{className:"compass-document-block-kind",children:[i?f.jsx(wv,{"aria-hidden":"true"}):f.jsx(cv,{"aria-hidden":"true"}),i?"OCR evidence":aj(n.document?.kind)]}),i&&f.jsx(nj,{confidence:i.confidence_bps})]}),f.jsx("span",{className:"compass-document-block-text",children:o||"(empty block)"}),f.jsxs("span",{className:"compass-document-block-locator",children:[f.jsx(y_,{"aria-hidden":"true"}),fs(r),i&&f.jsx(h_,{"aria-hidden":"true"})]})]})}function nj({confidence:n}){const e=Math.max(0,Math.min(100,n/100)),t=e>=85?"high":e>=60?"medium":"low";return f.jsxs("span",{className:"compass-ocr-confidence","data-confidence":t,children:[e.toFixed(2),"%"]})}function ij({previews:n}){const[e,t]=P.useState(0);P.useEffect(()=>{t(o=>Math.min(o,Math.max(0,n.length-1)))},[n.length]);const i=n[e];return i?f.jsxs("div",{className:"compass-ocr-preview compass-document-preview-gallery","aria-label":"Document preview",children:[f.jsxs("header",{children:[f.jsxs("span",{children:[f.jsx("strong",{children:i.label}),f.jsxs("small",{children:[fs(i.locator)," · Normalized preview"]})]}),n.length>1&&f.jsxs("span",{className:"compass-document-preview-controls",children:[f.jsx("button",{type:"button","aria-label":"Previous document preview",disabled:e===0,onClick:()=>t(o=>Math.max(0,o-1)),children:f.jsx(l_,{"aria-hidden":"true"})}),f.jsxs("span",{children:[e+1," / ",n.length]}),f.jsx("button",{type:"button","aria-label":"Next document preview",disabled:e===n.length-1,onClick:()=>t(o=>Math.min(n.length-1,o+1)),children:f.jsx(pc,{"aria-hidden":"true"})})]})]}),f.jsx("div",{className:"compass-document-preview-stage",children:f.jsx("img",{className:"compass-document-preview-image",src:Fv(i.svg),alt:`${i.label} document preview`})}),f.jsx("p",{children:"Compass generated a bounded local snapshot. Native text remains the authoritative evidence."})]}):null}function gj({block:n,siblings:e,previews:t,onFocus:i}){const o=n.document.locator,r=aC(o.width),A=aC(o.height),I=o.candidate_id,l=e.filter(h=>{const p=h.document.locator;return p.candidate_id===I&&p.width===o.width&&p.height===o.height});if(!r||!A)return null;const c=Aj(t,o);return f.jsxs("div",{className:"compass-ocr-preview","aria-label":"OCR region preview",children:[f.jsxs("header",{children:[f.jsxs("span",{children:[f.jsx("strong",{children:c?.label??"Visual region"}),f.jsxs("small",{children:[fs(o.owner)," · ",r," × ",A,"px"]})]}),f.jsxs("span",{className:"compass-ocr-preview-key",children:[f.jsx("i",{}),"OCR boxes",c?" · normalized preview":""]})]}),c?f.jsxs("div",{className:"compass-document-preview-stage",children:[f.jsx("img",{className:"compass-document-preview-image",src:Fv(c.svg),alt:`${c.label} document preview`}),f.jsx("svg",{className:"compass-document-preview-overlay",viewBox:`0 0 ${c.width} ${c.height}`,role:"img","aria-label":`OCR bounding boxes over ${c.label}`,preserveAspectRatio:"none",children:l.map(h=>{const p=Cj(h.document.locator,c);return p?Bv(h,p,h.id===n.id,i):null})})]}):f.jsxs("svg",{className:"compass-ocr-preview-canvas",viewBox:`0 0 ${r} ${A}`,role:"img","aria-label":`OCR bounding boxes for ${fs(o.owner)}`,children:[f.jsx("defs",{children:f.jsx("pattern",{id:"compass-ocr-preview-grid",width:"32",height:"32",patternUnits:"userSpaceOnUse",children:f.jsx("path",{d:"M 32 0 L 0 0 0 32",fill:"none",stroke:"currentColor",strokeOpacity:"0.12",strokeWidth:"1"})})}),f.jsx("rect",{width:r,height:A,fill:"var(--compass-ocr-preview-surface)"}),f.jsx("rect",{width:r,height:A,fill:"url(#compass-ocr-preview-grid)"}),l.map(h=>{const p=h.document.locator,m=lj(p.polygon,r,A);return m?Bv(h,m,h.id===n.id,i):null})]}),f.jsx("p",{children:c?"OCR boxes are mapped to the embedded image region. Click a box to inspect its text and confidence.":"Click a highlighted region to inspect its text and confidence."})]})}function Bv(n,e,t,i){return f.jsx("polygon",{className:"compass-ocr-preview-box","data-active":t,points:e,role:"button",tabIndex:0,"aria-label":`${n.document.text??n.label} · ${fs(n.document.locator)}`,onClick:()=>i(n.id),onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),i(n.id))},children:f.jsx("title",{children:n.document.text??n.label})},n.id)}function wc(n){return xc(n)!==void 0&&n.document?.locator?.kind==="ocr"}function xc(n){return n.document?.origin?.kind==="ocr"?n.document.origin:void 0}function oj(n,e){const t=n.document?.ordinal??Number.MAX_SAFE_INTEGER,i=e.document?.ordinal??Number.MAX_SAFE_INTEGER;return t-i||n.id.localeCompare(e.id)}function Zv(n){const e=n?.profile;return typeof e=="string"?sj(e):void 0}function sj(n){return n.replace(/^pp-/,"PP-").replace(/ocrv(\d+)/i,"OCRv$1").replace(/-(small|medium)$/i,(e,t)=>` ${t[0]?.toUpperCase()}${t.slice(1)}`)}function Lv(n){return n.length>0?`${n[0]?.toUpperCase()}${n.slice(1)}`:"Off"}function Gv(n){return{complete:"Complete",partial:"Partial coverage",failed:"Failed",not_requested:"Not requested"}[n]??"Unknown"}function rj(n,e){const t=n?.split(/[\\/]/).pop()??"Document";return e?`${t} · ${e.toUpperCase()}`:t}function aj(n){return n?n.replaceAll("_"," ").replace(/\b\w/g,e=>e.toUpperCase()):"Native text"}function fs(n){if(!n)return"Location unavailable";switch(n.kind){case"ocr":{const e=_t(n,"owner"),t=jn(_t(n,"occurrence"))??0;return`${fs(Vv(e)?e:void 0)} · Region ${t+1}`}case"pdf":return`Page ${jn(_t(n,"page"))??"?"}`;case"page":return`Page ${jn(_t(n,"page"))??"?"}`;case"slide":return`Slide ${jn(_t(n,"slide"))??"?"}${_t(n,"shape")!==void 0?` · Shape ${String(_t(n,"shape"))}`:""}`;case"spreadsheet":{const e=_t(n,"sheet");return`${typeof e=="string"?e:"Sheet"}!${Ij(jn(_t(n,"column"))??1)}${jn(_t(n,"row"))??"?"}`}case"package":{const e=_t(n,"part"),t=_t(n,"path"),i=typeof e=="string"?e:"Package part";if(/\/(?:media|embeddings)\//i.test(i)||/\.(?:avif|bmp|gif|jpe?g|png|tiff?|webp)$/i.test(i))return"Embedded image";const o=i.split(/[\\/]/).pop()||"Package part";return typeof t=="string"&&t.length>0?`${o} · ${t}`:o}case"text_range":{const e=jn(_t(n,"start_line")),t=jn(_t(n,"end_line"));return e!==void 0?`Lines ${e}${t!==void 0&&t!==e?`–${t}`:""}`:"Text range"}default:return"Document location"}}function Aj(n,e){if(!n||n.length===0)return;const t=e.candidate_id;if(t){const o=n.find(r=>r.regions.some(A=>A.candidate_id===t));if(o)return o}const i=e.owner;if(Vv(i)){if(i.kind==="slide"){const o=jn(_t(i,"slide")),r=n.find(A=>A.kind==="slide"&&A.locator.kind==="slide"&&jn(_t(A.locator,"slide"))===o);if(r)return r}if(i.kind==="spreadsheet"){const o=_t(i,"sheet"),r=n.find(A=>A.kind==="sheet"&&A.locator.kind==="spreadsheet"&&_t(A.locator,"sheet")===o);if(r)return r}}return n[0]}function Fv(n){return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`}function Cj(n,e){const t=n.candidate_id,i=t?e.regions.find(I=>I.candidate_id===t):void 0,o=aC(n.width),r=aC(n.height);if(!i||!o||!r||!Array.isArray(n.polygon))return;const A=n.polygon.slice(0,256).flatMap(I=>{if(typeof I!="object"||I===null)return[];const l=jn(_t(I,"x")),c=jn(_t(I,"y"));if(l===void 0||c===void 0)return[];const h=i.x+AC(l/o,0,1)*i.width,p=i.y+AC(c/r,0,1)*i.height;return[`${h},${p}`]});return A.length>=3?A.join(" "):void 0}function _t(n,e){return n[e]}function Vv(n){return typeof n=="object"&&n!==null&&typeof _t(n,"kind")=="string"}function jn(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ij(n){let e=Math.max(1,Math.floor(n)),t="";for(;e>0;){const i=(e-1)%26;t=String.fromCharCode(65+i)+t,e=Math.floor((e-1)/26)}return t}function aC(n){return n!==void 0&&Number.isFinite(n)&&n>0&&n<=1e4?n:void 0}function lj(n,e,t){if(!Array.isArray(n))return;const i=n.slice(0,256).flatMap(o=>{if(typeof o!="object"||o===null)return[];const r=jn(_t(o,"x")),A=jn(_t(o,"y"));return r!==void 0&&A!==void 0?[`${AC(r,0,e)},${AC(A,0,t)}`]:[]});return i.length>=3?i.join(" "):void 0}function AC(n,e,t){return Math.max(e,Math.min(t,n))}function Uv(n){return Hv(n.source)}function Yv(n){return Hv(n.relationshipSite)}function Hv(n){return n?.file.trim()&&(n.startLine!==void 0||n.endLine!==void 0||n.startByte!==void 0||n.endByte!==void 0)?n:void 0}const Kv=200;function cj(n,e,t){const i=new Map,o=new Map,r=(I,l,c)=>{const h=t.get(l);if(!h)return;const p=I.get(l);p?p.edges.push(c):I.set(l,{node:h,edges:[c]})};for(const I of e)I.target===n&&r(i,I.source,I),I.source===n&&r(o,I.target,I);const A=I=>[...I.values()].map(l=>({...l,edges:l.edges.sort((c,h)=>c.relation.localeCompare(h.relation)||c.id.localeCompare(h.id))})).sort((l,c)=>l.node.label.localeCompare(c.node.label)||l.node.id.localeCompare(c.node.id));return{incoming:A(i),outgoing:A(o)}}function dj(n){const e=new Map;for(const t of n){const i=t.relation||"related";e.set(i,(e.get(i)??0)+(t.weight??1))}return[...e.entries()].sort(([t],[i])=>t.localeCompare(i)).map(([t,i])=>i>1?`${t} ×${i}`:t).join(" · ")}function Wv({direction:n,groups:e,communityColors:t,onFocus:i}){const o=n==="incoming",r=e.reduce((c,h)=>c+h.edges.length,0),A=o?"Incoming":"Outgoing",I=o?"Nodes that point to this node":"Nodes this node points to",l=o?Cv:Iv;return f.jsxs("section",{className:"compass-direction-group","data-direction":n,children:[f.jsxs("div",{className:"compass-direction-heading",children:[f.jsx("span",{className:"compass-direction-icon","aria-hidden":"true",children:f.jsx(l,{})}),f.jsxs("span",{className:"compass-direction-copy",children:[f.jsx("strong",{children:A}),f.jsx("small",{children:I})]}),f.jsxs("span",{className:"compass-direction-count",children:[f.jsx("strong",{children:e.length}),f.jsxs("small",{children:[r," ",r===1?"edge":"edges"]})]})]}),f.jsx("div",{className:"compass-direction-list",children:e.length?e.map(c=>{const h=dj(c.edges);return f.jsxs("button",{type:"button",className:"compass-direction-link",title:`Focus ${c.node.label}`,"aria-label":`Focus ${c.node.label}; ${A.toLocaleLowerCase()}; ${h}`,onClick:()=>i(c.node.id),children:[f.jsx("span",{className:"compass-neighbor-dot","aria-hidden":"true",style:{background:c.node.color?.background??t.get(c.node.community)??"var(--border)"}}),f.jsxs("span",{className:"compass-direction-node",children:[f.jsx("strong",{children:c.node.label}),f.jsx("small",{children:h})]}),f.jsx(pc,{"aria-hidden":"true"})]},c.node.id)}):f.jsx("span",{className:"compass-direction-empty",children:o?"No incoming relationships":"No outgoing relationships"})})]})}function uj(n,e){const t=e.trim().toLocaleLowerCase();return(t?n.filter(o=>o.label.toLocaleLowerCase().includes(t)||String(o.id).includes(t)):n).slice(0,Kv)}function hj(n){const e=n.source?.startLine,t=n.source?.endLine;if(e!==void 0)return t!==void 0&&t!==e?`${e}–${t}`:String(e)}function Qv(n){const e=n.source?.startLine,t=n.source?.endLine;if(e!==void 0)return t!==void 0&&t!==e?{text:`Lines ${e}–${t}`,action:`at lines ${e}–${t}`}:{text:`Line ${e}`,action:`at line ${e}`};const i=n.source?.startByte,o=n.source?.endByte;if(i!==void 0)return o!==void 0&&o!==i?{text:`Bytes ${i}–${o}`,action:`at bytes ${i}–${o}`}:{text:`Byte ${i}`,action:`at byte ${i}`}}function Xv(n,e){const t=Qv(n);return`Open source ${e.file}${t?` ${t.action}`:""}`}function $v(n){return n==="unchanged"?"Context":n?`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`:void 0}function fj(n){if(n)return{added:"var(--vscode-gitDecoration-addedResourceForeground, #2ea043)",removed:"var(--vscode-gitDecoration-deletedResourceForeground, #f85149)",changed:"var(--vscode-gitDecoration-modifiedResourceForeground, #d29922)",unchanged:"var(--vscode-descriptionForeground, #6e7781)"}[n]}function pj({model:n,selected:e,neighbors:t,connectedEdges:i,query:o,matches:r,hiddenCommunities:A,comparisonMode:I,sourceRevisions:l,queryResult:c,renderedEdgeCount:h,showHeader:p,onQueryChange:m,onFocus:v,onOpenSource:x,onOpenCommunity:O,onQueryNode:y,onToggleCommunity:T,onSetAllVisible:S,collapsed:_,onToggleCollapsed:B}){const[Q,te]=P.useState(0),V=e?Uv(e):void 0,U=e?hj(e):void 0,Ce=e?Qv(e):void 0,Te=P.useMemo(()=>{const E=new Map;for(const G of n.nodes)E.set(G.community,(E.get(G.community)??0)+1);return E},[n.nodes]),Ze=A.size===0,ye=P.useMemo(()=>new Map(n.nodes.map(E=>[E.id,E])),[n.nodes]),Fe=P.useMemo(()=>new Map(n.communities.map(E=>[E.id,E.color])),[n.communities]),Ge=P.useMemo(()=>e?cj(e.id,i,ye):{incoming:[],outgoing:[]},[i,ye,e?.id]),le=e?c?.nodes.find(E=>E.id===e.id):void 0,M=e?q_(n,e):void 0,W=le?.evidence??e?.codeEvidence??[],oe=e?c?c.edges.filter(E=>E.source===e.id||E.target===e.id).flatMap(E=>E.evidence):i.flatMap(E=>E.codeEvidence??[]):[],se=E=>{v(E.id),m(""),te(0)},J=E=>{!r.length&&E.key!=="Escape"||(E.key==="ArrowDown"?(E.preventDefault(),te((Q+1)%r.length)):E.key==="ArrowUp"?(E.preventDefault(),te((Q-1+r.length)%r.length)):E.key==="Enter"&&r[Q]?(E.preventDefault(),se(r[Q])):E.key==="Escape"&&(m(""),te(0)))};return _?f.jsxs("aside",{className:"compass-graph-inspector compass-graph-inspector-collapsed","aria-label":"Graph inspector",children:[f.jsx("button",{className:"compass-inspector-disclosure compass-inspector-expand",type:"button","aria-label":"Expand graph inspector",title:"Expand graph inspector",onClick:B,children:f.jsx(O_,{"aria-hidden":"true"})}),f.jsx("span",{className:"compass-inspector-rail-label","aria-hidden":"true",children:"Inspector"})]}):f.jsxs("aside",{className:"compass-graph-inspector","aria-label":"Graph inspector",children:[p&&f.jsxs("header",{className:"compass-inspector-header",children:[f.jsx("span",{className:"compass-product-mark","aria-hidden":"true",children:f.jsx(u_,{})}),f.jsxs("span",{className:"compass-inspector-title",children:[f.jsx("strong",{children:"Compass"}),f.jsx("small",{children:n.title})]}),f.jsx("button",{className:"compass-inspector-disclosure",type:"button","aria-label":"Collapse graph inspector",title:"Collapse graph inspector",onClick:B,children:f.jsx(fv,{"aria-hidden":"true"})})]}),f.jsxs("div",{className:"compass-inspector-search",role:"search",children:[f.jsx("label",{className:"sr-only",htmlFor:"compass-node-search",children:"Search graph nodes"}),f.jsxs("div",{className:"compass-inspector-search-row",children:[f.jsxs("div",{className:"compass-search-field",children:[f.jsx(xv,{"aria-hidden":"true"}),f.jsx("input",{id:"compass-node-search",type:"search",role:"combobox",value:o,placeholder:"Search nodes and files",autoComplete:"off","aria-controls":"compass-search-results","aria-autocomplete":"list","aria-expanded":r.length>0,"aria-activedescendant":r[Q]?`compass-search-result-${Q}`:void 0,onChange:E=>{m(E.target.value),te(0)},onKeyDown:J})]}),!p&&f.jsx("button",{className:"compass-inspector-disclosure compass-inspector-search-disclosure",type:"button","aria-label":"Collapse graph inspector",title:"Collapse graph inspector",onClick:B,children:f.jsx(fv,{"aria-hidden":"true"})})]}),r.length>0&&f.jsx("div",{id:"compass-search-results",className:"compass-search-results",role:"listbox","aria-label":"Matching nodes",children:r.map((E,G)=>f.jsxs("button",{id:`compass-search-result-${G}`,type:"button",role:"option","aria-selected":G===Q,className:"compass-search-item",onMouseEnter:()=>te(G),onClick:()=>se(E),children:[f.jsx("strong",{children:E.label}),f.jsx("span",{children:E.source?.file??E.kind??"Graph node"})]},E.id))})]}),f.jsxs("section",{className:"compass-info-panel","aria-labelledby":"compass-info-title",children:[f.jsxs("div",{className:"compass-section-heading",children:[f.jsx("h2",{id:"compass-info-title",children:"Inspector"}),f.jsx("span",{children:e?"Pinned":"Node details"})]}),e?f.jsxs("div",{className:"compass-info-content",children:[f.jsxs("div",{className:"compass-node-identity",children:[f.jsx("span",{className:"compass-node-swatch","aria-hidden":"true",style:{background:fj(e.change)??e.color?.background??Fe.get(e.community)}}),f.jsxs("span",{children:[f.jsx("strong",{children:e.label}),f.jsx("small",{children:e.kind??"Symbol"})]}),$v(e.change)&&f.jsx("span",{className:"compass-change-badge","data-change":e.change,children:$v(e.change)})]}),f.jsxs("dl",{className:"compass-metadata-grid",children:[f.jsxs("div",{children:[f.jsx("dt",{children:"Community"}),f.jsx("dd",{children:e.communityName??n.communities.find(E=>E.id===e.community)?.label??e.community})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Degree"}),f.jsx("dd",{children:e.degree??t.length})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Incoming"}),f.jsx("dd",{children:Ge.incoming.length})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Outgoing"}),f.jsx("dd",{children:Ge.outgoing.length})]}),e.language&&f.jsxs("div",{children:[f.jsx("dt",{children:"Language"}),f.jsx("dd",{children:e.language})]}),U&&f.jsxs("div",{children:[f.jsx("dt",{children:"Lines"}),f.jsx("dd",{children:U})]}),f.jsx("div",{className:"compass-metadata-wide compass-source-metadata","data-interactive":V!==void 0,children:V?f.jsxs(f.Fragment,{children:[f.jsx("dt",{className:"sr-only",children:"Source"}),f.jsx("dd",{children:f.jsxs("button",{className:"compass-source-card",type:"button","aria-label":Xv(e,V),title:Xv(e,V),onClick:()=>x(V,e.change==="removed"?l?.before:l?.after),children:[f.jsxs("span",{className:"compass-source-copy",children:[f.jsx("span",{className:"compass-source-eyebrow","aria-hidden":"true",children:"Source"}),f.jsx("span",{className:"compass-source-path",children:V.file}),Ce&&f.jsx("span",{className:"compass-source-range",children:Ce.text})]}),f.jsx(gC,{"aria-hidden":"true"})]})})]}):f.jsxs(f.Fragment,{children:[f.jsx("dt",{children:"Source"}),f.jsx("dd",{title:e.source?.file??"Not recorded",children:e.source?.file??"Not recorded"})]})})]}),e.signature&&f.jsx("code",{className:"compass-signature-block",children:e.signature}),M&&f.jsx(J_,{context:M,selectedId:e.id,onFocus:v}),y&&f.jsxs("section",{className:"compass-node-actions","aria-labelledby":"compass-node-actions-title",children:[f.jsxs("div",{className:"compass-inspector-subheading",children:[f.jsx("h3",{id:"compass-node-actions-title",children:"Actions"}),f.jsx("span",{children:"3 available"})]}),f.jsxs("div",{className:"compass-code-query-actions","aria-label":"Code graph queries",children:[f.jsxs("button",{type:"button",title:"Find code that calls this node",onClick:()=>y("callers",e.id),children:[f.jsx(Cv,{"aria-hidden":"true"}),f.jsx("span",{children:"Callers"})]}),f.jsxs("button",{type:"button",title:"Find code called by this node",onClick:()=>y("callees",e.id),children:[f.jsx(Iv,{"aria-hidden":"true"}),f.jsx("span",{children:"Callees"})]}),f.jsxs("button",{type:"button",title:"Trace code affected by this node",onClick:()=>y("impact",e.id),children:[f.jsx(D_,{"aria-hidden":"true"}),f.jsx("span",{children:"Impact"})]})]})]}),f.jsx(jv,{evidence:W,diagnostics:c?.diagnostics,truncated:c?.truncated,title:"Node evidence",onOpenSource:x}),f.jsx(jv,{evidence:oe,title:"Relationship evidence",onOpenSource:x}),n.stats.aggregated&&e.memberCount!==void 0&&e.detailAvailable!==!1&&O&&f.jsxs("button",{className:"compass-inspector-action",type:"button",onClick:()=>O(e.community),children:[f.jsx("span",{className:"compass-inspector-action-icon","aria-hidden":"true",children:f.jsx(A_,{})}),f.jsxs("span",{className:"compass-inspector-action-copy",children:[f.jsx("strong",{children:I?"Inspect changes":"Open community"}),f.jsxs("small",{children:[e.memberCount.toLocaleString()," ",I?"current symbols":"members"]})]}),f.jsx(pc,{"aria-hidden":"true"})]}),n.stats.aggregated&&e.memberCount!==void 0&&e.detailAvailable===!1&&f.jsx("p",{className:"compass-empty",children:"This community detail was omitted to keep the standalone HTML export bounded. Open the graph in VS Code or export this community as JSON for full inspection."}),I?f.jsx(Y_,{node:e,edges:i,nodes:ye,sourceRevisions:l,onFocus:v,onOpenSource:x}):f.jsxs("section",{className:"compass-relationships","aria-labelledby":"compass-relationships-title",children:[f.jsxs("div",{className:"compass-inspector-subheading",children:[f.jsx("h3",{id:"compass-relationships-title",children:"Relationships"}),f.jsxs("span",{children:[i.length," ",i.length===1?"edge":"edges"]})]}),f.jsxs("div",{className:"compass-relationship-directions",children:[f.jsx(Wv,{direction:"incoming",groups:Ge.incoming,communityColors:Fe,onFocus:v}),f.jsx(Wv,{direction:"outgoing",groups:Ge.outgoing,communityColors:Fe,onFocus:v})]})]})]}):f.jsx("p",{className:"compass-empty",children:"Select a node to inspect its relationships."})]}),I&&!n.stats.aggregated&&f.jsx(K_,{nodes:n.nodes,query:o,selectedId:e?.id,onFocus:v}),n.effectiveGraph&&f.jsxs("section",{className:"compass-info-panel","aria-labelledby":"compass-agent-overlay-title",children:[f.jsxs("div",{className:"compass-section-heading",children:[f.jsx("h2",{id:"compass-agent-overlay-title",children:"Agent overlay"}),f.jsx("span",{children:"Exact revision"})]}),f.jsxs("dl",{className:"compass-metadata-grid",children:[f.jsxs("div",{children:[f.jsx("dt",{children:"Pinned profile"}),f.jsx("dd",{children:n.effectiveGraph.compositionProfile})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Retractions"}),f.jsx("dd",{children:n.effectiveGraph.retractions.total.toLocaleString()})]}),f.jsxs("div",{children:[f.jsx("dt",{children:"Omissions"}),f.jsx("dd",{children:n.effectiveGraph.omissions.total.toLocaleString()})]}),f.jsxs("div",{className:"compass-metadata-wide",children:[f.jsx("dt",{children:"Overlay revision"}),f.jsx("dd",{title:n.effectiveGraph.overlayRevision,children:f.jsx("code",{children:n.effectiveGraph.overlayRevision.slice(0,12)})})]})]}),n.effectiveGraph.retractions.examples.length>0&&f.jsxs("details",{children:[f.jsxs("summary",{children:["Retraction history",f.jsx("span",{children:n.effectiveGraph.retractions.examples.length})]}),f.jsx("ul",{children:n.effectiveGraph.retractions.examples.map(E=>f.jsxs("li",{children:[f.jsx("strong",{children:E.kind})," ",f.jsx("code",{children:E.id})," — ",E.reasonCode,": ",E.explanation]},`${E.kind}:${E.id}`))}),n.effectiveGraph.retractions.omittedExamples>0&&f.jsxs("p",{className:"compass-empty",children:[n.effectiveGraph.retractions.omittedExamples.toLocaleString()," additional Retractions omitted by the response bound."]})]}),f.jsx("p",{className:"compass-empty",children:"Changing augment or curated profile requires a new exact Effective Graph read; this viewer never relabels one identity as another."})]}),f.jsx("section",{className:"compass-community-panel","aria-labelledby":"compass-communities-title","data-secondary":I,children:I?f.jsxs("details",{children:[f.jsxs("summary",{id:"compass-communities-title",children:["Communities",f.jsx("span",{children:n.communities.length})]}),f.jsx(qv,{model:n,communityCounts:Te,hiddenCommunities:A,allVisible:Ze,onSetAllVisible:S,onToggleCommunity:T})]}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{id:"compass-communities-title",children:"Communities"}),f.jsx(qv,{model:n,communityCounts:Te,hiddenCommunities:A,allVisible:Ze,onSetAllVisible:S,onToggleCommunity:T})]})}),f.jsxs("footer",{className:"compass-graph-stats",children:[n.stats.nodes.toLocaleString()," nodes · ",n.stats.edges.toLocaleString()," edges",huj(n.communities,A),[n.communities,A]),c=P.useMemo(()=>{const h=A.trim().toLocaleLowerCase();return h?n.communities.filter(p=>p.label.toLocaleLowerCase().includes(h)||String(p.id).includes(h)).length:n.communities.length},[n.communities,A]);return f.jsxs("div",{className:"compass-community-controls",children:[f.jsxs("label",{className:"compass-community-control",children:[f.jsx("input",{type:"checkbox",checked:i,onChange:h=>o(h.target.checked)}),f.jsx("span",{children:"Select all"})]}),n.communities.length>Kv&&f.jsxs("label",{className:"compass-community-search",children:[f.jsx("span",{className:"sr-only",children:"Filter communities"}),f.jsx(xv,{"aria-hidden":"true"}),f.jsx("input",{type:"search",value:A,placeholder:"Filter communities",onChange:h=>I(h.target.value)})]}),f.jsx("div",{className:"compass-community-list",children:l.map(h=>{const p=!t.has(h.id);return f.jsxs("label",{className:"compass-community-item","data-hidden":!p,children:[f.jsx("input",{type:"checkbox",checked:p,onChange:()=>r(h.id)}),f.jsx("span",{className:"compass-community-dot","aria-hidden":"true",style:{background:h.color}}),f.jsx("span",{className:"compass-community-label",children:h.label}),f.jsx("small",{children:e.get(h.id)??0})]},h.id)})}),c>l.length&&f.jsxs("p",{className:"compass-community-limit",role:"status",children:["Showing ",l.length.toLocaleString()," of"," ",c.toLocaleString()," communities. Filter to find another community."]})]})}function mj({className:n="compass-load-logo"}){return f.jsx("svg",{className:n,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:f.jsx("path",{fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd",d:"M3.554 21.529c1.797 1.221 4.943-.038 11.236-2.554 1.342-.537 2.013-.806 2.54-1.267q.201-.177.378-.378c.461-.527.73-1.198 1.267-2.54 2.515-6.293 3.775-9.44 2.554-11.236a4.1 4.1 0 0 0-1.083-1.083c-1.797-1.221-4.944.037-11.236 2.554-1.342.537-2.013.806-2.54 1.267q-.201.177-.378.378c-.461.527-.73 1.198-1.267 2.54-2.517 6.292-3.775 9.439-2.554 11.236.29.426.657.793 1.083 1.083M8.25 12a3.75 3.75 0 1 1 7.5 0 3.75 3.75 0 0 1-7.5 0m1.5 0a2.25 2.25 0 1 1 4.5 0 2.25 2.25 0 0 1-4.5 0"})})}const vj=1e4;function Jv(n){const[e,t]=P.useState(!1);P.useEffect(()=>{if(n.kind!=="layout"){t(!1);return}const A=window.setTimeout(()=>{t(!0)},vj);return()=>window.clearTimeout(A)},[n.kind]);const i=n.kind==="community",o=i?`Opening ${n.communityLabel}`:e?"Still arranging this graph":"Arranging graph layout",r=i?"Fetching symbols and relationships for this community.":e?"This graph is taking longer than expected. You can open the current layout now.":"Positioning nodes and relationships for a readable first view.";return f.jsxs("section",{className:"compass-graph-transition","data-kind":n.kind,role:"status","aria-live":"polite","aria-atomic":"true",children:[f.jsxs("div",{className:"compass-load-visual","data-state":"loading","aria-hidden":"true",children:[f.jsx("span",{className:"compass-load-mark",children:f.jsx(mj,{})}),f.jsx("span",{className:"compass-load-progress",children:f.jsx("i",{})})]}),f.jsxs("div",{className:"compass-load-copy",children:[f.jsx("span",{className:"compass-load-eyebrow",children:"Compass graph"}),f.jsx("h1",{children:o}),f.jsx("p",{className:"compass-graph-transition-description",children:r}),!i&&e&&f.jsx("div",{className:"compass-load-actions",children:f.jsx("button",{className:"compass-load-action compass-load-action-primary",type:"button",onClick:n.onShowGraph,children:"Show graph now"})})]})]})}function bj(n){return n instanceof HTMLElement&&(n.isContentEditable||n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.tagName==="SELECT")}function yj({status:n,physicsRunning:e,layoutStyle:t,forceLabels:i,showEdgeLabels:o,hasSelection:r,isolateSelection:A,neighborhoodDepth:I,edgeDirection:l,layoutSpacing:c,showMinimap:h,leadingControls:p,leadingPanel:m,leadingPanelOpen:v,onLeadingPanelClose:x,onTogglePhysics:O,onLayoutChange:y,onZoomOut:T,onResetZoom:S,onZoomIn:_,onFit:B,onFitSelection:Q,onReset:te,onToggleLabels:V,onToggleEdgeLabels:U,onToggleIsolation:Ce,onNeighborhoodDepthChange:Te,onEdgeDirectionChange:Ze,onLayoutSpacingChange:ye,onToggleMinimap:Fe,onBack:Ge}){const[le,M]=P.useState(!1),W=P.useId(),oe=P.useRef(null),se=P.useRef(null),J=P.useRef(!1);return P.useEffect(()=>{v&&M(!1)},[v]),P.useEffect(()=>{le||!J.current||(J.current=!1,se.current?.focus())},[le]),P.useEffect(()=>{const E=ne=>{if(ne.key==="Escape"){le&&(J.current=!0,M(!1));return}ne.key!=="?"||bj(ne.target)||(ne.preventDefault(),x?.(),M(!0))},G=ne=>{oe.current?.contains(ne.target)||M(!1)};return document.addEventListener("keydown",E),document.addEventListener("pointerdown",G),()=>{document.removeEventListener("keydown",E),document.removeEventListener("pointerdown",G)}},[x,le]),f.jsxs("div",{ref:oe,className:"compass-graph-toolbar compass-glass-panel",role:"toolbar","aria-label":"Graph controls",children:[f.jsxs("div",{className:"compass-viewer-status","data-state":e?"running":"paused",role:"status","aria-live":"polite",children:[f.jsx("span",{className:"compass-viewer-status-dot","aria-hidden":"true"}),f.jsx("span",{className:"compass-viewer-status-text",children:n})]}),f.jsxs("div",{className:"compass-toolbar-actions",children:[Ge&&f.jsxs("button",{className:"compass-tool-button",type:"button","aria-label":"Back to community overview",onClick:Ge,children:[f.jsx(o_,{}),f.jsx("span",{children:"Overview"})]}),f.jsxs("label",{className:"compass-layout-picker",children:[f.jsx(b_,{"aria-hidden":"true"}),f.jsx("span",{className:"sr-only",children:"Graph layout"}),f.jsxs("select",{"aria-label":"Graph layout",value:t,onChange:E=>y(E.target.value),children:[f.jsx("option",{value:"automatic",children:"Automatic"}),f.jsx("option",{value:"circle",children:"Circle"}),f.jsx("option",{value:"concentric",children:"Concentric"}),f.jsx("option",{value:"spiral",children:"Spiral"}),f.jsx("option",{value:"grid",children:"Square grid"})]})]}),f.jsxs("button",{className:"compass-tool-button compass-physics-button",type:"button","aria-label":e?"Stop layout":t==="automatic"?"Run layout":"Fixed layout","aria-pressed":e,disabled:t!=="automatic",title:t==="automatic"?e?"Stop layout":"Run layout":"Physics is available in Automatic layout",onClick:O,children:[e?f.jsx(pv,{}):t==="automatic"?f.jsx(N_,{}):f.jsx(pv,{}),f.jsx("span",{children:e?"Stop":t==="automatic"?"Layout":"Fixed"})]}),f.jsx("span",{className:"compass-toolbar-separator","aria-hidden":"true"}),f.jsxs("div",{className:"compass-zoom-controls",role:"group","aria-label":"Zoom controls",children:[f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Zoom out",title:"Zoom out",onClick:T,children:f.jsx(L_,{})}),f.jsx("button",{className:"compass-tool-button compass-zoom-reset",type:"button","aria-label":"Reset zoom to 100%",title:"Reset zoom to 100%",onClick:S,children:"100%"}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Zoom in",title:"Zoom in",onClick:_,children:f.jsx(Z_,{})})]}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Fit graph in view",title:"Fit graph in view",onClick:B,children:f.jsx(hv,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Fit selected neighborhood",title:r?`Fit the selected node and its ${I}-hop neighborhood`:"Select a node to fit its neighborhood",disabled:!r,onClick:Q,children:f.jsx(m_,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Reset graph view",title:"Reset graph view",onClick:te,children:f.jsx(vv,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":i?"Hide labels":"Show labels","aria-pressed":i,title:i?"Hide node labels":"Show all node labels",onClick:V,children:f.jsx(P_,{})}),f.jsx("button",{className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":o?"Hide relationship labels":"Show relationship labels","aria-pressed":o,title:o?"Hide relationship labels":"Show relationship labels",onClick:U,children:f.jsx(bv,{})}),f.jsx("button",{ref:se,className:"compass-tool-button compass-tool-icon-button",type:"button","aria-label":"Graph settings","aria-expanded":le,"aria-controls":W,title:"Graph settings (?)",onClick:()=>M(E=>{const G=!E;return G&&x?.(),G}),children:f.jsx(M_,{})}),p?f.jsx("div",{className:"compass-toolbar-leading",children:p}):null]}),m,le?f.jsxs("div",{id:W,className:"compass-explore-panel compass-glass-panel",role:"region","aria-label":"Graph exploration controls",children:[f.jsxs("div",{className:"compass-explore-heading",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Graph settings"}),f.jsx("span",{children:r?"Tune the selected neighborhood and canvas":"Set the next neighborhood, then select a node"})]}),f.jsx("kbd",{children:"?"})]}),r?null:f.jsxs("div",{className:"compass-selection-prompt",role:"note",children:[f.jsx(yv,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Select a node to isolate it"}),f.jsx("small",{children:"Use the canvas or node search. Depth and direction can be set now."})]})]}),f.jsxs("button",{className:"compass-explore-toggle",type:"button","aria-label":"Isolate selection","aria-pressed":A,disabled:!r,onClick:Ce,children:[f.jsx(yv,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Isolate selection"}),f.jsx("small",{children:"Hide everything outside the traversal"})]}),f.jsx("i",{"aria-hidden":"true"})]}),f.jsxs("fieldset",{className:"compass-explore-field",children:[f.jsx("legend",{children:"Neighborhood depth"}),f.jsx("div",{className:"compass-segmented-control","aria-label":"Neighborhood depth",children:[1,2,3,4].map(E=>f.jsx("button",{type:"button","aria-label":`${E} hop${E===1?"":"s"}`,"aria-pressed":I===E,onClick:()=>Te(E),children:E},E))})]}),f.jsxs("fieldset",{className:"compass-explore-field",children:[f.jsx("legend",{children:"Edge direction"}),f.jsx("div",{className:"compass-segmented-control","aria-label":"Edge direction",children:[["both","Both"],["outgoing","Out"],["incoming","In"]].map(([E,G])=>f.jsx("button",{type:"button","aria-label":`${G==="Both"?"Both directions":G==="Out"?"Outgoing edges":"Incoming edges"}`,"aria-pressed":l===E,onClick:()=>Ze(E),children:G},E))})]}),f.jsxs("label",{className:"compass-explore-select",children:[f.jsx("span",{children:"Layout spacing"}),f.jsxs("select",{"aria-label":"Layout spacing",value:c,onChange:E=>ye(Number(E.target.value)),children:[f.jsx("option",{value:.75,children:"Compact · 75%"}),f.jsx("option",{value:1,children:"Default · 100%"}),f.jsx("option",{value:1.25,children:"Airy · 125%"}),f.jsx("option",{value:1.5,children:"Wide · 150%"})]})]}),f.jsxs("button",{className:"compass-explore-toggle",type:"button","aria-label":"Show minimap","aria-pressed":h,onClick:Fe,children:[f.jsx(w_,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Show minimap"}),f.jsx("small",{children:"Track and reposition the visible viewport"})]}),f.jsx("i",{"aria-hidden":"true"})]}),f.jsxs("div",{className:"compass-shortcut-guide","aria-label":"Graph keyboard shortcuts",children:[f.jsxs("div",{className:"compass-shortcut-title",children:[f.jsx(v_,{"aria-hidden":"true"}),f.jsx("strong",{children:"Keyboard"})]}),f.jsxs("dl",{children:[f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"F"})}),f.jsx("dd",{children:"Fit graph"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"⇧ F"})}),f.jsx("dd",{children:"Fit selection"})]}),f.jsxs("div",{children:[f.jsxs("dt",{children:[f.jsx("kbd",{children:"+"})," ",f.jsx("kbd",{children:"−"})]}),f.jsx("dd",{children:"Zoom"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"0"})}),f.jsx("dd",{children:"100% zoom"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"I"})}),f.jsx("dd",{children:"Isolate"})]}),f.jsxs("div",{children:[f.jsxs("dt",{children:[f.jsx("kbd",{children:"["})," ",f.jsx("kbd",{children:"]"})]}),f.jsx("dd",{children:"Depth"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"D"})}),f.jsx("dd",{children:"Direction"})]}),f.jsxs("div",{children:[f.jsx("dt",{children:f.jsx("kbd",{children:"M"})}),f.jsx("dd",{children:"Minimap"})]})]})]})]}):null]})}const wj=["callable","type","module","boundary","other"],xj=["execution","dependency","structure","flow","other"],Sj=new Set(["closure","constructor","function","lambda","macro","method","procedure","subroutine","database_procedure"]),Ej=new Set(["class","component","enum","interface","annotation","protocol","struct","trait","type","type_alias","union"]),Tj=new Set(["directory","document","export","file","folder","import","migration","module","namespace","package"]),Oj=new Set(["command","config_key","database","database_column","database_constraint","database_index","database_schema","database_table","database_trigger","database_view","endpoint","event","job","message","query","queue","resource","route","schema","table","topic"]),Nj=new Set(["awaits","calls","dispatches","executes","handles","instantiates","invokes","schedules","tests","triggers","spawns"]),Dj=new Set(["depends_on","exports","imports","imports_from","links","re_exports","references","returns","type_of","aliases","uses"]),kj=new Set(["contains","decorates","declares","documents","embeds","extends","implements","inherits","member_of","mixes_in","overrides","renders","owns"]),Mj=new Set(["consumes","emits","maps_to","produces","publishes","reads","receives","registers","routes_to","sends","subscribes","writes"]);function eb(n){return(n??"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function ps(n){const e=eb(n);return Sj.has(e)?"callable":Ej.has(e)?"type":Tj.has(e)?"module":Oj.has(e)?"boundary":"other"}function Sc(n){const e=eb(n);return Nj.has(e)?"execution":Dj.has(e)?"dependency":kj.has(e)?"structure":Mj.has(e)?"flow":"other"}function Rj(n){return n==="type"?"diamond":n==="module"?"square":n==="boundary"?"triangle":"dot"}function zj(n){return n==="callable"?"var(--vscode-symbolIcon-functionForeground, #5fa8ff)":n==="type"?"var(--vscode-symbolIcon-classForeground, #e3b341)":n==="module"?"var(--vscode-symbolIcon-moduleForeground, #56d4b4)":n==="boundary"?"var(--vscode-symbolIcon-eventForeground, #ff9b87)":"var(--vscode-descriptionForeground, #8b949e)"}const _j={callable:"Callable",type:"Type",module:"Module / file",boundary:"Boundary / data",other:"Other"},jj={execution:"Execution",dependency:"Dependency",structure:"Structure",flow:"Data / event flow",other:"Other"};function Pj({model:n}){const e=P.useMemo(()=>{const i=new Map;for(const o of n.nodes){const r=ps(o.kind);i.set(r,(i.get(r)??0)+1)}return i},[n.nodes]),t=P.useMemo(()=>{const i=new Map;for(const o of n.edges){const r=Sc(o.relation);i.set(r,(i.get(r)??0)+1)}return i},[n.edges]);return f.jsxs("aside",{className:"compass-semantic-legend compass-glass-panel","aria-label":"Graph visual legend",children:[f.jsxs("section",{"aria-label":"Node categories",children:[f.jsx("strong",{children:"Nodes"}),wj.filter(i=>(e.get(i)??0)>0).map(i=>f.jsxs("span",{className:"compass-semantic-legend-item",children:[f.jsx("i",{"data-node-category":i,"aria-hidden":"true"}),_j[i],f.jsx("small",{children:e.get(i)})]},i))]}),n.edges.length>0?f.jsxs("section",{"aria-label":"Relationship categories",children:[f.jsx("strong",{children:"Edges"}),xj.filter(i=>(t.get(i)??0)>0).map(i=>f.jsxs("span",{className:"compass-semantic-legend-item",children:[f.jsx("i",{"data-edge-category":i,"aria-hidden":"true"}),jj[i],f.jsx("small",{children:t.get(i)})]},i))]}):null]})}const tb=280,nb=560,ib=24,Ec={width:340,collapsed:!1};function Kr(n){return Number.isFinite(n)?Math.min(nb,Math.max(tb,Math.round(n))):Ec.width}function gb(n){return{width:Kr(n?.width??Ec.width),collapsed:n?.collapsed??Ec.collapsed}}function Bj(n,e){return Kr(n-e)}function Zj(n,e){return Kr(e==="ArrowLeft"?n+ib:e==="ArrowRight"?n-ib:n)}function Lj({width:n,onResize:e}){const t=P.useRef(!1),i=o=>{t.current=!1,o.currentTarget.hasPointerCapture(o.pointerId)&&o.currentTarget.releasePointerCapture(o.pointerId)};return f.jsx("div",{className:"compass-inspector-resizer",role:"separator","aria-label":"Resize graph inspector","aria-orientation":"vertical","aria-valuemin":tb,"aria-valuemax":nb,"aria-valuenow":n,tabIndex:0,onPointerDown:o=>{t.current=!0,o.currentTarget.setPointerCapture(o.pointerId)},onPointerMove:o=>{if(!t.current)return;const r=o.currentTarget.parentElement;r&&e(Bj(r.getBoundingClientRect().right,o.clientX))},onPointerUp:i,onPointerCancel:i,onKeyDown:o=>{o.key!=="ArrowLeft"&&o.key!=="ArrowRight"||(o.preventDefault(),e(Zj(n,o.key)))},children:f.jsx("span",{"aria-hidden":"true"})})}function ob(n,e,t){if(t===void 0&&n.stats.aggregated&&e.memberCount!==void 0&&e.detailAvailable!==!1)return{type:"community",communityId:e.community};const i=Uv(e);return i?{type:"source",source:i}:{type:"none"}}function Gj(n){const e=n.source?.startLine,t=n.source?.endLine;if(e!==void 0)return t!==void 0&&t!==e?`${e}–${t}`:String(e)}function Fj({node:n,hover:e,activation:t}){const i={"--compass-hover-x":`${e.x+18}px`,"--compass-hover-y":`${e.y-42}px`},o=Gj(n);return f.jsxs("div",{className:"compass-node-hover-card",role:"tooltip",style:i,children:[f.jsxs("div",{className:"compass-hover-heading",children:[f.jsx("strong",{children:n.label}),f.jsx("span",{children:(n.kind??"symbol").toLocaleUpperCase()})]}),n.change&&f.jsx("span",{className:"compass-change-badge","data-change":n.change,children:n.change==="unchanged"?"Context":`${n.change[0]?.toLocaleUpperCase()}${n.change.slice(1)}`}),n.groundingStatus==="GROUNDED"&&f.jsx("span",{className:"compass-change-badge","data-grounding":"grounded",children:"GROUNDED · agent-authored"}),n.agentSummary&&f.jsx("p",{children:n.agentSummary}),n.challenge&&f.jsxs("p",{children:["Challenge (",n.challenge.effect,"): ",n.challenge.summary]}),n.challenged&&!n.challenge&&f.jsx("p",{children:"Challenge: this Base Graph fact is disputed."}),n.memberCount!==void 0?f.jsxs("p",{children:[n.memberCount.toLocaleString()," symbols"]}):f.jsxs(f.Fragment,{children:[n.language&&f.jsxs("p",{children:["Language: ",n.language]}),n.source?.file&&f.jsx("p",{className:"compass-hover-source",children:n.source.file}),o&&f.jsxs("p",{children:["Lines: ",o]}),n.signature&&f.jsx("code",{children:n.signature})]}),t.type!=="none"&&f.jsxs("p",{className:"compass-hover-hint",children:[t.type==="community"?f.jsx(vc,{"aria-hidden":"true"}):f.jsx(f_,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Double-click"})," ",t.type==="community"?"to open community subgraph":"to open source code"]})]})]})}const Vj={routes_to:"routes to",publishes:"publishes",subscribes:"subscribes",produces:"produces",consumes:"consumes",schedules:"schedules",triggers:"triggers",handles:"handles",registers:"registers",reads:"reads",writes:"writes",maps_to:"maps to",depends_on:"depends on",renders:"renders"};function Uj(n){const e=n.relation.trim(),t=Vj[e]??e,i=n.details?.type==="route"?n.details.data:void 0,o=i?`${i.stage}${i.position===null||i.position===void 0?"":` ${i.position+1}`}`:void 0;return[t,o,i?.operation].filter(r=>r!==void 0&&r!=="").join(" · ")}function Yj(n){if(!n?.file.trim())return"";const e=n.startLine,t=n.endLine;if(e!==void 0){const i=t!==void 0&&t!==e?`${e}–${t}`:String(e);return`${n.file}:${i}`}return n.startByte!==void 0?`${n.file}:byte ${n.startByte}`:n.file}function Hj(n){const e=n.confidence;return e?`${e[0]?.toLocaleUpperCase()}${e.slice(1)}`:"Unspecified"}function Kj(n){if(n)return n==="unchanged"?"Context":`${n[0]?.toLocaleUpperCase()}${n.slice(1)}`}function Wj({edge:n,sourceNode:e,targetNode:t,hover:i}){const o={"--compass-hover-x":`${i.x+18}px`,"--compass-hover-y":`${i.y-52}px`},r=Yj(n.relationshipSite),A=n.codeEvidence?.[0],I=Kj(n.change),l=Yv(n)!==void 0;return f.jsxs("div",{className:"compass-edge-hover-card",role:"tooltip",style:o,children:[f.jsxs("div",{className:"compass-edge-hover-heading",children:[f.jsxs("span",{className:"compass-edge-hover-eyebrow",children:[f.jsx(dv,{"aria-hidden":"true"}),"Relationship"]}),f.jsx("span",{className:"compass-edge-confidence","data-confidence":n.confidence??"unspecified",children:Hj(n)})]}),f.jsxs("div",{className:"compass-edge-trace","aria-label":`${e.label} to ${t.label}`,children:[f.jsx("strong",{children:e.label}),f.jsx("span",{"aria-hidden":"true",children:f.jsx(s_,{})}),f.jsx("strong",{children:t.label})]}),f.jsxs("div",{className:"compass-edge-relation-row",children:[f.jsx("strong",{children:Uj(n)||"Relationship"}),I&&f.jsx("span",{className:"compass-change-badge","data-change":n.change,children:I}),n.groundingStatus==="GROUNDED"&&f.jsx("span",{className:"compass-change-badge","data-grounding":"grounded",children:"GROUNDED · agent-authored"})]}),n.agentSummary&&f.jsx("p",{children:n.agentSummary}),n.challenge&&f.jsxs("p",{children:["Challenge (",n.challenge.effect,"): ",n.challenge.summary]}),n.challenged&&!n.challenge&&f.jsx("p",{children:"Challenge: this Base Graph relationship is disputed."}),(A||r)&&f.jsxs("div",{className:"compass-edge-metadata",children:[A&&f.jsxs("p",{children:[f.jsx("span",{children:"Evidence"}),f.jsx("code",{children:A.rule??A.origin})]}),r&&f.jsxs("p",{children:[f.jsx("span",{children:"Source"}),f.jsx("code",{children:r})]})]}),l&&f.jsxs("p",{className:"compass-hover-hint",children:[f.jsx(dv,{"aria-hidden":"true"}),f.jsxs("span",{children:[f.jsx("strong",{children:"Double-click"})," to open relationship source"]})]})]})}var Tc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ke(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var CC=function(n){return n&&n.Math===Math&&n},Pt=CC(typeof globalThis=="object"&&globalThis)||CC(typeof window=="object"&&window)||CC(typeof self=="object"&&self)||CC(typeof Tc=="object"&&Tc)||(function(){return this})()||Tc||Function("return this")(),rt=function(n){try{return!!n()}catch{return!0}},Qj=rt,Wr=!Qj(function(){var n=(function(){}).bind();return typeof n!="function"||n.hasOwnProperty("prototype")}),Xj=Wr,sb=Function.prototype,rb=sb.apply,ab=sb.call,IC=typeof Reflect=="object"&&Reflect.apply||(Xj?ab.bind(rb):function(){return ab.apply(rb,arguments)}),Ab=Wr,Cb=Function.prototype,Oc=Cb.call,$j=Ab&&Cb.bind.bind(Oc,Oc),at=Ab?$j:function(n){return function(){return Oc.apply(n,arguments)}},Ib=at,qj=Ib({}.toString),Jj=Ib("".slice),qi=function(n){return Jj(qj(n),8,-1)},e5=qi,t5=at,Nc=function(n){if(e5(n)==="Function")return t5(n)},Dc=typeof document=="object"&&document.all,n5=typeof Dc>"u"&&Dc!==void 0,lb={all:Dc,IS_HTMLDDA:n5},cb=lb,i5=cb.all,fn=cb.IS_HTMLDDA?function(n){return typeof n=="function"||n===i5}:function(n){return typeof n=="function"},Qr={},g5=rt,rn=!g5(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),o5=Wr,lC=Function.prototype.call,bi=o5?lC.bind(lC):function(){return lC.apply(lC,arguments)},Xr={},db={}.propertyIsEnumerable,ub=Object.getOwnPropertyDescriptor,s5=ub&&!db.call({1:2},1);Xr.f=s5?function(e){var t=ub(this,e);return!!t&&t.enumerable}:db;var $r=function(n,e){return{enumerable:!(n&1),configurable:!(n&2),writable:!(n&4),value:e}},r5=at,a5=rt,A5=qi,kc=Object,C5=r5("".split),cC=a5(function(){return!kc("z").propertyIsEnumerable(0)})?function(n){return A5(n)==="String"?C5(n,""):kc(n)}:kc,ms=function(n){return n==null},I5=ms,l5=TypeError,qr=function(n){if(I5(n))throw new l5("Can't call method on "+n);return n},c5=cC,d5=qr,yi=function(n){return c5(d5(n))},hb=fn,fb=lb,u5=fb.all,Tn=fb.IS_HTMLDDA?function(n){return typeof n=="object"?n!==null:hb(n)||n===u5}:function(n){return typeof n=="object"?n!==null:hb(n)},Ct={},Mc=Ct,Rc=Pt,h5=fn,pb=function(n){return h5(n)?n:void 0},wi=function(n,e){return arguments.length<2?pb(Mc[n])||pb(Rc[n]):Mc[n]&&Mc[n][e]||Rc[n]&&Rc[n][e]},f5=at,Bt=f5({}.isPrototypeOf),Jr=typeof navigator<"u"&&String(navigator.userAgent)||"",mb=Pt,zc=Jr,vb=mb.process,bb=mb.Deno,yb=vb&&vb.versions||bb&&bb.version,wb=yb&&yb.v8,xi,dC;wb&&(xi=wb.split("."),dC=xi[0]>0&&xi[0]<4?1:+(xi[0]+xi[1])),!dC&&zc&&(xi=zc.match(/Edge\/(\d+)/),(!xi||xi[1]>=74)&&(xi=zc.match(/Chrome\/(\d+)/),xi&&(dC=+xi[1])));var ea=dC,xb=ea,p5=rt,m5=Pt,v5=m5.String,vs=!!Object.getOwnPropertySymbols&&!p5(function(){var n=Symbol("symbol detection");return!v5(n)||!(Object(n)instanceof Symbol)||!Symbol.sham&&xb&&xb<41}),b5=vs,Sb=b5&&!Symbol.sham&&typeof Symbol.iterator=="symbol",y5=wi,w5=fn,x5=Bt,S5=Sb,E5=Object,ta=S5?function(n){return typeof n=="symbol"}:function(n){var e=y5("Symbol");return w5(e)&&x5(e.prototype,E5(n))},T5=String,na=function(n){try{return T5(n)}catch{return"Object"}},O5=fn,N5=na,D5=TypeError,wo=function(n){if(O5(n))return n;throw new D5(N5(n)+" is not a function")},k5=wo,M5=ms,_c=function(n,e){var t=n[e];return M5(t)?void 0:k5(t)},jc=bi,Pc=fn,Bc=Tn,R5=TypeError,z5=function(n,e){var t,i;if(e==="string"&&Pc(t=n.toString)&&!Bc(i=jc(t,n))||Pc(t=n.valueOf)&&!Bc(i=jc(t,n))||e!=="string"&&Pc(t=n.toString)&&!Bc(i=jc(t,n)))return i;throw new R5("Can't convert object to primitive value")},Eb={exports:{}},Tb=Pt,_5=Object.defineProperty,j5=function(n,e){try{_5(Tb,n,{value:e,configurable:!0,writable:!0})}catch{Tb[n]=e}return e},P5=Pt,B5=j5,Ob="__core-js_shared__",Z5=P5[Ob]||B5(Ob,{}),Zc=Z5,Nb=Zc;(Eb.exports=function(n,e){return Nb[n]||(Nb[n]=e!==void 0?e:{})})("versions",[]).push({version:"3.33.0",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.33.0/LICENSE",source:"https://github.com/zloirock/core-js"});var bs=Eb.exports,L5=qr,G5=Object,Kn=function(n){return G5(L5(n))},F5=at,V5=Kn,U5=F5({}.hasOwnProperty),an=Object.hasOwn||function(e,t){return U5(V5(e),t)},Y5=at,H5=0,K5=Math.random(),W5=Y5(1 .toString),uC=function(n){return"Symbol("+(n===void 0?"":n)+")_"+W5(++H5+K5,36)},Q5=Pt,X5=bs,Db=an,$5=uC,q5=vs,J5=Sb,ys=Q5.Symbol,Lc=X5("wks"),e4=J5?ys.for||ys:ys&&ys.withoutSetter||$5,Yt=function(n){return Db(Lc,n)||(Lc[n]=q5&&Db(ys,n)?ys[n]:e4("Symbol."+n)),Lc[n]},t4=bi,kb=Tn,Mb=ta,n4=_c,i4=z5,g4=Yt,o4=TypeError,s4=g4("toPrimitive"),r4=function(n,e){if(!kb(n)||Mb(n))return n;var t=n4(n,s4),i;if(t){if(e===void 0&&(e="default"),i=t4(t,n,e),!kb(i)||Mb(i))return i;throw new o4("Can't convert object to primitive value")}return e===void 0&&(e="number"),i4(n,e)},a4=r4,A4=ta,hC=function(n){var e=a4(n,"string");return A4(e)?e:e+""},C4=Pt,Rb=Tn,Gc=C4.document,I4=Rb(Gc)&&Rb(Gc.createElement),zb=function(n){return I4?Gc.createElement(n):{}},l4=rn,c4=rt,d4=zb,_b=!l4&&!c4(function(){return Object.defineProperty(d4("div"),"a",{get:function(){return 7}}).a!==7}),u4=rn,h4=bi,f4=Xr,p4=$r,m4=yi,v4=hC,b4=an,y4=_b,jb=Object.getOwnPropertyDescriptor;Qr.f=u4?jb:function(e,t){if(e=m4(e),t=v4(t),y4)try{return jb(e,t)}catch{}if(b4(e,t))return p4(!h4(f4.f,e,t),e[t])};var w4=rt,x4=fn,S4=/#|\.prototype\./,ia=function(n,e){var t=T4[E4(n)];return t===N4?!0:t===O4?!1:x4(e)?w4(e):!!e},E4=ia.normalize=function(n){return String(n).replace(S4,".").toLowerCase()},T4=ia.data={},O4=ia.NATIVE="N",N4=ia.POLYFILL="P",D4=ia,Pb=Nc,k4=wo,M4=Wr,R4=Pb(Pb.bind),ga=function(n,e){return k4(n),e===void 0?n:M4?R4(n,e):function(){return n.apply(e,arguments)}},Wn={},z4=rn,_4=rt,Bb=z4&&_4(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),j4=Tn,P4=String,B4=TypeError,Ji=function(n){if(j4(n))return n;throw new B4(P4(n)+" is not an object")},Z4=rn,L4=_b,G4=Bb,fC=Ji,Zb=hC,F4=TypeError,Fc=Object.defineProperty,V4=Object.getOwnPropertyDescriptor,Vc="enumerable",Uc="configurable",Yc="writable";Wn.f=Z4?G4?function(e,t,i){if(fC(e),t=Zb(t),fC(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Yc in i&&!i[Yc]){var o=V4(e,t);o&&o[Yc]&&(e[t]=i.value,i={configurable:Uc in i?i[Uc]:o[Uc],enumerable:Vc in i?i[Vc]:o[Vc],writable:!1})}return Fc(e,t,i)}:Fc:function(e,t,i){if(fC(e),t=Zb(t),fC(i),L4)try{return Fc(e,t,i)}catch{}if("get"in i||"set"in i)throw new F4("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var U4=rn,Y4=Wn,H4=$r,ws=U4?function(n,e,t){return Y4.f(n,e,H4(1,t))}:function(n,e,t){return n[e]=t,n},pC=Pt,K4=IC,W4=Nc,Q4=fn,X4=Qr.f,$4=D4,xs=Ct,q4=ga,Ss=ws,Lb=an,J4=function(n){var e=function(t,i,o){if(this instanceof e){switch(arguments.length){case 0:return new n;case 1:return new n(t);case 2:return new n(t,i)}return new n(t,i,o)}return K4(n,this,arguments)};return e.prototype=n.prototype,e},je=function(n,e){var t=n.target,i=n.global,o=n.stat,r=n.proto,A=i?pC:o?pC[t]:(pC[t]||{}).prototype,I=i?xs:xs[t]||Ss(xs,t,{})[t],l=I.prototype,c,h,p,m,v,x,O,y,T;for(m in e)c=$4(i?m:t+(o?".":"#")+m,n.forced),h=!c&&A&&Lb(A,m),x=I[m],h&&(n.dontCallGetSet?(T=X4(A,m),O=T&&T.value):O=A[m]),v=h&&O?O:e[m],!(h&&typeof x==typeof v)&&(n.bind&&h?y=q4(v,pC):n.wrap&&h?y=J4(v):r&&Q4(v)?y=W4(v):y=v,(n.sham||v&&v.sham||x&&x.sham)&&Ss(y,"sham",!0),Ss(I,m,y),r&&(p=t+"Prototype",Lb(xs,p)||Ss(xs,p,{}),Ss(xs[p],m,v),n.real&&l&&(c||!l[m])&&Ss(l,m,v)))},eP=Math.ceil,tP=Math.floor,nP=Math.trunc||function(e){var t=+e;return(t>0?tP:eP)(t)},iP=nP,mC=function(n){var e=+n;return e!==e||e===0?0:iP(e)},gP=mC,oP=Math.max,sP=Math.min,oa=function(n,e){var t=gP(n);return t<0?oP(t+e,0):sP(t,e)},rP=mC,aP=Math.min,AP=function(n){return n>0?aP(rP(n),9007199254740991):0},CP=AP,oi=function(n){return CP(n.length)},IP=yi,lP=oa,cP=oi,Gb=function(n){return function(e,t,i){var o=IP(e),r=cP(o),A=lP(i,r),I;if(n&&t!==t){for(;r>A;)if(I=o[A++],I!==I)return!0}else for(;r>A;A++)if((n||A in o)&&o[A]===t)return n||A||0;return!n&&-1}},Hc={includes:Gb(!0),indexOf:Gb(!1)},sa={},dP=at,Kc=an,uP=yi,hP=Hc.indexOf,fP=sa,Fb=dP([].push),Vb=function(n,e){var t=uP(n),i=0,o=[],r;for(r in t)!Kc(fP,r)&&Kc(t,r)&&Fb(o,r);for(;e.length>i;)Kc(t,r=e[i++])&&(~hP(o,r)||Fb(o,r));return o},Wc=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],pP=Vb,mP=Wc,ra=Object.keys||function(e){return pP(e,mP)},aa={};aa.f=Object.getOwnPropertySymbols;var Ub=rn,vP=at,bP=bi,yP=rt,Qc=ra,wP=aa,xP=Xr,SP=Kn,EP=cC,Es=Object.assign,Yb=Object.defineProperty,TP=vP([].concat),OP=!Es||yP(function(){if(Ub&&Es({b:1},Es(Yb({},"a",{enumerable:!0,get:function(){Yb(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var n={},e={},t=Symbol("assign detection"),i="abcdefghijklmnopqrst";return n[t]=7,i.split("").forEach(function(o){e[o]=o}),Es({},n)[t]!==7||Qc(Es({},e)).join("")!==i})?function(e,t){for(var i=SP(e),o=arguments.length,r=1,A=wP.f,I=xP.f;o>r;)for(var l=EP(arguments[r++]),c=A?TP(Qc(l),A(l)):Qc(l),h=c.length,p=0,m;h>p;)m=c[p++],(!Ub||bP(I,l,m))&&(i[m]=l[m]);return i}:Es,NP=je,Hb=OP;NP({target:"Object",stat:!0,forced:Object.assign!==Hb},{assign:Hb});var DP=Ct,kP=DP.Object.assign,MP=kP,RP=MP,zP=RP,Ht=ke(zP),_P=at,vC=_P([].slice),Kb=at,jP=wo,PP=Tn,BP=an,Wb=vC,ZP=Wr,Qb=Function,LP=Kb([].concat),GP=Kb([].join),Xc={},FP=function(n,e,t){if(!BP(Xc,e)){for(var i=[],o=0;o=.1;)x=+r[p++%A],x>h&&(x=h),v=Math.sqrt(x*x/(1+c*c)),v=I<0?-v:v,e+=v,t+=c*v,m===!0?n.lineTo(e,t):n.moveTo(e,t),h-=x,m=!m}function oB(n,e,t,i){n.beginPath();const o=6,r=Math.PI*2/o;n.moveTo(e+i,t);for(let A=1;A1?t-1:0),o=1;o"u")){var i=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",t==="top"&&i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),o.styleSheet?o.styleSheet.cssText=n:o.appendChild(document.createTextNode(n))}}var rB=`.vis-overlay { position: absolute; top: 0px; right: 0px; diff --git a/crates/compass-output/assets/viewer/manifest.json b/crates/compass-output/assets/viewer/manifest.json index 4ab607d52..edc895564 100644 --- a/crates/compass-output/assets/viewer/manifest.json +++ b/crates/compass-output/assets/viewer/manifest.json @@ -3,8 +3,8 @@ "viewerSchema": "compass.viewer.graph/1", "files": { "graph.js": { - "bytes": 1107260, - "sha256": "afc183dc931800c15baa2a33c5324190f1f981a282f3c3598b2afb9c382ecc8e" + "bytes": 1107289, + "sha256": "509da5ca31f62a0f62608669ae6dc7f27333d66e864e6b0d865ea1d698f83f50" }, "viewer.css": { "bytes": 281613, diff --git a/crates/compass-output/src/agent_query.rs b/crates/compass-output/src/agent_query.rs index 8d6bb9b6c..89fd543fa 100644 --- a/crates/compass-output/src/agent_query.rs +++ b/crates/compass-output/src/agent_query.rs @@ -1560,6 +1560,13 @@ fn agent_caveat(diagnostic: &QueryDiagnostic) -> AgentCaveat { diagnostic.message ), ), + QueryDiagnosticCode::RelationshipInconsistency => ( + AgentSeverity::Warning, + format!( + "Relationship traversal disagrees with indexed source-backed usage evidence. {}", + diagnostic.message + ), + ), QueryDiagnosticCode::NoMatch => ( AgentSeverity::Blocker, format!( @@ -1584,7 +1591,7 @@ fn agent_caveat(diagnostic: &QueryDiagnostic) -> AgentCaveat { QueryDiagnosticCode::IncompleteCoverage => ( AgentSeverity::Warning, format!( - "Absence is not proof that the relationship does not exist. {}", + "Coverage or precision is limited; verify before drawing a conclusion. {}", diagnostic.message ), ), @@ -1634,6 +1641,7 @@ fn diagnostic_code_name(code: QueryDiagnosticCode) -> &'static str { match code { QueryDiagnosticCode::NoMatch => "no_match", QueryDiagnosticCode::AmbiguousMatch => "ambiguous_match", + QueryDiagnosticCode::RelationshipInconsistency => "relationship_inconsistency", QueryDiagnosticCode::DirectionMismatch => "direction_mismatch", QueryDiagnosticCode::UnresolvedHandler => "unresolved_handler", QueryDiagnosticCode::IncompleteCoverage => "incomplete_coverage", diff --git a/crates/compass-output/src/report.rs b/crates/compass-output/src/report.rs index 41a12e4a0..f95735d4b 100644 --- a/crates/compass-output/src/report.rs +++ b/crates/compass-output/src/report.rs @@ -2080,7 +2080,7 @@ fn fit_orientation_json_budget(model: &mut AgentOrientation) { if trim_blind_spots_for_budget(model) { continue; } - if model.communities.is_empty() { + if model.communities.len() <= 1 { break; } let scaled = model @@ -2088,7 +2088,7 @@ fn fit_orientation_json_budget(model: &mut AgentOrientation) { .len() .saturating_mul(ORIENTATION_JSON_FIT_BYTES) / rendered.len(); - let next = scaled.min(model.communities.len().saturating_sub(1)); + let next = scaled.max(1).min(model.communities.len().saturating_sub(1)); model.communities.truncate(next); model .omissions @@ -2133,13 +2133,13 @@ fn fit_report_budget(model: &mut AgentOrientation, obsidian: bool) { .omissions .surprising_connections .set_shown(model.details.surprising_connections.len()); - } else if !model.communities.is_empty() { + } else if model.communities.len() > 1 { let scaled = model .communities .len() .saturating_mul(REPORT_MARKDOWN_FIT_CHARS) / rendered_chars; - let next = scaled.min(model.communities.len().saturating_sub(1)); + let next = scaled.max(1).min(model.communities.len().saturating_sub(1)); model.communities.truncate(next); model .omissions @@ -2310,6 +2310,24 @@ fn render_orientation_markdown_with_community_limit( shown_communities, )), ]; + if shown_communities == 0 && model.omissions.communities.total > 0 { + let witness_ids = model + .communities + .iter() + .take(1) + .map(|community| community.id.to_string()) + .collect::>(); + lines.push( + format!( + "- Architecture entries were omitted by the report budget; retained witness IDs: {}. Use the bounded architecture export or query those IDs instead of treating this section as empty evidence.", + if witness_ids.is_empty() { + "none (no safe witness survived)".to_owned() + } else { + witness_ids.join(", ") + } + ), + ); + } for community in model.communities.iter().take(shown_communities) { lines.push(format!( "### {}", diff --git a/crates/compass-query/src/affected.rs b/crates/compass-query/src/affected.rs index 43a9ded7a..ad2d60c2d 100644 --- a/crates/compass-query/src/affected.rs +++ b/crates/compass-query/src/affected.rs @@ -84,15 +84,24 @@ pub fn affected_nodes( let mut seen = HashSet::from([seed]); let mut queue = VecDeque::from([(seed, 0_usize)]); let mut hits = Vec::new(); - for edge_index in graph.outgoing_edges(seed) { - let edge = graph.edge(edge_index); - if !["method", "contains"].contains(&edge.string("relation").as_str()) { - continue; - } - if let Some(member) = graph.node_index(&edge.target) - && seen.insert(member) - { - queue.push_back((member, 0)); + // Relationship commands must answer for the resolved declaration as well + // as its containing file/module. Seed all canonical members before + // walking incoming dependency edges; this mirrors the source-backed + // relationship resolution used by typed search instead of silently + // stopping at whichever container happened to resolve first. + let mut member_queue = VecDeque::from([seed]); + while let Some(container) = member_queue.pop_front() { + for edge_index in graph.outgoing_edges(container) { + let edge = graph.edge(edge_index); + if !["method", "contains"].contains(&edge.string("relation").as_str()) { + continue; + } + if let Some(member) = graph.node_index(&edge.target) + && seen.insert(member) + { + queue.push_back((member, 0)); + member_queue.push_back(member); + } } } while let Some((current, current_depth)) = queue.pop_front() { @@ -125,7 +134,24 @@ pub fn affected_nodes( #[must_use] pub fn format_affected(graph: &Graph, query: &str, relations: &[String], depth: usize) -> String { let Some(seed) = resolve_seed(graph, query) else { - return format!("No unique node match for {query}"); + let normalized = normalize_label(query); + let mut candidates = graph + .nodes() + .filter(|(_, node)| { + let label = normalize_label(node.label()); + label.contains(&normalized) || normalized.contains(&label) + }) + .map(|(index, node)| format!("{} ({})", node.label(), graph.node(index).id)) + .collect::>(); + candidates.sort(); + candidates.truncate(8); + if candidates.is_empty() { + return format!("NO EXACT MATCH for {query:?}"); + } + return format!( + "No unique node match for {query:?}. Candidates: {}", + candidates.join(", ") + ); }; let hits = affected_nodes(graph, seed, relations, depth); let mut lines = vec![ @@ -256,7 +282,7 @@ mod tests { assert_eq!(hits.len(), 1); assert_eq!(graph.node(hits[0].node).label(), "caller()"); assert!(format_affected(&graph, "file", &relations, 2).contains("caller() [calls] -")); - assert!(format_affected(&graph, "missing", &relations, 2).contains("No unique")); + assert!(format_affected(&graph, "missing", &relations, 2).contains("NO EXACT MATCH")); assert!(format_affected(&graph, "file", &relations, 0).contains("No affected")); Ok(()) } diff --git a/crates/compass-query/src/code_query.rs b/crates/compass-query/src/code_query.rs index d9291963a..7d26edded 100644 --- a/crates/compass-query/src/code_query.rs +++ b/crates/compass-query/src/code_query.rs @@ -40,6 +40,11 @@ const MAX_RECALL_FUZZY_VARIANTS_TOTAL: usize = 256; const MIN_RECALL_CANDIDATES_BEFORE_FUZZY: usize = 4; const SEARCH_QUERY_CACHE_CAPACITY: usize = 64; const FUZZY_LOOKUP_CACHE_CAPACITY: usize = 512; +const RELATIONSHIP_SELF_CHECK_MIN_IMPORTERS: usize = 8; +const RELATIONSHIP_OWNER_SCOPE_LIMIT: usize = 32; +const RELATIONSHIP_TERM_LIMIT: usize = 128; +const RELATIONSHIP_SOURCE_EDGE_SCAN_LIMIT: usize = 256; +type ContainmentPath = (Vec, Vec); const ALL_EDGE_KINDS: &[EdgeKind] = &[ EdgeKind::Contains, @@ -411,6 +416,7 @@ pub(crate) struct CodeLookupIndex { node_by_id: HashMap, nodes_by_normalized_name: HashMap>, operation_nodes_by_term: HashMap>, + relationship_source_ids_by_term: HashMap>, file_by_path: HashMap, scope_values: HashMap<(u8, String), Vec>, } @@ -421,6 +427,10 @@ impl CodeLookupIndex { node_by_id: HashMap::with_capacity(graph.nodes.len()), nodes_by_normalized_name: HashMap::new(), operation_nodes_by_term: HashMap::new(), + relationship_source_ids_by_term: + compass_model::search::relationship_source_identifier_postings(graph) + .into_iter() + .collect(), file_by_path: HashMap::with_capacity(graph.graph.files.len()), scope_values: HashMap::new(), }; @@ -1164,6 +1174,71 @@ impl PinnedDiscoveryBackend<'_> { } } + /// Read the shared source-backed relationship posting. Materialized graphs + /// use a precomputed bounded posting, while store snapshots use the + /// versioned sidecar when available and retain a legacy fallback. + pub(crate) fn relationship_sources_for_term( + &self, + term: &str, + limit: usize, + ) -> Result { + let normalized = canonical_query_token(term.to_owned()); + if normalized.is_empty() || limit == 0 { + return Ok(RelationshipCandidateRead { + source_ids: Vec::new(), + truncated: false, + node_ids_decoded: 0, + chunks_decoded: 0, + }); + } + match self { + Self::Materialized { lookup, .. } => { + let indexed = lookup + .relationship_source_ids_by_term + .get(&normalized) + .cloned() + .unwrap_or_default(); + let truncated = indexed.len() > limit; + let source_ids = indexed.into_iter().take(limit).collect::>(); + Ok(RelationshipCandidateRead { + node_ids_decoded: u64::try_from(source_ids.len()).unwrap_or(u64::MAX), + source_ids, + truncated, + chunks_decoded: 0, + }) + } + Self::Store(reader) => { + let read_limits = snapshot_limits(limit)?; + let (mut source_ids, truncated, work) = if reader + .supports_relationship_search_terms() + .map_err(snapshot_error)? + { + reader + .source_ids_for_exact_relationship_search_term_bounded_work( + &normalized, + read_limits, + ) + .map_err(snapshot_error)? + } else { + reader + .source_ids_for_exact_relationship_term_bounded_work( + &normalized, + read_limits, + ) + .map_err(snapshot_error)? + }; + let truncated = truncated || source_ids.len() > limit; + source_ids.truncate(limit); + Ok(RelationshipCandidateRead { + source_ids, + truncated, + node_ids_decoded: work.node_ids_decoded, + chunks_decoded: work.chunks_decoded, + }) + } + } + } + pub(crate) fn operation_role_candidates( &self, terms: &[String], @@ -2215,6 +2290,280 @@ impl CodeQueryEngine { }) } + /// Return the bounded inbound relationship set for a resolved target. + /// + /// The canonical adjacency remains authoritative. The shared + /// relationship postings add a second, source-backed resolution pass for + /// imports/references whose published edge terminates at a module or file + /// owner instead of the declaration selected by the query. This keeps + /// callers, impact, and affected on the same evidence path as search. + fn resolved_incoming_relationships( + &self, + target: &str, + canonical_kinds: &[EdgeKind], + include_heuristic: bool, + limit: usize, + ) -> Result<(Vec, bool, usize, bool), QueryError> { + if limit == 0 { + return Ok((Vec::new(), false, 0, false)); + } + let (canonical, mut truncated) = self.backend.matching_bounded( + target, + true, + canonical_kinds, + include_heuristic, + limit, + )?; + let mut edges = canonical + .into_iter() + .map(|edge| (edge.id.clone(), edge)) + .collect::>(); + // Imports often terminate at a file/module owner while the query + // resolves to a declaration nested inside it. Walk the bounded + // containment chain and index every owner spelling so aliases and + // re-exports can recover the same importer evidence as search. + let mut owner_ids = BTreeSet::from([target.to_owned()]); + let mut owner_queue = VecDeque::from([target.to_owned()]); + while let Some(child) = owner_queue.pop_front() { + let remaining = RELATIONSHIP_OWNER_SCOPE_LIMIT.saturating_sub(owner_ids.len()); + if remaining == 0 { + truncated = true; + break; + } + let (containers, containers_truncated) = self.backend.matching_bounded( + &child, + true, + &[EdgeKind::Contains], + false, + remaining, + )?; + truncated |= containers_truncated; + for edge in containers { + if owner_ids.insert(edge.source.clone()) { + owner_queue.push_back(edge.source); + } + } + } + // Without a containing owner, every relevant relationship terminates + // at the exact target and canonical inbound adjacency is complete. + // Do not probe broad term postings for each hop of a call chain: a + // common source-file term could make that internal probe appear + // truncated and prematurely stop an otherwise bounded impact walk. + if owner_ids.len() == 1 { + let (probe, probe_truncated) = if limit < RELATIONSHIP_SELF_CHECK_MIN_IMPORTERS { + self.backend.matching_bounded( + target, + true, + canonical_kinds, + include_heuristic, + RELATIONSHIP_SELF_CHECK_MIN_IMPORTERS, + )? + } else { + (edges.values().cloned().collect(), truncated) + }; + let observed = probe + .iter() + .map(|edge| edge.source.as_str()) + .collect::>() + .len(); + truncated |= probe_truncated || probe.len() > limit; + return Ok(( + edges.into_values().collect(), + truncated, + observed, + probe_truncated, + )); + } + let mut terms = BTreeSet::new(); + for owner_id in &owner_ids { + let Some(owner) = self.backend.node_by_id(owner_id)? else { + continue; + }; + terms.extend(compass_model::search::identifier_search_terms(&owner.name)); + terms.extend(compass_model::search::identifier_search_terms( + &owner.qualified_name, + )); + if let Some(source_file) = owner.source_file() { + terms.extend(compass_model::search::identifier_search_terms(source_file)); + } + } + let terms = terms + .into_iter() + .filter(|term| term.len() >= 3) + .collect::>(); + let terms_truncated = terms.len() > RELATIONSHIP_TERM_LIMIT; + let terms = terms + .into_iter() + .take(RELATIONSHIP_TERM_LIMIT) + .collect::>(); + truncated |= terms_truncated; + if terms.is_empty() { + return Ok((edges.into_values().collect(), truncated, 0, false)); + } + + let pinned = self.backend.pin_discovery()?; + let mut importer_ids = BTreeSet::new(); + let mut importer_probe_truncated = false; + for term in &terms { + let read = pinned.relationship_sources_for_term( + term, + limit + .saturating_sub(edges.len()) + .max(RELATIONSHIP_SELF_CHECK_MIN_IMPORTERS), + )?; + truncated |= read.truncated; + importer_probe_truncated |= read.truncated; + importer_ids.extend(read.source_ids); + if importer_ids.len() >= limit.saturating_add(RELATIONSHIP_SELF_CHECK_MIN_IMPORTERS) { + importer_probe_truncated = true; + break; + } + } + if importer_ids.is_empty() { + return Ok(( + edges.into_values().collect(), + truncated, + 0, + importer_probe_truncated, + )); + } + let mut verified_importers = edges + .values() + .map(|edge| edge.source.clone()) + .collect::>(); + for source_id in importer_ids { + let (source_edges, source_truncated) = self.backend.matching_bounded( + &source_id, + false, + canonical_kinds, + include_heuristic, + RELATIONSHIP_SOURCE_EDGE_SCAN_LIMIT, + )?; + truncated |= source_truncated; + importer_probe_truncated |= source_truncated; + for edge in source_edges { + if !owner_ids.contains(&edge.target) { + continue; + } + verified_importers.insert(source_id.clone()); + if edges.contains_key(&edge.id) { + continue; + } + if edges.len() < limit { + edges.insert(edge.id.clone(), edge); + } else { + truncated = true; + } + } + if edges.len() >= limit + && verified_importers.len() >= RELATIONSHIP_SELF_CHECK_MIN_IMPORTERS + { + importer_probe_truncated = true; + break; + } + } + Ok(( + edges.into_values().take(limit).collect(), + truncated, + verified_importers.len(), + importer_probe_truncated, + )) + } + + /// Return the actual containment hops from a declaration to an owner. + /// Owner-backed imports must not appear as a one-hop path to the declaration. + fn containment_path_to_owner( + &self, + target: &str, + owner: &str, + ) -> Result, QueryError> { + if target == owner { + return Ok(Some((vec![target.to_owned()], Vec::new()))); + } + let mut queue = VecDeque::from([target.to_owned()]); + let mut seen = BTreeSet::from([target.to_owned()]); + let mut predecessor = BTreeMap::::new(); + while let Some(child) = queue.pop_front() { + let remaining = RELATIONSHIP_OWNER_SCOPE_LIMIT.saturating_sub(seen.len()); + if remaining == 0 { + return Ok(None); + } + let (containers, truncated) = self.backend.matching_bounded( + &child, + true, + &[EdgeKind::Contains], + false, + remaining, + )?; + if truncated { + return Ok(None); + } + for edge in containers { + if !seen.insert(edge.source.clone()) { + continue; + } + predecessor.insert(edge.source.clone(), (child.clone(), edge.clone())); + if edge.source == owner { + let mut nodes = vec![owner.to_owned()]; + let mut edges = Vec::new(); + let mut cursor = owner.to_owned(); + while cursor != target { + let Some((next, step)) = predecessor.get(&cursor) else { + return Ok(None); + }; + edges.push(step.clone()); + nodes.push(next.clone()); + cursor.clone_from(next); + } + nodes.reverse(); + edges.reverse(); + return Ok(Some((nodes, edges))); + } + queue.push_back(edge.source); + } + } + Ok(None) + } + + fn relationship_consistency_diagnostic( + response: &mut CodeQueryResponse, + target: &str, + returned: usize, + observed_importers: usize, + observed_importers_truncated: bool, + ) { + if returned <= 1 && observed_importers >= RELATIONSHIP_SELF_CHECK_MIN_IMPORTERS { + let usage_count = if observed_importers_truncated { + format!("at least {observed_importers}") + } else { + observed_importers.to_string() + }; + response.diagnostics.push(QueryDiagnostic { + code: QueryDiagnosticCode::RelationshipInconsistency, + message: format!( + "search found {usage_count} source-backed usages for {target}, but this relationship query returned {returned}; results may be incomplete" + ), + node_id: Some(target.to_owned()), + path: None, + }); + } + } + + fn owner_level_relationship_diagnostic(response: &mut CodeQueryResponse, target: &str) { + if response.diagnostics.iter().any(|diagnostic| { + diagnostic.code == QueryDiagnosticCode::IncompleteCoverage + && diagnostic.node_id.as_deref() == Some(target) + }) { + return; + } + response.diagnostics.push(QueryDiagnostic { + code: QueryDiagnosticCode::IncompleteCoverage, + message: "Some incoming imports or references end at a containing module or file. They prove an owner-level dependency, not direct use of the selected symbol. Check the source anchors before treating them as symbol callers.".to_owned(), + node_id: Some(target.to_owned()), + path: None, + }); + } + pub fn callers(&self, request: CallRequest) -> Result { self.call_neighbors_instrumented(request, true, &mut QueryInstrumentation::default()) } @@ -2263,13 +2612,24 @@ impl CodeQueryEngine { &[EdgeKind::Calls] }; let max_edges = usize::try_from(request.limits.max_edges).unwrap_or(usize::MAX); - let (selected_edges, truncated) = self.backend.matching_bounded( - &seed, - inbound, - kinds, - request.include_heuristic, - max_edges, - )?; + let (selected_edges, truncated, observed_importers, observed_importers_truncated) = + if inbound { + self.resolved_incoming_relationships( + &seed, + CALLER_KINDS, + request.include_heuristic, + max_edges, + )? + } else { + let (edges, truncated) = self.backend.matching_bounded( + &seed, + inbound, + kinds, + request.include_heuristic, + max_edges, + )?; + (edges, truncated, 0, false) + }; instrumentation.work.nodes_expanded = instrumentation.work.nodes_expanded.saturating_add(1); instrumentation.work.edges_expanded = instrumentation .work @@ -2280,6 +2640,18 @@ impl CodeQueryEngine { instrumentation.work.edges_expanded.saturating_add(1); } response.truncated |= truncated; + if inbound { + Self::relationship_consistency_diagnostic( + &mut response, + &seed, + selected_edges.len(), + observed_importers, + observed_importers_truncated, + ); + if selected_edges.iter().any(|edge| edge.target != seed) { + Self::owner_level_relationship_diagnostic(&mut response, &seed); + } + } let mut ids = HashSet::from([seed.clone()]); for edge in &selected_edges { ids.insert(edge.source.clone()); @@ -2296,10 +2668,35 @@ impl CodeQueryEngine { self.impact_instrumented(request, &mut QueryInstrumentation::default()) } + /// Resolve inbound dependency relationships for the compatibility + /// `affected` command. It deliberately shares the same relationship + /// postings and consistency probe as `impact`, while allowing the legacy + /// command's caller-selected relation vocabulary to remain explicit. + pub fn affected( + &self, + request: ImpactRequest, + relation_kinds: &[EdgeKind], + ) -> Result { + self.impact_instrumented_with_kinds( + request, + relation_kinds, + &mut QueryInstrumentation::default(), + ) + } + pub(crate) fn impact_instrumented( &self, request: ImpactRequest, instrumentation: &mut QueryInstrumentation, + ) -> Result { + self.impact_instrumented_with_kinds(request, IMPACT_KINDS, instrumentation) + } + + fn impact_instrumented_with_kinds( + &self, + request: ImpactRequest, + relationship_kinds: &[EdgeKind], + instrumentation: &mut QueryInstrumentation, ) -> Result { validate_limits(&request.limits)?; let mut response = @@ -2325,8 +2722,10 @@ impl CodeQueryEngine { let mut queue = VecDeque::from([(seed.clone(), Vec::::new(), Vec::::new())]); let mut visited = HashSet::from([seed.clone()]); + let mut included_nodes = HashSet::from([seed.clone()]); + let mut owner_paths = BTreeMap::<(String, String), Option>::new(); let max_edges = usize::try_from(request.limits.max_edges).unwrap_or(usize::MAX); - let mut selected_edges = HashSet::new(); + let mut selected_edges = BTreeMap::::new(); while let Some((node, path_nodes, path_edges)) = queue.pop_front() { instrumentation.work.nodes_expanded = instrumentation.work.nodes_expanded.saturating_add(1); @@ -2334,13 +2733,25 @@ impl CodeQueryEngine { continue; } let remaining_edges = max_edges.saturating_sub(selected_edges.len()); - let (incoming, incoming_truncated) = self.backend.matching_bounded( - &node, - true, - IMPACT_KINDS, - request.include_heuristic, - remaining_edges, - )?; + let (incoming, incoming_truncated, observed, observed_truncated) = self + .resolved_incoming_relationships( + &node, + relationship_kinds, + request.include_heuristic, + remaining_edges, + )?; + if node == seed { + Self::relationship_consistency_diagnostic( + &mut response, + &seed, + incoming.len(), + observed, + observed_truncated, + ); + if incoming.iter().any(|edge| edge.target != seed) { + Self::owner_level_relationship_diagnostic(&mut response, &seed); + } + } instrumentation.work.edges_expanded = instrumentation .work .edges_expanded @@ -2351,37 +2762,73 @@ impl CodeQueryEngine { } response.truncated |= incoming_truncated; for edge in incoming { - if selected_edges.len() >= max_edges { + let bridge_key = (node.clone(), edge.target.clone()); + let bridge = if let Some(cached) = owner_paths.get(&bridge_key) { + cached.clone() + } else { + let result = self.containment_path_to_owner(&node, &edge.target)?; + owner_paths.insert(bridge_key, result.clone()); + result + }; + let Some((bridge_nodes, bridge_edges)) = bridge else { response.truncated = true; - break; + continue; + }; + let added_edges = bridge_edges + .iter() + .map(|step| step.id.as_str()) + .chain(std::iter::once(edge.id.as_str())) + .filter(|id| !selected_edges.contains_key(*id)) + .count(); + let added_nodes = bridge_nodes + .iter() + .chain(std::iter::once(&edge.source)) + .filter(|id| !included_nodes.contains(*id)) + .collect::>() + .len(); + if selected_edges.len().saturating_add(added_edges) > max_edges + || included_nodes.len().saturating_add(added_nodes) > max_nodes + || path_edges + .len() + .saturating_add(bridge_edges.len()) + .saturating_add(1) + > max_depth + { + response.truncated = true; + continue; + } + included_nodes.extend(bridge_nodes.iter().cloned()); + included_nodes.insert(edge.source.clone()); + for step in &bridge_edges { + selected_edges.insert(step.id.clone(), step.clone()); } + selected_edges.insert(edge.id.clone(), edge.clone()); if visited.insert(edge.source.clone()) { - if visited.len() > max_nodes { - visited.remove(&edge.source); - response.truncated = true; - break; - } - selected_edges.insert(edge.id.clone()); let mut nodes = path_nodes.clone(); if nodes.is_empty() { nodes.push(seed.clone()); } + nodes.extend(bridge_nodes.into_iter().skip(1)); nodes.push(edge.source.clone()); let mut edges = path_edges.clone(); + edges.extend(bridge_edges.iter().map(|step| step.id.clone())); edges.push(edge.id.clone()); - response.paths.push(self.path_record(&nodes, &edges)?); + response.paths.push(self.path_record_with_edges( + &nodes, + &edges, + &selected_edges, + )?); queue.push_back((edge.source.clone(), nodes, edges)); - } else { - selected_edges.insert(edge.id.clone()); } } if response.truncated { break; } } - let ids = visited; - self.add_nodes(&ids, &mut response)?; - self.add_edges(&selected_edges, &mut response)?; + self.add_nodes(&included_nodes, &mut response)?; + response + .edges + .extend(selected_edges.values().map(query_edge)); self.apply_path_bound(&mut response); let response = self.finish_response(&mut response); instrumentation.execution += execution_started.elapsed(); @@ -2806,6 +3253,23 @@ impl CodeQueryEngine { Ok(path_record(nodes, edges, &selected)) } + fn path_record_with_edges( + &self, + nodes: &[String], + edges: &[String], + selected_edges: &BTreeMap, + ) -> Result { + let mut selected = Vec::with_capacity(edges.len()); + for edge in edges { + if let Some(record) = selected_edges.get(edge) { + selected.push(record.clone()); + } else if let Some(record) = self.backend.edge_by_id(edge)? { + selected.push(record); + } + } + Ok(path_record(nodes, edges, &selected)) + } + fn shortest_path( &self, source: &str, diff --git a/crates/compass-query/src/index.rs b/crates/compass-query/src/index.rs index 88597273f..fb4409e70 100644 --- a/crates/compass-query/src/index.rs +++ b/crates/compass-query/src/index.rs @@ -694,6 +694,9 @@ fn build_index( .map_err(sql_error)?; } } + // Preserve the discovery index contract. Structural relationship + // commands use their own bounded broad posting path; discovery's + // relationship promotion remains based on trusted direct calls. for (term, source_ids) in direct_call_source_identifier_postings(graph) { for source_id in source_ids { transaction diff --git a/crates/compass-query/tests/code_traversal.rs b/crates/compass-query/tests/code_traversal.rs index cf17737ed..da604fe73 100644 --- a/crates/compass-query/tests/code_traversal.rs +++ b/crates/compass-query/tests/code_traversal.rs @@ -4,10 +4,10 @@ use std::collections::HashSet; use std::fs; use compass_model::code_graph::{EdgeKind, GraphDocument}; -use compass_model::identity::edge_id; +use compass_model::identity::{edge_id, file_id}; use compass_model::provenance::{OccurrenceRule, SourceAnchor}; use compass_model::query_contract::{ - CallRequest, CodeQueryLimits, NodeTrailRequest, QueryDiagnosticCode, + CallRequest, CodeQueryLimits, ImpactRequest, NodeTrailRequest, QueryDiagnosticCode, }; use compass_query::open; @@ -63,6 +63,231 @@ fn callers_include_calls_and_route_bindings_while_callees_follow_calls() Ok(()) } +#[test] +fn callers_recover_source_backed_importers_that_target_a_tsconfig_alias_owner() +-> Result<(), Box> { + let directory = tempfile::tempdir()?; + let graph_path = directory.path().join("graph.json"); + support::write_graph(&graph_path)?; + let mut graph = GraphDocument::load(&graph_path)?; + let module = graph + .nodes + .iter() + .find(|node| node.id == "n:list") + .cloned() + .ok_or("missing module template")?; + let mut module = module; + module.id = "n:list-module".to_owned(); + module.kind = compass_model::code_graph::NodeKind::Module; + // This is the shape emitted after a TypeScript `paths` alias such as + // `@scope/pkg/* -> packages/pkg/src/*` has been resolved: the importer + // edge targets the module owner while the queried declaration is nested + // inside that owner. + module.name = "@scope/pkg".to_owned(); + module.qualified_name = "@scope/pkg/index".to_owned(); + if let Some(source) = module.source.as_mut() { + source.file = "packages/pkg/src/index.ts".to_owned(); + } + let mut module_file = graph + .graph + .files + .first() + .cloned() + .ok_or("missing file template")?; + module_file.id = file_id("packages/pkg/src/index.ts"); + module_file.path = "packages/pkg/src/index.ts".to_owned(); + graph.graph.files.push(module_file); + graph.nodes.push(module); + let edge_template = graph + .links + .iter() + .find(|edge| edge.source == "n:caller") + .cloned() + .ok_or("missing edge template")?; + for index in 0..8 { + let source_id = format!("n:importer-{index}"); + let mut source = graph + .nodes + .iter() + .find(|node| node.id == "n:caller") + .cloned() + .ok_or("missing source template")?; + source.id = source_id.clone(); + source.name = format!("importer_{index}"); + source.qualified_name = format!("Api.importer_{index}"); + graph.nodes.push(source); + let mut edge = edge_template.clone(); + edge.source = source_id; + edge.target = "n:list-module".to_owned(); + edge.kind = EdgeKind::Imports; + let id = edge_id( + &edge.source, + edge.kind, + &edge.target, + edge.relationship_site.as_ref(), + None, + ); + edge.id.clone_from(&id); + edge.key = id; + graph.links.push(edge); + } + let mut contains = edge_template.clone(); + contains.source = "n:list-module".to_owned(); + contains.target = "n:list".to_owned(); + contains.kind = EdgeKind::Contains; + let id = edge_id( + &contains.source, + contains.kind, + &contains.target, + contains.relationship_site.as_ref(), + None, + ); + contains.id.clone_from(&id); + contains.key = id; + graph.links.push(contains); + // A different module can share a display name or search term. Its import + // must not become evidence for the queried declaration. + let mut other_module = graph + .nodes + .iter() + .find(|node| node.id == "n:list-module") + .cloned() + .ok_or("missing module")?; + other_module.id = "n:other-module".to_owned(); + other_module.qualified_name = "@other/pkg/index".to_owned(); + if let Some(source) = other_module.source.as_mut() { + source.file = "packages/other/src/index.ts".to_owned(); + } + graph.nodes.push(other_module); + let mut other_file = graph + .graph + .files + .iter() + .find(|file| file.path == "packages/pkg/src/index.ts") + .cloned() + .ok_or("missing module file")?; + other_file.id = file_id("packages/other/src/index.ts"); + other_file.path = "packages/other/src/index.ts".to_owned(); + graph.graph.files.push(other_file); + let mut unrelated_importer = graph + .nodes + .iter() + .find(|node| node.id == "n:caller") + .cloned() + .ok_or("missing source template")?; + unrelated_importer.id = "n:unrelated-importer".to_owned(); + unrelated_importer.name = "unrelated_importer".to_owned(); + unrelated_importer.qualified_name = "Other.unrelated_importer".to_owned(); + graph.nodes.push(unrelated_importer); + let mut unrelated_edge = edge_template.clone(); + unrelated_edge.source = "n:unrelated-importer".to_owned(); + unrelated_edge.target = "n:other-module".to_owned(); + unrelated_edge.kind = EdgeKind::Imports; + let id = edge_id( + &unrelated_edge.source, + unrelated_edge.kind, + &unrelated_edge.target, + unrelated_edge.relationship_site.as_ref(), + None, + ); + unrelated_edge.id.clone_from(&id); + unrelated_edge.key = id; + graph.links.push(unrelated_edge); + fs::write(&graph_path, serde_json::to_vec_pretty(&graph)?)?; + + let engine = open(&graph_path, None, &directory.path().join("cache"))?; + let response = engine.callers(CallRequest { + symbol: "UserService.list".to_owned(), + include_heuristic: false, + limits: CodeQueryLimits::default(), + })?; + let importer_count = response + .nodes + .iter() + .filter(|node| node.id.starts_with("n:importer-")) + .count(); + assert_eq!(importer_count, 8); + assert!( + !response + .nodes + .iter() + .any(|node| node.id == "n:unrelated-importer") + ); + assert!( + response + .edges + .iter() + .any(|edge| { edge.kind == EdgeKind::Imports && edge.target == "n:list-module" }) + ); + assert!( + !response + .diagnostics + .iter() + .any(|diagnostic| diagnostic.code == QueryDiagnosticCode::RelationshipInconsistency) + ); + assert!(response.diagnostics.iter().any(|diagnostic| { + diagnostic.code == QueryDiagnosticCode::IncompleteCoverage + && diagnostic.message.contains("owner-level dependency") + })); + + let bounded = engine.callers(CallRequest { + symbol: "UserService.list".to_owned(), + include_heuristic: false, + limits: CodeQueryLimits { + max_edges: 1, + ..CodeQueryLimits::default() + }, + })?; + assert!(bounded.diagnostics.iter().any(|diagnostic| { + diagnostic.code == QueryDiagnosticCode::RelationshipInconsistency + && diagnostic.message.contains("search found ") + && diagnostic + .message + .contains("source-backed usages for n:list") + })); + + let affected = engine.affected( + ImpactRequest { + symbol: "UserService.list".to_owned(), + include_heuristic: false, + limits: CodeQueryLimits::default(), + }, + &[EdgeKind::Imports], + )?; + assert_eq!( + affected + .nodes + .iter() + .filter(|node| node.id.starts_with("n:importer-")) + .count(), + 8 + ); + assert!( + !affected + .nodes + .iter() + .any(|node| node.id == "n:unrelated-importer") + ); + assert!(!affected.paths.is_empty()); + assert!(affected.diagnostics.iter().any(|diagnostic| { + diagnostic.code == QueryDiagnosticCode::IncompleteCoverage + && diagnostic.message.contains("owner-level dependency") + })); + for path in &affected.paths { + assert_eq!(path.node_ids.len(), path.edge_ids.len() + 1); + for (pair, edge_id) in path.node_ids.windows(2).zip(&path.edge_ids) { + let edge = affected + .edges + .iter() + .find(|edge| &edge.id == edge_id) + .ok_or("missing path edge")?; + assert_eq!(edge.target, pair[0]); + assert_eq!(edge.source, pair[1]); + } + } + Ok(()) +} + #[test] fn call_queries_never_publish_edges_with_truncated_endpoints() -> Result<(), Box> { diff --git a/docs/reference/commands.md b/docs/reference/commands.md index 119fed302..606eb95e5 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -420,13 +420,36 @@ existing discovery entry ledger and v2 cursor remain unchanged. bounded `nextActions` as argv arrays or JSON argument objects; clients should use those values instead of reconstructing shell commands from result text. -`callers` returns direct incoming usage evidence: calls, routes, references, +`callers` returns incoming relationship evidence: calls, routes, references, imports, exports, and aliases. `callees` remains the direct outgoing call view. +When an import or reference ends at a containing module rather than the +selected declaration, `callers`, `impact`, and `affected` retain the real +owner-targeted edge and emit an `incomplete_coverage` precision warning. +Such an edge proves a module-level dependency, not a direct symbol call; +impact paths include the containment hop instead of silently jumping from +the selected symbol to the importer. + +### `architecture` + +```text +compass architecture + [--graph PATH] + [--labels PATH] + [--format text|json|agent-json] +``` + +Returns the existing bounded architecture projection as a first-class command. +The text form is answer-first and names the graph totals, groups, routes, +diagnostics, and any omitted groups. `agent-json` adds the versioned +`compass.architecture.agent-view/1` envelope while preserving coverage counts +and witness group IDs, so an empty displayed section cannot be mistaken for an +empty architecture. ### `path` ```text -compass path "" "" [--max-depth N] [--graph PATH | --at REV] +compass path "" "" [--max-depth N] + [--format text|json|agent-json] [--graph PATH | --at REV] ``` Resolves both endpoints by exact node ID, name, or qualified name before doing @@ -446,6 +469,7 @@ choice visible rather than rewriting the graph. compass explain "" [--budget N] [--page N] + [--format text|json|agent-json] [--graph PATH | --at REV] ``` @@ -464,10 +488,14 @@ after the first group. compass affected "" [--relation R] [--depth N] + [--format text|json|agent-json] [--graph PATH] ``` -Traverses incoming impact-relevant relations. +Traverses incoming impact-relevant relations. Typed `compass.graph/1` inputs use +the same bounded resolver and source-backed relationship postings as callers +and impact; legacy node-link inputs retain the compatibility traversal. JSON +and agent JSON retain diagnostics, evidence, and explicit ambiguity candidates. ### `context` @@ -580,7 +608,9 @@ changes, affected callers/modules, and test evidence. Routine symbol churn is collapsed; `--limit N` changes the visible per-section budget, while `--all` expands routine findings and is exhaustive. `--explain` prints the evidence and reasoning for one finding. Diff requires comparable build profiles; -rebuild the newer revision with `--profile-from OLD` when needed. +rebuild the newer revision with `--profile-from OLD` when needed. `diff` never +materializes a revision: build each uncached revision explicitly with +`compass history build REV --code-only` before comparing. `--format html` requires `--output PATH` and writes a self-contained interactive report containing the reviewer findings, unified/split source diffs, the exact Git patch fallback, and meaningful code-graph changes. @@ -1040,9 +1070,13 @@ count. `history change-counts` requires existing preferred realizations with the same complete build profile and never builds them. Its bounded structural counts exclude source-coordinate, clustering/layout, and anchor-derived edge identity churn while preserving topology and relationship multiplicity. +`history export` is also read-only; run `compass history build REV --code-only` +before exporting an uncached revision. `history diff` streams an exhaustive, -deterministic record-level diff for selected immutable roots. It may lazily -materialize a missing revision, requires identical complete build profiles and +deterministic record-level diff for selected immutable roots. It is read-only: +both revisions must already be materialized, and an uncached revision returns +the exact `compass history build REV --code-only` prerequisite instead of +starting extraction. It requires identical complete build profiles and compatible graph engines, refuses to overwrite `--output`, and bounds stdout for safety. This is distinct from the ranked `compass diff` semantic-review report. Guided writers accept `--events jsonl`; stdout then contains diff --git a/fixtures/contracts/compass-query-v1.fingerprint b/fixtures/contracts/compass-query-v1.fingerprint index 8a8ee438d..6d3bdbb28 100644 --- a/fixtures/contracts/compass-query-v1.fingerprint +++ b/fixtures/contracts/compass-query-v1.fingerprint @@ -1 +1 @@ -sha256:6bab0ebdb192a202ed9845e1d0a9e30310f0f17d4f7c2229a8af156d5ef7d7dd +sha256:e5dd8bf0ad65e1ce5e4a159ee0d8cd43d74fc1fe39ac58d7107025ad0d3481cf diff --git a/fixtures/contracts/compass-query-v1.manifest.json b/fixtures/contracts/compass-query-v1.manifest.json index 08fc7ed53..37392909a 100644 --- a/fixtures/contracts/compass-query-v1.manifest.json +++ b/fixtures/contracts/compass-query-v1.manifest.json @@ -10,7 +10,7 @@ "evidenceOrigin": ["ast", "config", "convention", "artifact", "heuristic"], "confidence": ["exact", "inferred", "ambiguous"], "resolution": ["exact", "ambiguous", "unresolved"], - "diagnosticCode": ["no_match", "ambiguous_match", "direction_mismatch", "unresolved_handler", "incomplete_coverage", "stale_source_digest", "bounded_truncation", "program_orphan", "program_conflict", "program_unavailable"] + "diagnosticCode": ["no_match", "ambiguous_match", "relationship_inconsistency", "direction_mismatch", "unresolved_handler", "incomplete_coverage", "stale_source_digest", "bounded_truncation", "program_orphan", "program_conflict", "program_unavailable"] }, "fields": { "response": ["schema", "operation", "results", "nodes", "edges", "files", "paths", "diagnostics", "limits", "truncated"], diff --git a/packages/compass-viewer/src/contracts/codeQuery.test.ts b/packages/compass-viewer/src/contracts/codeQuery.test.ts index bfa5314ae..ce8d190e1 100644 --- a/packages/compass-viewer/src/contracts/codeQuery.test.ts +++ b/packages/compass-viewer/src/contracts/codeQuery.test.ts @@ -64,6 +64,17 @@ describe("compass.query/1", () => { expect(CodeRouteStageSchema.parse("security")).toBe("security"); }); + it("accepts a relationship inconsistency diagnostic", () => { + const response = example() as Record; + response.diagnostics = [{ + code: "relationship_inconsistency", + message: "Search found 8 importers; this query returned 1", + nodeId: "n:target", + path: null + }]; + expect(CodeQueryResponseSchema.safeParse(response).success).toBe(true); + }); + it("retains heuristic wiring and ambiguous candidates", () => { const value = example() as Record; value.edges = [{ diff --git a/packages/compass-viewer/src/contracts/codeQuery.ts b/packages/compass-viewer/src/contracts/codeQuery.ts index afa87041f..d89f68878 100644 --- a/packages/compass-viewer/src/contracts/codeQuery.ts +++ b/packages/compass-viewer/src/contracts/codeQuery.ts @@ -51,7 +51,7 @@ export const CODE_QUERY_CONTRACT_MANIFEST = { confidence: ["exact", "inferred", "ambiguous"], resolution: ["exact", "ambiguous", "unresolved"], diagnosticCode: [ - "no_match", "ambiguous_match", "direction_mismatch", "unresolved_handler", "incomplete_coverage", + "no_match", "ambiguous_match", "relationship_inconsistency", "direction_mismatch", "unresolved_handler", "incomplete_coverage", "stale_source_digest", "bounded_truncation", "program_orphan", "program_conflict", "program_unavailable" ] @@ -362,7 +362,7 @@ export const CodeQueryPathSchema = z.strictObject({ export const CodeQueryDiagnosticSchema = z.strictObject({ code: z.enum([ - "no_match", "ambiguous_match", "direction_mismatch", "unresolved_handler", "incomplete_coverage", + "no_match", "ambiguous_match", "relationship_inconsistency", "direction_mismatch", "unresolved_handler", "incomplete_coverage", "stale_source_digest", "bounded_truncation", "program_orphan", "program_conflict", "program_unavailable" ]),