diff --git a/docs/agents/create-projection.md b/docs/agents/create-projection.md index 68a1550ef..7e50192e3 100644 --- a/docs/agents/create-projection.md +++ b/docs/agents/create-projection.md @@ -381,6 +381,10 @@ prepared. ``` `schema` is one of these. Pick the closest; domain detail goes in `data`. +An entity or relationship takes only the fields its schema names (an unknown +field is an error; put extensions in `data`), and each schema below says which +`data` fields the engine checks, which of those are required and which objects +are closed, with a link to every field. **In Python, don't write this JSON yourself.** Projections puts its `projections` module on the extractor's `PYTHONPATH` (nothing to install): @@ -416,17 +420,24 @@ result({entities: {'service:payments': {kind: 'service', label: 'Payments'}}}) In other languages, write the JSON above. - `graph/v0`: entities and directed relationships between them; the general choice. Built-in extractors present it with `dependencies`, `file-packing`, `gallery`, `graph`, `text-diff`. - - With `"vocabularies": ["scenarios/v0"]`: renderer fixture scenarios: `scenarios` documents that `contains` `scenario` entities, each with its renderer and synthetic extraction or comparison; the engine checks its typed `data`. + - Fields and strictness: no typed `data`, so every `data` field is open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/graph.md). + - With `"vocabularies": ["scenarios/v0"]`: renderer fixture scenarios: `scenarios` documents that `contains` `scenario` entities, each with its renderer and synthetic extraction or comparison. Fields and strictness: the engine checks, on entities, `data.path` (string on `scenarios`, required), `data.renderer` (string on `scenarios` and `scenario`, required on `scenario`), `data.scenarios` (array of string on `scenarios`), `data.after` (object on `scenario`), `data.before` (object on `scenario`), `data.bundle` (string on `scenario`), `data.comparator` (string on `scenario`), `data.comparison` (object on `scenario`), `data.description` (string on `scenario`), `data.extraction` (object on `scenario`), `data.group` (string on `scenario`), `data.mode` (one of its values on `scenario`, required) and `data.presentation` (object on `scenario`); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/vocabularies-scenarios.md). - `dag/v0`: like `graph/v0`, with no cycles: steps, stages, job or build order. Built-in extractors present it with `dag`. + - Fields and strictness: no typed `data`, so every `data` field is open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/dag.md). - `treemap/v0`: a containment forest (at most one parent each, no cycles) whose leaves carry a nonnegative numeric `data.value`. + - Fields and strictness: the engine checks, on entities, `data.value` (number); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/treemap.md). - `metrics/v0`: measurements: every entity carries a numeric `data.value` and optionally a string `data.unit`. Built-in extractors present it with `code-statistics`. + - Fields and strictness: the engine checks, on entities, `data.unit` (string) and `data.value` (number, required); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/metrics.md). - `api/v0`: public API declarations; `export`, `type`, `member`, `function`, `class`, `interface`, `method`, `property` and `enum` entities carry a string `data.signature` and optionally a `data.contract` object of compatibility facts. Built-in extractors present it with `api`. + - Fields and strictness: the engine checks, on entities, `data.signature` (string on `export`, `type`, `member`, `function`, `class`, `interface`, `method`, `property` and `enum`, required) and `data.contract` (`contract`), a closed object: no fields beyond its schema's, and `declaration`, `term` and `visibility` required; other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/api.md). - `database/v0`: tables, columns, keys and constraints; `column` entities carry `data.type` and optionally `data.databaseType` (a string or null), and booleans `data.nullable` and `data.primaryKey`; `constraint` and `primary-key` entities may name `data.table` and `data.columns`, and `foreign-key` and `relation` relationships `data.columns` and `data.principalColumns`. Built-in extractors present it with `database`. + - Fields and strictness: the engine checks, on entities, `data.databaseType` (string or null on `column`), `data.nullable` (boolean on `column`), `data.primaryKey` (boolean on `column`), `data.type` (string on `column` and `constraint`, required on `column`), `data.columns` (array of string on `constraint` and `primary-key`) and `data.table` (string on `constraint` and `primary-key`); and on relationships, `data.columns` (array of string on `foreign-key` and `relation`) and `data.principalColumns` (array of string on `foreign-key` and `relation`); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/database.md). - `architecture/v0`: components and their connections, as `graph/v0`, for architecture and infrastructure. Built-in extractors present it with `agentic-workflows`, `dependency-injection`, `infrastructure`, `runtime-policy`. - - With `"vocabularies": ["dependency-injection/v0"]`: `service`, `registration` and `implementation` entities and `dependsOn` relationships of a dependency-injection container, with lifetimes and keys; the engine checks its typed `data`. - - With `"vocabularies": ["infrastructure/v0"]`: resources, data sources, modules and resource groups with their `data.type`, `data.provider` and planned `data.action`; the engine checks its typed `data`. - - With `"vocabularies": ["runtime-policy/v0"]`: kernel runtime policies (such as Tetragon): `policy`, `hook`, `selector` and `subject` entities; the engine checks its typed `data`. - - With `"vocabularies": ["agentic-workflows/v0"]`: agentic workflows (such as GitHub Agentic Workflows): `workflow` and `group` entities; the engine checks its typed `data`. + - Fields and strictness: no typed `data`, so every `data` field is open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/architecture.md). + - With `"vocabularies": ["dependency-injection/v0"]`: `service`, `registration` and `implementation` entities and `dependsOn` relationships of a dependency-injection container, with lifetimes and keys. Fields and strictness: the engine checks, on entities, `data.key` (string on `service`), `data.module` (string on `service` and `registration`), `data.name` (string on `service`), `data.type` (string on `service` and `implementation`), `data.declaredLifetime` (string on `registration`), `data.implementation` (string on `registration`), `data.lifetime` (string on `registration`), `data.ordinal` (number on `registration`) and `data.scope` (string on `registration`); and on relationships, `data.collection` (boolean on `dependsOn`), `data.optional` (boolean on `dependsOn`) and `data.parameter` (string on `dependsOn`); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/vocabularies-dependency-injection.md). + - With `"vocabularies": ["infrastructure/v0"]`: resources, data sources, modules and resource groups with their `data.type`, `data.provider` and planned `data.action`. Fields and strictness: the engine checks, on entities, `data.action` (string), `data.provider` (string), `data.replaceOrder` (string) and `data.type` (string); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/vocabularies-infrastructure.md). + - With `"vocabularies": ["runtime-policy/v0"]`: kernel runtime policies (such as Tetragon): `policy`, `hook`, `selector` and `subject` entities. Fields and strictness: the engine checks, on entities, `data.effect` (string on `policy` and `selector`), `data.mode` (string on `policy`), `data.namespace` (string or null on `policy`), `data.nodes` (string on `policy`), `data.scope` (string on `policy`), `data.category` (string on `hook`), `data.hookType` (string on `hook`), `data.stability` (string on `hook`), `data.enforcement` (string on `selector`), `data.ordinal` (number on `selector`) and `data.subjectKind` (string on `subject`); and on relationships, `data.operator` (string on `matches` and `excludes`) and `data.parent` (boolean on `matches` and `excludes`); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/vocabularies-runtime-policy.md). + - With `"vocabularies": ["agentic-workflows/v0"]`: agentic workflows (such as GitHub Agentic Workflows): `workflow` and `group` entities. Fields and strictness: the engine checks, on entities, `data.group` (string on `workflow`), `data.name` (string or null on `workflow`), `data.path` (string on `workflow`, required), `data.secrets` (array of string on `workflow`), `data.strict` (boolean on `workflow`), `data.tools` (array of string on `workflow`), `data.unrecognized` (array of string on `workflow`) and `data.workflows` (array of string on `group`); other `data` fields are open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/vocabularies-agentic-workflows.md). - Every entity has `id`, `kind`, `label`; every relationship `id`, `kind`, `from`, `to`, and both ends must exist. Renderers draw a relationship as an @@ -546,6 +557,16 @@ it, the person can build it from a Git submodule ([Install @githubnext/projections](https://github.com/githubnext/projections/blob/main/docs/guides/develop-a-renderer.md#install-githubnextprojections)); never replace it with a `file:` link to a package directory. +**Declare what it does first**, in `vite.config.ts`: `rendererConfig({view: +'src/view.tsx', name, title, comparisonModes, capabilities})` is the only +place the renderer says what it does, and the host and the checks read it from +there. `comparisonModes` lists the modes it draws, `'diff'` first. In +`capabilities`, declare `drawsRelationships: false` when it deliberately draws +no relationships, or shows them only as nesting or order; otherwise the +`relationships` check expects every relationship drawn and marked. The other +capabilities (`hover`, `filter`, `annotations`, …) are off unless declared, +and the kit declares the ones it implements. + ```sh cd .github/projections//renderer npm install @@ -606,8 +627,8 @@ animated from the same view if time allows. The starter does this: `status-text` checks hold the diff to these rules. The renderer has no entry of its own: `vite.config.ts` -(`rendererConfig({view: 'src/view.tsx', …})`) declares its capabilities once, -and the build generates the entry that mounts `src/view.tsx`'s `View` with +(`rendererConfig({view: 'src/view.tsx', …})`) declares its capabilities once +(above), and the build generates the entry that mounts `src/view.tsx`'s `View` with them in the kit's shell, along with that module's `options` (`nouns`, `facts`, `controls`). The shell gives `View` `RendererProps`: `model` (rows pairing each entity across the comparison), `diff`, @@ -640,9 +661,8 @@ them in the kit's shell, along with that module's `options` (`nouns`, `facts`, - Draw relationships and put the relationship's ID in `data-entity-id` on what draws each one, as for entities (the starter does, in each card), so they can be selected and the checks see them (the `relationships` check - fails when none is marked). A renderer that deliberately draws none, or - shows them only as nesting, declares `capabilities: {drawsRelationships: - false}` in `vite.config.ts`'s `rendererConfig`. + fails when none is marked), unless it declares `drawsRelationships: false` + (above). - Put `data-entity-id` on the element that draws the item's visible edge (its **unit**, or **item**; mark it `data-projections-unit` where entity elements nest). Hover, keyboard focus and selection rings are the renderer SDK's, diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 50a0762c3..c32a87185 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -637,6 +637,7 @@ projections help [OPTIONS] [COMMAND|TOPIC]... | Argument | Description | |---|---| | `...` | A command, `authoring` for the guide to building a projection, or `agents [NAME]` for the prompts a coding agent follows. | +| `--all` | With `agents NAME`, the whole prompt, not its overview and table of sections. | ## `projections licenses` diff --git a/packages/cli/src/docs.rs b/packages/cli/src/docs.rs index 6eb18f7ab..c31e9b51e 100644 --- a/packages/cli/src/docs.rs +++ b/packages/cli/src/docs.rs @@ -55,10 +55,136 @@ fn strip_generated(text: &str) -> &str { } } +/// A prompt longer than this, with at least [`SECTIONS`] `###` sections, prints as its overview and a table of its +/// sections, each printed on its own by name. +const SECTIONED: usize = 16 * 1024; +const SECTIONS: usize = 4; + +/// One section of a long prompt: its name (`the-loop`), its heading and its text, heading included. +pub struct Section<'a> { + pub name: String, + pub title: &'a str, + pub text: &'a str, +} + +/// A prompt's overview (what comes before its first `###` section) and its sections; no sections when the prompt is +/// short enough to print whole. +pub fn prompt_sections(prompt: &str) -> (&str, Vec>) { + if prompt.len() <= SECTIONED { + return (prompt, Vec::new()); + } + let starts: Vec = prompt.match_indices("\n### ").map(|(at, _)| at + 1).collect(); + let Some(&first) = starts.first().filter(|_| starts.len() >= SECTIONS) else { + return (prompt, Vec::new()); + }; + let sections = starts + .iter() + .enumerate() + .map(|(index, &start)| { + let end = starts.get(index + 1).copied().unwrap_or(prompt.len()); + let text = &prompt[start..end]; + let title = text["### ".len()..].lines().next().unwrap_or_default().trim(); + Section { + name: slug(title), + title, + text: text.trim_end(), + } + }) + .collect(); + (prompt[..first].trim_end(), sections) +} + +/// A heading as a section name: lowercase words joined by `-`. +fn slug(title: &str) -> String { + title + .to_lowercase() + .split(|character: char| !character.is_alphanumeric()) + .filter(|word| !word.is_empty()) + .collect::>() + .join("-") +} + +/// The first sentence of a section's prose, on one line, for its table of contents entry: code blocks are skipped, +/// and a list's first item is read as prose. +fn first_sentence(text: &str) -> String { + let mut fenced = false; + let mut paragraph: Vec<&str> = Vec::new(); + for line in text.lines().skip(1) { + let line = line.trim(); + if line.starts_with("```") { + fenced = !fenced; + continue; + } + if fenced { + continue; + } + if line.is_empty() { + if paragraph.is_empty() { + continue; + } + break; + } + paragraph.push(line.trim_start_matches("- ")); + } + let paragraph = paragraph.join(" "); + let end = paragraph.find(". ").map_or(paragraph.len(), |at| at + 1); + let sentence = ¶graph[..end]; + if sentence.chars().count() > 160 { + format!("{}…", sentence.chars().take(159).collect::().trim_end()) + } else { + sentence.to_owned() + } +} + +/// What `projections help agents NAME [SECTION…]` prints: a long prompt's overview and table of contents, or the +/// sections named; a short prompt, or `all`, whole. +pub fn agent_prompt_text(name: &str, sections: &[String], all: bool) -> Result { + let prompt = agent_prompt(name).ok_or_else(|| format!("No agent prompt named {name}; `projections help agents` lists them"))?; + let (overview, parts) = prompt_sections(prompt); + if all || parts.is_empty() { + if let Some(section) = sections.first().filter(|_| parts.is_empty()) { + return Err(format!( + "The agent prompt {name} has no sections; `projections help agents {name}` prints it ({section})" + )); + } + return Ok(prompt.to_owned()); + } + if sections.is_empty() { + let width = parts.iter().map(|part| part.name.len()).max().unwrap_or(0) + 2; + let mut text = format!( + "{overview}\n\n## Sections\n\nThis guide is in sections; read each before the step that needs it, and every one your task reaches before you build. Print sections with `projections help agents {name}
...`, or the whole guide with `projections help agents {name} --all`. A link such as `#extractor` names a section.\n\n" + ); + for part in &parts { + let name = format!("`{}`", part.name); + text.push_str(&format!("- {name:width$} {}: {}\n", part.title, first_sentence(part.text))); + } + return Ok(text); + } + let mut text = String::new(); + for wanted in sections { + let wanted = slug(wanted.trim_start_matches('#')); + let part = parts.iter().find(|part| part.name == wanted).ok_or_else(|| { + format!( + "The agent prompt {name} has no section {wanted}; its sections are {}", + parts.iter().map(|part| part.name.as_str()).collect::>().join(", ") + ) + })?; + if !text.is_empty() { + text.push_str("\n\n"); + } + text.push_str(part.text); + } + text.push('\n'); + Ok(text) +} + /// The list `projections help agents` prints. pub fn agent_prompt_list() -> String { let width = AGENT_PROMPTS.iter().map(|(id, _, _)| id.len()).max().unwrap_or(0); - let mut text = String::from("Prompts for a coding agent; `projections help agents NAME` prints one for the agent to follow:\n\n"); + let mut text = String::from( + "Prompts for a coding agent; `projections help agents NAME` prints one for the agent to follow (a long one, its overview and \ + sections: `projections help agents NAME SECTION...` prints sections, `--all` the whole prompt):\n\n", + ); for (id, summary, _) in AGENT_PROMPTS { text.push_str(&format!(" {id:width$} {summary}\n")); } @@ -83,6 +209,29 @@ mod tests { assert!(agent_prompt_list().contains("create-projection")); } + #[test] + fn a_long_prompt_prints_its_overview_and_sections_by_name() { + let whole = agent_prompt("create-projection").unwrap(); + let overview = agent_prompt_text("create-projection", &[], false).unwrap(); + assert!(overview.len() < whole.len() / 4, "{} of {}", overview.len(), whole.len()); + assert!(overview.starts_with("# Create a projection")); + assert!(overview.contains("## Sections")); + assert!(overview.contains("- `custom-renderer`"), "{overview}"); + let renderer = agent_prompt_text("create-projection", &["custom-renderer".into()], false).unwrap(); + assert!(renderer.starts_with("### Custom renderer\n"), "{renderer}"); + assert!(!renderer.contains("### Comparator")); + // Its capabilities come before its build commands. + assert!(renderer.find("drawsRelationships").unwrap() < renderer.find("npm run build").unwrap()); + let two = agent_prompt_text("create-projection", &["#extractor".into(), "Definition".into()], false).unwrap(); + assert!(two.starts_with("### Extractor\n") && two.contains("\n### Definition\n")); + assert_eq!(agent_prompt_text("create-projection", &[], true).unwrap(), whole); + let error = agent_prompt_text("create-projection", &["nope".into()], false).unwrap_err(); + assert!(error.contains("its sections are show-the-person,"), "{error}"); + // A short prompt, or one of few sections, prints whole. + assert_eq!(agent_prompt_text("ci", &[], false).unwrap(), agent_prompt("ci").unwrap()); + assert_eq!(agent_prompt_text("install", &[], false).unwrap(), agent_prompt("install").unwrap()); + } + #[test] fn the_docs_base_is_a_github_tree() { assert!(DOCS_BASE.starts_with("https://github.com/") && DOCS_BASE.ends_with('/')); diff --git a/packages/cli/src/main.rs b/packages/cli/src/main.rs index 980d2a589..5ffc77e30 100644 --- a/packages/cli/src/main.rs +++ b/packages/cli/src/main.rs @@ -122,6 +122,9 @@ enum Commands { /// agent follows #[arg(value_name = "COMMAND|TOPIC")] topic: Vec, + /// With `agents NAME`, the whole prompt, not its overview and table of sections + #[arg(long)] + all: bool, }, /// The license and third-party notices of this executable Licenses, @@ -151,7 +154,7 @@ enum Commands { Reference, } -fn help(topic: &[String]) -> Result<()> { +fn help(topic: &[String], all: bool) -> Result<()> { match topic { [one] if one == "authoring" => { io::stdout().lock().write_all(scaffold::authoring_guide().as_bytes())?; @@ -163,10 +166,9 @@ fn help(topic: &[String]) -> Result<()> { .write_all(projections_cli::docs::agent_prompt_list().as_bytes())?; Ok(()) } - [one, name] if one == "agents" => { - let prompt = projections_cli::docs::agent_prompt(name) - .with_context(|| format!("No agent prompt named {name}; `projections help agents` lists them"))?; - io::stdout().lock().write_all(prompt.as_bytes())?; + [one, name, sections @ ..] if one == "agents" => { + let text = projections_cli::docs::agent_prompt_text(name, sections, all).map_err(anyhow::Error::msg)?; + io::stdout().lock().write_all(text.as_bytes())?; Ok(()) } [] => Ok(Cli::command().print_long_help()?), @@ -294,7 +296,7 @@ async fn run(directory: &Path, command: Commands) -> Result<()> { Commands::Pr(args) => commands::pull_request(directory, args), Commands::Extractor(command) => commands::extractor(command), Commands::Validate(args) => commands::validate(args), - Commands::Help { topic } => help(&topic), + Commands::Help { topic, all } => help(&topic, all), Commands::Licenses => { let licenses = assets::licenses().context( "This build does not include the Inspector client, whose notices cover the executable; build the browser client before rebuilding the native CLI", diff --git a/packages/cli/src/skill.rs b/packages/cli/src/skill.rs index d4ff1926b..221bc5bee 100644 --- a/packages/cli/src/skill.rs +++ b/packages/cli/src/skill.rs @@ -6,6 +6,7 @@ use serde_json::Value; use std::collections::BTreeSet; +mod formats; pub mod health; pub mod install; @@ -139,12 +140,17 @@ fn schemas() -> String { .filter(|(_, schemas)| schemas.contains(schema)) .map(|(vocabulary, _)| { format!( - " - With `\"vocabularies\": [\"{vocabulary}\"]`: {}; the engine checks its typed `data`.\n", - vocabulary_summary(vocabulary) + " - With `\"vocabularies\": [\"{vocabulary}\"]`: {}. {}\n", + vocabulary_summary(vocabulary), + formats::note(vocabulary).unwrap_or_default() ) }) .collect(); - format!("- `{schema}`: {}.{used}\n{vocabularies}", schema_summary(schema)) + format!( + "- `{schema}`: {}.{used}\n - {}\n{vocabularies}", + schema_summary(schema), + formats::note(schema).unwrap_or_default() + ) }) .collect() } diff --git a/packages/cli/src/skill/formats.rs b/packages/cli/src/skill/formats.rs new file mode 100644 index 000000000..0a058b4c2 --- /dev/null +++ b/packages/cli/src/skill/formats.rs @@ -0,0 +1,302 @@ +//! Each built-in format's fields and strictness, for the authoring guide, read from its JSON schema so the guide can't +//! drift from what the engine checks: the `data` fields it types, which are required, and which objects are closed. + +use serde_json::Value; + +/// A schema's JSON and its reference page, by schema or vocabulary ID. +fn schema(id: &str) -> Option<(&'static str, &'static str)> { + Some(match id { + "graph/v0" => (include_str!("../../../schemas/schemas/graph/v0.json"), "graph"), + "dag/v0" => (include_str!("../../../schemas/schemas/dag/v0.json"), "dag"), + "treemap/v0" => (include_str!("../../../schemas/schemas/treemap/v0.json"), "treemap"), + "metrics/v0" => (include_str!("../../../schemas/schemas/metrics/v0.json"), "metrics"), + "api/v0" => (include_str!("../../../schemas/schemas/api/v0.json"), "api"), + "database/v0" => (include_str!("../../../schemas/schemas/database/v0.json"), "database"), + "architecture/v0" => (include_str!("../../../schemas/schemas/architecture/v0.json"), "architecture"), + "dependency-injection/v0" => ( + include_str!("../../../schemas/schemas/vocabularies/dependency-injection/v0.json"), + "vocabularies-dependency-injection", + ), + "infrastructure/v0" => ( + include_str!("../../../schemas/schemas/vocabularies/infrastructure/v0.json"), + "vocabularies-infrastructure", + ), + "runtime-policy/v0" => ( + include_str!("../../../schemas/schemas/vocabularies/runtime-policy/v0.json"), + "vocabularies-runtime-policy", + ), + "agentic-workflows/v0" => ( + include_str!("../../../schemas/schemas/vocabularies/agentic-workflows/v0.json"), + "vocabularies-agentic-workflows", + ), + "scenarios/v0" => ( + include_str!("../../../schemas/schemas/vocabularies/scenarios/v0.json"), + "vocabularies-scenarios", + ), + _ => return None, + }) +} + +/// Where a field is required. +#[derive(PartialEq)] +enum Required { + Never, + /// On these kinds, whose condition requires it. + On(Vec), + Always, +} + +/// One typed `data` field. +struct Field { + /// `entity` or `relationship`. + on: &'static str, + name: String, + kind: String, + /// The kinds whose `data` it types, in the schema's order; none for every kind. + applies: Option>, + required: Required, +} + +/// The note on schema or vocabulary `id`: its typed `data` fields, required ones and closed objects, then the link to +/// its reference page. +pub(super) fn note(id: &str) -> Option { + let (text, page) = schema(id)?; + let document: Value = serde_json::from_str(text).ok()?; + let mut fields = Vec::new(); + walk(&document["$defs"]["refinement"], None, None, &mut fields); + let link = format!("{}docs/reference/schemas/{page}.md", crate::docs::DOCS_BASE); + if fields.is_empty() { + return Some(format!( + "Fields and strictness: no typed `data`, so every `data` field is open JSON ({link})." + )); + } + let groups: Vec = [("entity", "on entities"), ("relationship", "on relationships")] + .iter() + .filter_map(|(on, words)| { + let described: Vec = fields + .iter() + .filter(|field| field.on == *on) + .map(|field| describe(field, &document["$defs"])) + .collect(); + (!described.is_empty()).then(|| format!("{words}, {}", list(&described))) + }) + .collect(); + Some(format!( + "Fields and strictness: the engine checks, {}; other `data` fields are open JSON ({link}).", + groups.join("; and ") + )) +} + +/// Collects the `data` fields a refinement types, under `entities` or `relationships`, following `allOf`, `anyOf`, +/// `oneOf`, array items and a condition's `then`, whose requirements hold only on the kinds its `if` selects. +fn walk(node: &Value, on: Option<&'static str>, kinds: Option<&[String]>, fields: &mut Vec) { + for key in ["allOf", "anyOf", "oneOf"] { + for item in node[key].as_array().into_iter().flatten() { + walk(item, on, kinds, fields); + } + } + walk_child(&node["items"], on, kinds, fields); + if node["then"].is_object() { + let kind = &node["if"]["properties"]["kind"]; + let selected: Vec = kind["enum"] + .as_array() + .into_iter() + .flatten() + .chain(kind.get("const")) + .filter_map(|kind| kind.as_str().map(str::to_owned)) + .collect(); + walk(&node["then"], on, Some(&selected), fields); + } + let Some(properties) = node["properties"].as_object() else { + return; + }; + for (key, child) in properties { + match (key.as_str(), on) { + ("entities", _) => walk(child, Some("entity"), kinds, fields), + ("relationships", _) => walk(child, Some("relationship"), kinds, fields), + ("data", Some(on)) => { + let required: Vec<&str> = child["required"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + for (name, schema) in child["properties"].as_object().into_iter().flatten() { + let here = match (required.contains(&name.as_str()), kinds) { + (false, _) => Required::Never, + (true, Some(kinds)) => Required::On(kinds.to_vec()), + (true, None) => Required::Always, + }; + let applies = kinds.map(<[String]>::to_vec); + match fields.iter_mut().find(|field| field.on == on && field.name == *name) { + Some(field) => { + field.required = merge(std::mem::replace(&mut field.required, Required::Never), here); + field.applies = match (field.applies.take(), applies) { + (Some(mut a), Some(b)) => { + let more: Vec = b.into_iter().filter(|kind| !a.contains(kind)).collect(); + a.extend(more); + Some(a) + } + _ => None, + }; + } + None => fields.push(Field { + on, + name: name.clone(), + kind: kind(schema), + applies, + required: here, + }), + } + } + walk(child, Some(on), kinds, fields); + } + _ => {} + } + } +} + +/// A field's requirement where two branches type it: required always if either requires it always, else on the kinds +/// either requires it on. +fn merge(a: Required, b: Required) -> Required { + match (a, b) { + (Required::Always, _) | (_, Required::Always) => Required::Always, + (Required::On(mut a), Required::On(b)) => { + let more: Vec = b.into_iter().filter(|kind| !a.contains(kind)).collect(); + a.extend(more); + Required::On(a) + } + (Required::On(kinds), Required::Never) | (Required::Never, Required::On(kinds)) => Required::On(kinds), + (Required::Never, Required::Never) => Required::Never, + } +} + +fn walk_child(node: &Value, on: Option<&'static str>, kinds: Option<&[String]>, fields: &mut Vec) { + if node.is_object() { + walk(node, on, kinds, fields); + } +} + +/// A field's type in words: its JSON types, or the definition it refers to. +fn kind(schema: &Value) -> String { + if let Some(reference) = schema["$ref"].as_str() { + let name = reference.rsplit('/').next().unwrap_or(reference); + return match (reference.starts_with('#'), name) { + (true, _) => format!("`{name}`"), + (false, "text") => "string".to_owned(), + (false, "json") => "JSON".to_owned(), + (false, other) => other.to_owned(), + }; + } + match &schema["type"] { + Value::String(single) if single == "array" => format!("array of {}", kind(&schema["items"])), + Value::String(single) => single.clone(), + Value::Array(types) => types.iter().filter_map(Value::as_str).collect::>().join(" or "), + _ if schema["enum"].is_array() => "one of its values".to_owned(), + _ => "JSON".to_owned(), + } +} + +fn describe(field: &Field, definitions: &Value) -> String { + let named = |kinds: &[String]| list(&kinds.iter().map(|kind| format!("`{kind}`")).collect::>()); + // Typed on some kinds only: other kinds' `data` may use the name freely. + let applies = field + .applies + .as_deref() + .map(|kinds| format!(" on {}", named(kinds))) + .unwrap_or_default(); + let required = match &field.required { + Required::Always => ", required".to_owned(), + Required::On(kinds) + if field + .applies + .as_deref() + .is_some_and(|applies| applies.len() == kinds.len() && applies.iter().all(|kind| kinds.contains(kind))) => + { + ", required".to_owned() + } + Required::On(kinds) => format!(", required on {}", named(kinds)), + Required::Never => String::new(), + }; + let mut text = format!("`data.{}` ({}{applies}{required})", field.name, field.kind); + // A closed object it refers to: no fields beyond its own, and the ones it requires. + let closed = field + .kind + .trim_matches('`') + .split_whitespace() + .last() + .map(|name| &definitions[name.trim_matches('`')]) + .filter(|definition| definition["additionalProperties"] == false); + if let Some(definition) = closed { + let needed: Vec = definition["required"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(|name| format!("`{name}`")) + .collect(); + text.push_str(&format!( + ", a closed object: no fields beyond its schema's{}", + if needed.is_empty() { + String::new() + } else { + format!(", and {} required", list(&needed)) + } + )); + } + text +} + +/// `a`, `a and b`, `a, b and c`. +fn list(items: &[String]) -> String { + match items { + [] => String::new(), + [one] => one.clone(), + [rest @ .., last] => format!("{} and {last}", rest.join(", ")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn api_s_contract_is_closed_with_its_required_facts() { + let api = note("api/v0").unwrap(); + assert!( + api.contains("on entities, `data.signature` (string on `export`, `type`, `member`, `function`, `class`, `interface`, `method`, `property` and `enum`, required)"), + "{api}" + ); + assert!( + api.contains( + "`data.contract` (`contract`), a closed object: no fields beyond its schema's, and `declaration`, `term` and `visibility` required" + ), + "{api}" + ); + assert!(api.ends_with("docs/reference/schemas/api.md)."), "{api}"); + assert!(note("metrics/v0").unwrap().contains("`data.value` (number, required)")); + let database = note("database/v0").unwrap(); + assert!(database.contains("; and on relationships, `data.columns`"), "{database}"); + assert!(database.contains("`data.nullable` (boolean on `column`)"), "{database}"); + assert!( + database.contains("`data.type` (string on `column` and `constraint`, required on `column`)"), + "{database}" + ); + assert!( + database.contains("`data.columns` (array of string on `foreign-key` and `relation`)"), + "{database}" + ); + let scenarios = note("scenarios/v0").unwrap(); + assert!( + scenarios.contains("`data.renderer` (string on `scenarios` and `scenario`, required on `scenario`)"), + "{scenarios}" + ); + assert!(note("graph/v0").unwrap().starts_with("Fields and strictness: no typed `data`")); + for id in projections_engine::SCHEMAS { + assert!(note(id).is_some(), "{id} has no note"); + } + for (vocabulary, _) in projections_engine::VOCABULARIES { + assert!(note(vocabulary).is_some(), "{vocabulary} has no note"); + } + } +} diff --git a/packages/cli/templates/SKILL.md b/packages/cli/templates/SKILL.md index c62839ae6..21af80501 100644 --- a/packages/cli/templates/SKILL.md +++ b/packages/cli/templates/SKILL.md @@ -374,6 +374,10 @@ prepared. ``` `schema` is one of these. Pick the closest; domain detail goes in `data`. +An entity or relationship takes only the fields its schema names (an unknown +field is an error; put extensions in `data`), and each schema below says which +`data` fields the engine checks, which of those are required and which objects +are closed, with a link to every field. **In Python, don't write this JSON yourself.** Projections puts its `projections` module on the extractor's `PYTHONPATH` (nothing to install): @@ -519,6 +523,16 @@ it, the person can build it from a Git submodule ([Install @githubnext/projections](https://github.com/githubnext/projections/blob/main/docs/guides/develop-a-renderer.md#install-githubnextprojections)); never replace it with a `file:` link to a package directory. +**Declare what it does first**, in `vite.config.ts`: `rendererConfig({view: +'src/view.tsx', name, title, comparisonModes, capabilities})` is the only +place the renderer says what it does, and the host and the checks read it from +there. `comparisonModes` lists the modes it draws, `'diff'` first. In +`capabilities`, declare `drawsRelationships: false` when it deliberately draws +no relationships, or shows them only as nesting or order; otherwise the +`relationships` check expects every relationship drawn and marked. The other +capabilities (`hover`, `filter`, `annotations`, …) are off unless declared, +and the kit declares the ones it implements. + ```sh cd .github/projections//renderer npm install @@ -579,8 +593,8 @@ animated from the same view if time allows. The starter does this: `status-text` checks hold the diff to these rules. The renderer has no entry of its own: `vite.config.ts` -(`rendererConfig({view: 'src/view.tsx', …})`) declares its capabilities once, -and the build generates the entry that mounts `src/view.tsx`'s `View` with +(`rendererConfig({view: 'src/view.tsx', …})`) declares its capabilities once +(above), and the build generates the entry that mounts `src/view.tsx`'s `View` with them in the kit's shell, along with that module's `options` (`nouns`, `facts`, `controls`). The shell gives `View` `RendererProps`: `model` (rows pairing each entity across the comparison), `diff`, @@ -613,9 +627,8 @@ them in the kit's shell, along with that module's `options` (`nouns`, `facts`, - Draw relationships and put the relationship's ID in `data-entity-id` on what draws each one, as for entities (the starter does, in each card), so they can be selected and the checks see them (the `relationships` check - fails when none is marked). A renderer that deliberately draws none, or - shows them only as nesting, declares `capabilities: {drawsRelationships: - false}` in `vite.config.ts`'s `rendererConfig`. + fails when none is marked), unless it declares `drawsRelationships: false` + (above). - Put `data-entity-id` on the element that draws the item's visible edge (its **unit**, or **item**; mark it `data-projections-unit` where entity elements nest). Hover, keyboard focus and selection rings are the renderer SDK's,