Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 30 additions & 10 deletions docs/agents/create-projection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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, required on `scenarios`), `data.renderer` (string, required on `scenario`), `data.scenarios` (array of string), `data.after` (object), `data.before` (object), `data.bundle` (string), `data.comparator` (string), `data.comparison` (object), `data.description` (string), `data.extraction` (object), `data.group` (string), `data.mode` (one of its values, required on `scenario`) and `data.presentation` (object); 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, required on `export`, `type`, `member`, `function`, `class`, `interface`, `method`, `property` and `enum`) 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), `data.nullable` (boolean), `data.primaryKey` (boolean), `data.type` (string, required on `column`), `data.columns` (array of string) and `data.table` (string); and on relationships, `data.columns` (array of string) and `data.principalColumns` (array of string); 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), `data.module` (string), `data.name` (string), `data.type` (string), `data.declaredLifetime` (string), `data.implementation` (string), `data.lifetime` (string), `data.ordinal` (number) and `data.scope` (string); and on relationships, `data.collection` (boolean), `data.optional` (boolean) and `data.parameter` (string); 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), `data.mode` (string), `data.namespace` (string or null), `data.nodes` (string), `data.scope` (string), `data.category` (string), `data.hookType` (string), `data.stability` (string), `data.enforcement` (string), `data.ordinal` (number) and `data.subjectKind` (string); and on relationships, `data.operator` (string) and `data.parent` (boolean); 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), `data.name` (string or null), `data.path` (string, required on `workflow`), `data.secrets` (array of string), `data.strict` (boolean), `data.tools` (array of string), `data.unrecognized` (array of string) and `data.workflows` (array of string); 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
Expand Down Expand Up @@ -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/<id>/renderer
npm install
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,7 @@ projections help [OPTIONS] [COMMAND|TOPIC]...
| Argument | Description |
|---|---|
| `<COMMAND\|TOPIC>...` | 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`

Expand Down
151 changes: 150 additions & 1 deletion packages/cli/src/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Section<'_>>) {
if prompt.len() <= SECTIONED {
return (prompt, Vec::new());
}
let starts: Vec<usize> = 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::<Vec<_>>()
.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 = &paragraph[..end];
if sentence.chars().count() > 160 {
format!("{}…", sentence.chars().take(159).collect::<String>().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<String, String> {
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} <section>...`, 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::<Vec<_>>().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"));
}
Expand All @@ -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('/'));
Expand Down
Loading
Loading