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
4 changes: 2 additions & 2 deletions docs/agents/explore.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ This file guides you, a coding agent, to find the projections that apply to this

1. Prefer the Projections tools when you have them: in VS Code’s agent the Projections extension offers them, and an MCP client gets them from `projections mcp` (an MCP server over standard input and output; add it as a stdio server run in this repository). They do each step below and answer in short text; writes preview first and write only once confirmed (over MCP, call again with the preview’s `confirm` token after the person agrees). Otherwise use the CLI commands below.
2. Check the CLI: `projections --version`. If it is missing, install it by following https://github.com/githubnext/projections/blob/main/docs/agents/install.md.
3. Propose: the `explore` tool, or `projections explore --list --json`, lists the projections whose built-in extractors apply here, each with the files that suggested it.
3. Propose: the `explore` tool, or `projections explore --list --json`, lists the projections whose built-in extractors apply here, each with the files that suggested it and what it `needs` first (configuration, or an install such as the repository's own TypeScript): do that, or leave it out.
4. Sweep: the `sweep` tool, or `projections explore --sweep --json`, runs each one on the last 20 merges into this branch (`--last N` for more). Projections that run repository code are skipped unless you pass `--trust`; ask the person first.
5. Report, per projection, the pull requests it changed on and how (for example `#12: 3 added, 1 removed`), and its `signal`, which ranks the sweep: `rare` (only on structural work: worth a look), `noisy` (on nearly every change: likely noise, so don’t recommend it) or `quiet` (never changed here); and the pull requests where several changed. To look at one yourself, draw it: `projections compare <before>..<after> -p <id> --png FILE` (a new file outside the repository).
5. Report, per projection, the pull requests it changed on and how (for example `#12: 3 added, 1 removed`), why it failed when it did (the sweep gives the extractor's own words), and its `signal`, which ranks the sweep: `rare` (only on structural work: worth a look), `noisy` (on nearly every change: likely noise, so don’t recommend it) or `quiet` (never changed here); and the pull requests where several changed. To look at one yourself, draw it: `projections compare <before>..<after> -p <id> --png FILE` (a new file outside the repository).
6. Ask the person which projections to keep. Never adopt or change CI on your own; a request to set projections up for them is their go-ahead to adopt the few the sweep shows are worth having, so you can show them. Say which you adopted and why.
7. Adopt what they chose: `projections adopt <id>... --dry-run`, then `projections adopt <id>...`. If they want something no built-in projection shows, build it: run `projections help agents create-projection` and follow what it prints.
8. Show them each adopted projection yourself: `projections view show -p <id> --choice bookmark:<bookmark>` (or the `open_projection` tool) shows it in the Projections viewer on a pull request it changed on (`projections bookmark list` lists the ones adopt saved) and prints the viewer’s URL. When the person asks to “open it in the inspector” or to “show” a projection, they mean this viewer.
Expand Down
9 changes: 8 additions & 1 deletion packages/cli/src/commands/explore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,14 @@ pub fn adopt(directory: &Path, args: Adopt) -> Result<()> {
continue;
}
let found = onboard::bookmarks::highlights(id, &changes, &cells, usize::from(args.bookmarks));
if found.is_empty() {
let mine: Vec<&Value> = cells.iter().filter(|cell| cell["projection"] == id).collect();
if found.is_empty() && !mine.is_empty() && mine.iter().all(|cell| cell["status"] == "failed") {
notes.push(format!(
"{id} has no bookmarks: it failed on every one of the last {} changes: {}",
changes.len(),
sweep::failure_reason(mine[0])
));
} else if found.is_empty() {
notes.push(format!(
"{id} showed no change in the last {} changes, so nothing was bookmarked",
changes.len()
Expand Down
12 changes: 12 additions & 0 deletions packages/cli/src/explore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use anyhow::{Context, Result};
use serde_json::{Value, json};
use std::path::Path;

mod typescript;
mod vendored;

/// Files listed at most, so discovery stays bounded in very large checkouts.
Expand Down Expand Up @@ -139,6 +140,10 @@ pub fn candidates(runner: &Runner, root: &Path) -> Result<Vec<Value>> {
continue;
};
let id = descriptor["id"].as_str().unwrap_or_default();
if id == typescript::EXTRACTOR {
specific.extend(typescript::candidates(root, descriptor, &files, &authored, pattern, matched.len()));
continue;
}
if let Some(input) = collectors::per_file_input(id) {
specific.extend(per_file(descriptor, input, &matched, &authored));
continue;
Expand Down Expand Up @@ -283,6 +288,13 @@ pub fn text(candidates: &[Value]) -> String {
if candidate["requiresTrust"] == true {
notes.push("runs repository code: --trust".to_owned());
}
for need in candidate["needs"].as_array().into_iter().flatten() {
notes.push(format!(
"needs {}: {}",
if need["kind"] == "install" { "an install" } else { "configuration" },
need["message"].as_str().unwrap_or_default()
));
}
text.push_str(&format!(
" {:width$} {}: {}{}\n",
candidate["id"].as_str().unwrap_or_default(),
Expand Down
185 changes: 185 additions & 0 deletions packages/cli/src/explore/typescript.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
//! `typescript-public-api` proposals: one per package that declares its public API (`exports`, `types` or `typings`)
//! beside a `tsconfig.json`, with that tsconfig as its input, so the extractor finds the package and its entrypoints
//! from the `exports` it already reads. A repository with no such package gets the extractor's one proposal, marked as
//! needing configuration. Each says when the repository's own TypeScript, which the extractor uses, isn't installed.

use serde_json::{Value, json};
use std::path::Path;

use super::{EXAMPLES, candidate, slug};

pub(super) const EXTRACTOR: &str = "typescript-public-api";

/// The proposals for `files` (paths relative to the project in the repository at `root`), which the descriptor's
/// detection `pattern` matched `count` of.
pub(super) fn candidates(
root: &Path,
descriptor: &Value,
files: &[String],
authored: &[&Value],
pattern: &str,
count: usize,
) -> Vec<Value> {
let project = crate::project::directory(root);
let mut seen = std::collections::BTreeSet::new();
let mut found: Vec<Value> = files
.iter()
.filter(|file| file.rsplit('/').next() == Some("package.json"))
.filter_map(|manifest| {
let directory = manifest.strip_suffix("package.json").unwrap_or_default().trim_end_matches('/');
let tsconfig = if directory.is_empty() {
"tsconfig.json".to_owned()
} else {
format!("{directory}/tsconfig.json")
};
if !files.contains(&tsconfig) {
return None;
}
let value: Value = serde_json::from_slice(&std::fs::read(project.join(manifest)).ok()?).ok()?;
if ["exports", "types", "typings"].iter().all(|field| value.get(*field).is_none()) {
return None;
}
let name = value["name"]
.as_str()
.unwrap_or(if directory.is_empty() { "root" } else { directory });
let id = unique(&mut seen, slug(name.rsplit('/').next().unwrap_or(name)), &slug(directory));
let mut definition = descriptor["template"].clone();
definition["id"] = json!(id);
definition["title"] = json!(format!("{}: {name}", descriptor["title"].as_str().unwrap_or(EXTRACTOR)));
definition["inputs"] = json!({"tsconfig": tsconfig});
let adopted = authored
.iter()
.find(|item| {
item["id"] == id.as_str() || (item["extractor"] == EXTRACTOR && item["inputs"]["tsconfig"] == tsconfig.as_str())
})
.and_then(|item| item["id"].as_str());
let basis = json!({"pattern": "**/package.json", "count": 1, "examples": [manifest], "file": manifest});
let mut proposal = candidate(descriptor, &id, basis, adopted, definition);
proposal["needs"] = json!(installed(&project, directory).into_iter().collect::<Vec<_>>());
Some(proposal)
})
.collect();
if found.is_empty() {
let basis = json!({
"pattern": pattern,
"count": count,
"examples": files.iter().filter(|file| file.ends_with("tsconfig.json")).take(EXAMPLES).collect::<Vec<_>>(),
});
let mut proposal = candidate(descriptor, EXTRACTOR, basis, adopted(authored), descriptor["template"].clone());
let mut needs = vec![json!({"kind": "configuration", "message":
"no package declares its public API (exports, types or typings) beside a tsconfig.json: set inputs.tsconfig, or inputs.entrypoints"})];
needs.extend(installed(&project, ""));
proposal["needs"] = json!(needs);
found.push(proposal);
}
found
}

/// The first of `<extractor>-<name>`, `<extractor>-<directory>`, `<extractor>-<directory>-2`, … not yet `seen`.
fn unique(seen: &mut std::collections::BTreeSet<String>, name: String, directory: &str) -> String {
let mut candidates = [name, directory.to_owned()]
.into_iter()
.chain((2..).map(|number| format!("{directory}-{number}")))
.map(|suffix| format!("{EXTRACTOR}-{suffix}"));
loop {
let id = candidates.next().unwrap_or_default();
if seen.insert(id.clone()) {
return id;
}
}
}

fn adopted<'a>(authored: &[&'a Value]) -> Option<&'a str> {
authored
.iter()
.find(|item| item["extractor"] == EXTRACTOR || item["id"] == EXTRACTOR)
.and_then(|item| item["id"].as_str())
}

/// Why the extractor can't run yet in `directory` (project-relative): the repository's own `typescript` isn't installed
/// there or above it, as Node resolves it.
fn installed(project: &Path, directory: &str) -> Option<Value> {
let start = project.join(directory);
let found = start
.ancestors()
.take_while(|ancestor| ancestor.starts_with(project))
.any(|ancestor| ancestor.join("node_modules").join("typescript").join("package.json").is_file());
(!found).then(|| {
json!({"kind": "install", "message":
"the repository's own TypeScript isn't installed (npm ci, pnpm install)"})
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn every_proposal_has_its_own_id() {
let mut seen = std::collections::BTreeSet::new();
let ids: Vec<String> = [("sdk", "a"), ("sdk", "b"), ("b", "c"), ("b", "c")]
.iter()
.map(|(name, directory)| unique(&mut seen, (*name).to_owned(), directory))
.collect();
assert_eq!(
ids,
[
"typescript-public-api-sdk",
"typescript-public-api-b",
"typescript-public-api-c",
"typescript-public-api-c-2"
]
);
}

#[test]
fn a_package_that_declares_its_api_beside_a_tsconfig_is_proposed_with_it() {
let root = tempfile::tempdir().unwrap();
let write = |path: &str, text: &str| {
let path = root.path().join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
write("package.json", r#"{"name": "repo", "private": true}"#);
write("tsconfig.json", "{}");
write(
"packages/sdk/package.json",
r#"{"name": "@acme/sdk", "exports": {".": "./dist/index.js"}}"#,
);
write("packages/sdk/tsconfig.json", "{}");
write("packages/app/package.json", r#"{"name": "app"}"#);
write("packages/app/tsconfig.json", "{}");
write("node_modules/typescript/package.json", "{}");
let files: Vec<String> = [
"package.json",
"tsconfig.json",
"packages/sdk/package.json",
"packages/sdk/tsconfig.json",
"packages/app/package.json",
"packages/app/tsconfig.json",
]
.map(str::to_owned)
.into();
let descriptor = crate::collectors::catalog()["extractors"]
.as_array()
.unwrap()
.iter()
.find(|item| item["id"] == EXTRACTOR)
.unwrap()
.clone();
let found = candidates(root.path(), &descriptor, &files, &[], "**/tsconfig.json", 3);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0]["id"], "typescript-public-api-sdk");
assert_eq!(found[0]["definition"]["inputs"], json!({"tsconfig": "packages/sdk/tsconfig.json"}));
assert_eq!(found[0]["needs"], json!([]));
// Without TypeScript installed it says so; without a declared API, it needs configuration.
std::fs::remove_dir_all(root.path().join("node_modules")).unwrap();
let found = candidates(root.path(), &descriptor, &files, &[], "**/tsconfig.json", 3);
assert_eq!(found[0]["needs"][0]["kind"], "install");
let bare: Vec<String> = files.iter().filter(|file| !file.contains("sdk")).cloned().collect();
let found = candidates(root.path(), &descriptor, &bare, &[], "**/tsconfig.json", 2);
assert_eq!(found[0]["id"], EXTRACTOR);
let kinds: Vec<&Value> = found[0]["needs"].as_array().unwrap().iter().map(|need| &need["kind"]).collect();
assert_eq!(kinds, [&json!("configuration"), &json!("install")]);
}
}
29 changes: 21 additions & 8 deletions packages/cli/src/sweep/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ pub fn text(changes: &[Change], rows: &[Value], cells: &[Value]) -> String {
text
}

/// A ready projection's lines: the changes it changed on, its signal and its first failure.
/// A ready projection's lines: the changes it changed on, its signal and why it first failed.
fn row_text(text: &mut String, id: &str, tally: &signal::Tally, changes: &[Change], cells: &[Value]) {
let mine: Vec<&Value> = cells.iter().filter(|cell| cell["projection"] == id).collect();
let changed: Vec<String> = changes
Expand Down Expand Up @@ -254,23 +254,36 @@ fn row_text(text: &mut String, id: &str, tally: &signal::Tally, changes: &[Chang
} else {
format!(": {}", changed.join(", "))
},
if tally.failed > 0 {
format!("; failed on {}", tally.failed)
} else {
String::new()
match mine.iter().find(|cell| cell["status"] == "failed") {
Some(cell) if tally.failed > 0 => format!("; failed on {}: {}", tally.failed, failure_reason(cell)),
_ => String::new(),
},
));
if let Some(note) = signal::note(tally) {
text.push_str(&format!(" {note}\n"));
}
if let Some(failed) = mine.iter().find(|cell| cell["status"] == "failed") {
text.push_str(&format!(" first failure: {}\n", failed["error"].as_str().unwrap_or_default()));
for line in failed["stderr"].as_str().into_iter().flat_map(|stderr| last_lines(stderr, 5)) {
// What the extractor said before the reason the summary line gives.
if let Some(stderr) = mine
.iter()
.find(|cell| cell["status"] == "failed")
.and_then(|cell| cell["stderr"].as_str())
{
let said: Vec<&str> = last_lines(stderr.trim_end(), 5).collect();
for line in &said[..said.len().saturating_sub(1)] {
text.push_str(&format!(" {line}\n"));
}
}
}

/// Why a swept cell failed, in the extractor's own words when it said any (its last line of standard error), else the
/// runner's.
pub fn failure_reason(cell: &Value) -> String {
let said = cell["stderr"]
.as_str()
.and_then(|stderr| stderr.lines().rev().map(str::trim).find(|line| !line.is_empty()));
said.or(cell["error"].as_str()).unwrap_or("it failed").to_owned()
}

/// The last `count` lines of `text`.
fn last_lines(text: &str, count: usize) -> impl Iterator<Item = &str> {
let lines: Vec<&str> = text.lines().collect();
Expand Down
13 changes: 11 additions & 2 deletions packages/cli/src/sweep/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ fn failed_cells_keep_the_end_of_the_extractors_stderr() {
let cells = vec![json!({"projection": "api", "before": "a0", "after": "a1", "status": "failed",
"error": "Extractor api exited with exit status: 1", "stderr": "one\ntwo\nthree\nfour\nfive\nsix\nTypeError: x is undefined"})];
let text = super::text(&[change], &rows, &cells);
assert!(text.contains("first failure: Extractor api exited with exit status: 1\n"), "{text}");
assert!(text.contains(" TypeError: x is undefined\n"), "{text}");
// The reason ends the summary line, the lines before it under it.
assert!(text.contains("failed on 1: TypeError: x is undefined\n"), "{text}");
assert!(text.contains(" six\n") && !text.contains(" TypeError"), "{text}");
assert!(!text.contains(" two\n"), "only the last lines: {text}");
}

Expand Down Expand Up @@ -138,3 +139,11 @@ fn a_few_changes_are_too_few_to_judge() {
.collect();
assert_eq!(super::signal::tally("map", &cells).signal, super::signal::Signal::Noisy, "4 of 5");
}

#[test]
fn a_failure_is_said_in_the_extractor_s_own_words() {
let cell = json!({"status": "failed", "error": "Extractor x exited with exit status: 1",
"stderr": "warming up\nDuplicate workspace package name \"superego\"\n\n"});
assert_eq!(super::failure_reason(&cell), "Duplicate workspace package name \"superego\"");
assert_eq!(super::failure_reason(&json!({"error": "Timed out"})), "Timed out");
}
2 changes: 1 addition & 1 deletion packages/cli/src/tools/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub fn catalog() -> Vec<Tool> {
Tool {
name: "explore",
title: "Explore projections",
description: "Find the built-in projections that apply to this repository, each with the files that suggested it (its reason), whether it is already adopted, and whether it runs repository code. Runs nothing. Follow with sweep to see what each shows on recent changes; adopt only what the person chooses.",
description: "Find the built-in projections that apply to this repository, each with the files that suggested it (its reason), whether it is already adopted, whether it runs repository code, and what it needs first (configuration, or an install such as the repository's own TypeScript). Runs nothing. Follow with sweep to see what each shows on recent changes; adopt only what the person chooses.",
input_schema: object(json!({}), &[]),
read_only: true,
destructive: false,
Expand Down
3 changes: 3 additions & 0 deletions packages/extractors/typescript-support/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ publish = false
anyhow = "1"
projections-extractor-sdk = { path = "../sdk" }
serde_json = { version = "1", features = ["float_roundtrip"] }

[dev-dependencies]
projections-extractor-sdk = { path = "../sdk", features = ["testing"] }
Loading
Loading