From 83531adc5448a0a722c0b5d99cc5c05803b079fd Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:45:36 +0000 Subject: [PATCH 1/7] Sweep ranking: discount bot updates; lockfile-only transitive churn is version-only Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/runner/commands.md | 47 +++- docs/setup/quick-start.md | 8 +- packages/cli/src/commands/explore.rs | 2 + packages/cli/src/onboard/tests.rs | 2 + packages/cli/src/service/sweeps.rs | 2 + packages/cli/src/sweep/bots.rs | 47 ++++ packages/cli/src/sweep/mod.rs | 86 +++++- packages/cli/src/sweep/run.rs | 169 +++++++++--- packages/cli/src/sweep/signal.rs | 101 +++++-- packages/cli/src/sweep/tests.rs | 264 ++++++++++++++++--- packages/cli/templates/SKILL.md | 12 +- packages/cli/tests/authoring.rs | 124 +++++++++ packages/host/inspector/src/sweep/stats.ts | 49 +++- packages/host/inspector/test/client.test.mjs | 38 ++- packages/schemas/internal/runner-api.json | 26 +- packages/schemas/src/runner/api.ts | 12 +- tools/scripts/reference-docs/agents.mjs | 3 +- 17 files changed, 853 insertions(+), 139 deletions(-) create mode 100644 packages/cli/src/sweep/bots.rs diff --git a/docs/runner/commands.md b/docs/runner/commands.md index c551cba80..a997f5ac2 100644 --- a/docs/runner/commands.md +++ b/docs/runner/commands.md @@ -63,20 +63,39 @@ projections validate /tmp/services.extraction.json those that changed more often, those that changed on four in five or more (likely noise), and those that never changed, followed by a summary of which are worth a look. Fewer than four changes aren't judged. A change that only - updates version strings, such as a dependency or action bump, is marked - `versionOnly` and doesn't count, so a projection with only bumps is `quiet`. - Use `-p ID` to narrow the sweep, and `--json` to print the `projections.sweep` - document with each ready projection's `signal` (`rare`, `steady`, `unknown`, - `noisy`, or `quiet`), `changed`, `versionOnly` and `failed` counts. While - running, the sweep writes progress to standard error (one line per change when - stderr isn't a terminal). In a shallow clone, it notes how many changes are - missing from history and suggests `git fetch --unshallow`. On a busy - repository, where the last 100 merges may span only a few hours, pass - `--since` with a date (`2026-11-01`) or duration (`30d`, `2w`, `3m`) to sweep - `--last N` changes spaced evenly across all changes since then. The sweep - notes how many changes the window held. At the end, it prints how many - extractions failed and the first reason, exiting nonzero if all failed. - Projections that run repository code are skipped unless `--trust` is passed. + updates versions is marked `versionOnly` and doesn't count, so a projection + with only bumps is `quiet`. Only dependency-like projections, those drawn with + the `dependencies` or `github-actions` renderer, can be version-only: an item + must differ only in its version attributes (a package's `version`, a + dependency's range and `resolved` version, or an action's `ref`, a reusable + workflow's `@ref` and an image's tag), and in a dependency graph a lockfile + update may also add or drop transitive packages, as long as no direct + dependency is added or removed and no workspace member changes other than in + its own version. A custom projection whose items carry versions (each + release's, say) always counts them. A change a bot made is marked `bot` and + counts a quarter as much: by its author for a squash or rebase merge (or its + committer), and by the pull request's author (the merged branch's head) for a + merge commit. Bots are `[bot]` accounts, Renovate, Dependabot and the common + release-notes and changeset bots, listed in one place, `BOT_AUTHORS` in + `packages/cli/src/sweep/bots.rs`. A quarter keeps a run of bumps from deciding + a projection's signal, which then rests on the changes people made; and once + four changes people made were judged, a projection that changed only on bot + changes is `quiet`. The summary says how many changes were bot updates + (`7 of 20 changes were bot updates`). Neither rule changes an extraction, a + comparison or a picture, only the ranking. Use `-p ID` to narrow the sweep, + and `--json` to print the `projections.sweep` document with `botChanges`, each + change's `author` and `bot`, and each ready projection's `signal` (`rare`, + `steady`, `unknown`, `noisy`, or `quiet`), `changed`, `bots`, `versionOnly` + and `failed` counts. While running, the sweep writes progress to standard + error (one line per change when stderr isn't a terminal). In a shallow clone, + it notes how many changes are missing from history and suggests + `git fetch --unshallow`. On a busy repository, where the last 100 merges may + span only a few hours, pass `--since` with a date (`2026-11-01`) or duration + (`30d`, `2w`, `3m`) to sweep `--last N` changes spaced evenly across all + changes since then. The sweep notes how many changes the window held. At the + end, it prints how many extractions failed and the first reason, exiting + nonzero if all failed. Projections that run repository code are skipped unless + `--trust` is passed. - `adopt ID...` writes definitions for the chosen explore candidates into `.github/projections/ID.json` (or `.projections/` if the repository uses it, never overwriting an existing file) and adds the `--bookmarks N` (default 3) diff --git a/docs/setup/quick-start.md b/docs/setup/quick-start.md index 59b82017d..e0b5245b7 100644 --- a/docs/setup/quick-start.md +++ b/docs/setup/quick-start.md @@ -67,8 +67,12 @@ projections explore --sweep The sweep reports how often each projection changed across those pull requests and distinguishes noisy ones (changing on nearly every pull request) from -structural ones (showing up only when a change reshapes something). Pass -`--json` if you want structured output for scripts or tools. +structural ones (showing up only when a change reshapes something). Dependency +bumps count for less: a pull request from Renovate, Dependabot or a release bot +counts a quarter as much, and in a dependency projection one that only moves +versions, transitive lockfile entries included, doesn't count. Neither changes +what a projection extracts or draws, only how the sweep ranks it. Pass `--json` +if you want structured output for scripts or tools. In a busy repository, the last 20 merges might cover only a few hours, so every projection looks quiet. Pass `--since` to widen the window: diff --git a/packages/cli/src/commands/explore.rs b/packages/cli/src/commands/explore.rs index 98dff31d4..4dff887a1 100644 --- a/packages/cli/src/commands/explore.rs +++ b/packages/cli/src/commands/explore.rs @@ -273,6 +273,7 @@ fn explore_sweep(root: &Path, args: Explore, candidates: Vec) -> Result<( row["signal"] = json!(tally.signal.name()); row["changed"] = json!(tally.changed); row["versionOnly"] = json!(tally.versions); + row["bots"] = json!(tally.bots); row["failed"] = json!(tally.failed); } row @@ -281,6 +282,7 @@ fn explore_sweep(root: &Path, args: Explore, candidates: Vec) -> Result<( output( &json!({"format": "projections.sweep", "version": 0, "changes": changes.iter().map(sweep::Change::json).collect::>(), + "botChanges": changes.iter().filter(|change| change.bot).count(), "projections": rows, "cells": cells, "notes": notes}), None, 32 * 1024 * 1024, diff --git a/packages/cli/src/onboard/tests.rs b/packages/cli/src/onboard/tests.rs index 59c78f59b..330355568 100644 --- a/packages/cli/src/onboard/tests.rs +++ b/packages/cli/src/onboard/tests.rs @@ -16,6 +16,8 @@ fn change(after: &str, number: Option) -> sweep::Change { number, kind: "merge", date: String::new(), + author: None, + bot: false, } } diff --git a/packages/cli/src/service/sweeps.rs b/packages/cli/src/service/sweeps.rs index c46c67230..fe3cb9d07 100644 --- a/packages/cli/src/service/sweeps.rs +++ b/packages/cli/src/service/sweeps.rs @@ -194,6 +194,8 @@ pub(super) fn start_sweep(state: &Arc, body: &Value) -> Result bool { + let (name, email) = (name.trim().to_ascii_lowercase(), email.trim().to_ascii_lowercase()); + if name.ends_with("[bot]") || email.contains("[bot]@") { + return true; + } + BOT_AUTHORS + .iter() + .any(|bot| *bot == name || *bot == email || email.split_once('@').is_some_and(|(local, _)| local == *bot)) +} diff --git a/packages/cli/src/sweep/mod.rs b/packages/cli/src/sweep/mod.rs index 1bfa8bdad..a254c48c5 100644 --- a/packages/cli/src/sweep/mod.rs +++ b/packages/cli/src/sweep/mod.rs @@ -11,6 +11,10 @@ //! digest and the revision's Git tree, each revision is materialized once for //! every projection, and at most [`DEFAULT_CONCURRENCY`] extractor processes //! run at once. +//! +//! Bot changes ([`bots`]) and changes that only move versions are swept like +//! any other; they only count for less, or not at all, when projections are +//! ranked ([`signal`]). Neither changes an extraction, a comparison or a picture. use crate::runtime::Runner; use anyhow::{Context as _, Result}; @@ -21,6 +25,7 @@ use std::{ sync::{Arc, Mutex}, }; +pub mod bots; mod run; pub mod signal; mod titles; @@ -52,12 +57,20 @@ pub struct Change { /// `merge` (a merge commit) or `commit`. pub kind: &'static str, pub date: String, + /// Who made it: a commit's author, or the author of the pull request a merge merged. + pub author: Option, + /// Whether a bot made it ([`bots`]), so it counts for less when projections are ranked. + pub bot: bool, } impl Change { pub fn json(&self) -> Value { - json!({"before": self.before, "after": self.after, "title": self.title, - "number": self.number, "kind": self.kind, "date": self.date}) + let mut value = json!({"before": self.before, "after": self.after, "title": self.title, + "number": self.number, "kind": self.kind, "date": self.date, "bot": self.bot}); + if let Some(author) = &self.author { + value["author"] = json!(author); + } + value } /// How a change reads: `#123`, else the short commit. @@ -69,18 +82,33 @@ impl Change { /// Changes from `git log -z --format=LOG_FORMAT`: each commit compared with its first parent. A merge's title comes /// from its message, else from its merged branch's subject. -pub(super) const LOG_FORMAT: &str = "--format=%H%x09%P%x09%cI%x09%s%x09%b"; +pub(super) const LOG_FORMAT: &str = "--format=%H%x09%P%x09%cI%x09%an%x09%ae%x09%cn%x09%ce%x09%s%x09%b"; pub(super) fn parse_log(runner: &Runner, root: &Path, text: &str) -> Vec { - text.split('\0') - .filter_map(|record| { - let mut parts = record.trim_start_matches('\n').splitn(5, '\t'); - let (commit, parents, date, subject) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?); - let body = parts.next().unwrap_or_default(); + let records: Vec> = text + .split('\0') + .map(|record| record.trim_start_matches('\n').splitn(9, '\t').collect()) + .filter(|parts: &Vec<&str>| parts.len() >= 8) + .collect(); + // A merge's pull request author is its merged branch's head author: every merge's, in one call. + let merged: Vec<&str> = records.iter().filter_map(|parts| parts[1].split(' ').nth(1)).collect(); + let authors = authors(runner, root, &merged); + records + .into_iter() + .filter_map(|parts| { + let (commit, parents, date, subject) = (parts[0], parts[1], parts[2], parts[7]); + let body = parts.get(8).copied().unwrap_or_default(); let mut parents = parents.split(' ').filter(|parent| !parent.is_empty()); let parent = parents.next()?; let second = parents.next(); let merge = second.is_some(); + let (author, bot) = match second.and_then(|second| authors.get(second)) { + Some((name, email)) => (name.clone(), bots::is_bot(name, email)), + None => ( + parts[3].to_owned(), + bots::is_bot(parts[3], parts[4]) || (!merge && bots::is_bot(parts[5], parts[6])), + ), + }; Some(Change { before: parent.to_owned(), after: commit.to_owned(), @@ -88,11 +116,32 @@ pub(super) fn parse_log(runner: &Runner, root: &Path, text: &str) -> Vec number: number(subject, merge), kind: if merge { "merge" } else { "commit" }, date: date.to_owned(), + author: Some(author), + bot, }) }) .collect() } +/// Each commit's author name and email; none when Git can't say. +fn authors(runner: &Runner, root: &Path, commits: &[&str]) -> HashMap { + if commits.is_empty() { + return HashMap::new(); + } + let mut args = vec!["log", "-z", "--no-walk=unsorted", "--format=%H%x09%an%x09%ae"]; + args.extend(commits); + let Ok(text) = runner.git_text(root, &args) else { + return HashMap::new(); + }; + text.split('\0') + .filter_map(|record| { + let mut parts = record.trim_start_matches('\n').splitn(3, '\t'); + let (commit, name, email) = (parts.next()?, parts.next()?, parts.next()?); + Some((commit.to_owned(), (name.to_owned(), email.trim_end().to_owned()))) + }) + .collect() +} + /// The last `last` changes into `HEAD`. They are the first-parent merges when /// merges are how this branch takes changes: at least half of its last `last` /// first-parent commits. Otherwise (a repository that squashes or rebases, @@ -262,6 +311,9 @@ pub fn text(changes: &[Change], rows: &[Value], cells: &[Value]) -> String { changes.len(), if changes.len() == 1 { "" } else { "s" } ); + if let Some(note) = bot_note(changes.iter().filter(|change| change.bot).count(), changes.len()) { + text.push_str(&format!(" {note}\n")); + } let ranked = signal::ranked(rows, &cells.iter().collect::>()); for (row, tally) in &ranked { let id = row["projection"].as_str().unwrap_or_default(); @@ -284,6 +336,19 @@ pub fn text(changes: &[Change], rows: &[Value], cells: &[Value]) -> String { text } +/// How many of a sweep's changes bots made, when any did: `7 of 20 changes were bot updates`, and what that means +/// for the ranking. +pub fn bot_note(bots: usize, changes: usize) -> Option { + (bots > 0).then(|| { + format!( + "{bots} of {changes} change{} {} bot update{} (Renovate, Dependabot, release bots), which count a quarter as much as other changes when ranking", + if changes == 1 { "" } else { "s" }, + if bots == 1 { "was a" } else { "were" }, + if bots == 1 { "" } else { "s" }, + ) + }) +} + /// How many of a sweep's cells failed, and the first reason, when any did. pub fn failures(cells: &[Value]) -> Option { let failed: Vec<&Value> = cells.iter().filter(|cell| cell["status"] == "failed").collect(); @@ -319,12 +384,13 @@ fn row_text(text: &mut String, id: &str, tally: &signal::Tally, changes: &[Chang let cell = mine.iter().find(|cell| cell["after"] == change.after.as_str())?; (cell["status"] == "changed" && cell["versionOnly"] != true).then(|| { format!( - "{} ({} change{}, {} step{})", + "{} ({} change{}, {} step{}{})", change.label(), cell["changes"], if cell["changes"] == 1 { "" } else { "s" }, cell["steps"], - if cell["steps"] == 1 { "" } else { "s" } + if cell["steps"] == 1 { "" } else { "s" }, + if change.bot { ", bot update" } else { "" } ) }) }) diff --git a/packages/cli/src/sweep/run.rs b/packages/cli/src/sweep/run.rs index 5200146de..f1db500a6 100644 --- a/packages/cli/src/sweep/run.rs +++ b/packages/cli/src/sweep/run.rs @@ -20,8 +20,9 @@ use std::{ /// Runs a sweep, reporting each projection row's failure and each cell as it /// finishes. Rows: `{projection, status: "ready"|"trust"|"failed", error?}`; -/// cells: `{projection, before, after, status: "changed"|"unchanged"|"failed", changes, steps, counts, error?, stderr?}`, -/// `stderr` being the end of a failed extractor's stderr. +/// cells: `{projection, before, after, status: "changed"|"unchanged"|"failed", changes, steps, counts, error?, stderr?, +/// versionOnly?, bot?}`, `stderr` being the end of a failed extractor's stderr, `versionOnly` marking a change that +/// only moved versions ([`version_only`]) and `bot` one a bot made ([`super::bots`]). pub fn run(runner: &Runner, request: Request<'_>, on_row: &(dyn Fn(Value) + Sync), on_cell: &(dyn Fn(Cell) + Sync)) -> Result<()> { let root = runner.repository_root()?; let prepared = prepare(runner, &request.projections, on_row); @@ -209,7 +210,10 @@ impl Sweep<'_> { /// One projection on one change: its comparison, or why it failed. fn cell(&self, id: &str, definition: &Prepared, change: &Change) -> Cell { - let base = json!({"projection": id, "before": change.before, "after": change.after}); + let mut base = json!({"projection": id, "before": change.before, "after": change.after}); + if change.bot { + base["bot"] = json!(true); + } let (before, after) = match ( self.extraction(id, definition, &change.before), self.extraction(id, definition, &change.after), @@ -219,7 +223,8 @@ impl Sweep<'_> { }; match artifact::compare_extractions_with(&before, &after, definition.rules.as_deref()) { Ok(comparison) => { - let versions = version_only(&comparison, &before, &after); + let versions = + Versioning::of(&definition.definition).is_some_and(|versioning| version_only(versioning, &comparison, &before, &after)); let mut cell = compared(base, comparison); if versions { cell.value["versionOnly"] = json!(true); @@ -244,45 +249,149 @@ fn compared(mut value: Value, comparison: Value) -> Cell { } } -/// Whether every change a comparison found only moved version strings, as a -/// dependency or action bump does (`v4` to `v5`, `1.2.3` to `1.3.0`, one -/// pinned commit to another): items modified, none added, removed or renamed, -/// and each the same once its versions are masked. -pub(super) fn version_only(comparison: &Value, before: &Value, after: &Value) -> bool { +/// How a dependency-like projection's items carry versions, the only projections whose changes can be version-only. +/// It is told by the definition's renderer, which says what its items are: `dependencies` (packages and the +/// dependencies between them, each with its `version`) or `github-actions` (jobs and the actions, reusable +/// workflows and images they pin). Any other projection, a custom one whose items happen to carry versions +/// included, is never version-only: a version there is what it shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Versioning { + Dependencies, + Actions, +} + +impl Versioning { + pub(super) fn of(definition: &Value) -> Option { + match definition["renderer"].as_str()? { + "dependencies" => Some(Self::Dependencies), + "github-actions" => Some(Self::Actions), + _ => None, + } + } + + /// The data fields that hold an item's version, at any depth. + fn attributes(self) -> &'static [&'static str] { + match self { + // A package's version, a declaration's range and the version it resolved to, a pinned revision. + Self::Dependencies => &["version", "resolved", "revision"], + // An action's ref, a reusable workflow's `@ref`, an image's tag or digest. + Self::Actions => &["ref", "uses", "image"], + } + } +} + +/// Entity kinds a dependency graph starts from besides workspace members: projects and their target frameworks, +/// and Swift packages' targets and products. Keep with the dependencies renderer's (`rootKinds` in +/// packages/renderers/graph/src/dependencies/kinds.ts). +const ROOT_KINDS: &[&str] = &["project", "target-framework", "target", "product"]; +/// Relationship kinds that record membership rather than a dependency: NuGet's `resolved`. +const MEMBERSHIP_KINDS: &[&str] = &["resolved"]; + +/// Whether every change a comparison found only moved versions, as a dependency or action bump does (`v4` to `v5`, +/// `1.2.3` to `1.3.0`, one pinned commit to another), for a projection that carries versions as `versioning` says. +/// +/// Every modified item must be the same once its version attributes are masked (and its label, where the label is +/// its version, as a dependency's declared range is). In a dependency graph, packages installed only transitively +/// and the dependencies between them may also be added or removed, as a lockfile's churn adds and drops them; but a +/// direct dependency (one a workspace member, project or target declares) added or removed, or a workspace member +/// added, removed or changed other than in its own version, is a real change. +pub(super) fn version_only(versioning: Versioning, comparison: &Value, before: &Value, after: &Value) -> bool { let Some(changes) = comparison["comparison"]["changes"].as_array().filter(|changes| !changes.is_empty()) else { return false; }; - fn item<'a>(document: &'a Value, change: &Value, side: &str) -> Option<&'a Value> { - let id = change[side][0].as_str()?; - let collection = change["collection"].as_str()?; - document["extraction"][collection].as_array()?.iter().find(|item| item["id"] == id) - } changes.iter().all(|change| { - change["status"] == "modified" - && matches!( - (item(before, change, "before"), item(after, change, "after")), - (Some(old), Some(new)) if masked(old) == masked(new) - ) + let old = item(before, change, "before"); + let new = item(after, change, "after"); + match change["status"].as_str() { + Some("modified") => matches!( + (old, new), + (Some(old), Some(new)) if masked(versioning, old) == masked(versioning, new) + ), + Some("added") if versioning == Versioning::Dependencies => { + new.is_some_and(|new| transitive(after, change["collection"].as_str(), new)) + } + Some("removed") if versioning == Versioning::Dependencies => { + old.is_some_and(|old| transitive(before, change["collection"].as_str(), old)) + } + _ => false, + } }) } -/// An item with every version-like string masked and its evidence left out. -fn masked(item: &Value) -> Value { +/// A changed item on one side of a comparison. +fn item<'a>(document: &'a Value, change: &Value, side: &str) -> Option<&'a Value> { + let id = change[side][0].as_str()?; + let collection = change["collection"].as_str()?; + document["extraction"][collection].as_array()?.iter().find(|item| item["id"] == id) +} + +/// Whether a dependency graph's entity is a root: a workspace member, or a project, framework or target. +fn root(entity: &Value) -> bool { + entity["data"]["workspaceMember"] == true || entity["kind"].as_str().is_some_and(|kind| ROOT_KINDS.contains(&kind)) +} + +/// Whether a dependency graph's item is only transitive: a package that isn't a root, or a dependency (or membership) +/// that no root declares. +fn transitive(document: &Value, collection: Option<&str>, item: &Value) -> bool { + match collection { + Some("entities") => !root(item), + Some("relationships") => { + item["kind"].as_str().is_some_and(|kind| MEMBERSHIP_KINDS.contains(&kind)) + || document["extraction"]["entities"] + .as_array() + .and_then(|entities| entities.iter().find(|entity| entity["id"] == item["from"])) + .is_some_and(|from| !root(from)) + } + _ => false, + } +} + +/// An item with the versions in its version attributes masked (and its label, where its label is its version), and +/// its evidence left out. +fn masked(versioning: Versioning, item: &Value) -> Value { + let mut item = item.clone(); + let Some(fields) = item.as_object_mut() else { + return item; + }; + fields.remove("evidence"); + let version = fields.get("data").and_then(|data| data["version"].as_str()).map(str::to_owned); + if version.is_some() && fields.get("label").and_then(Value::as_str) == version.as_deref() { + fields.insert("label".to_owned(), mask(&fields["label"])); + } + if let Some(data) = fields.get_mut("data") { + mask_attributes(versioning.attributes(), data); + } + item +} + +/// Masks every version attribute's value, at any depth. +fn mask_attributes(attributes: &[&str], value: &mut Value) { + match value { + Value::Object(fields) => { + for (key, value) in fields.iter_mut() { + if attributes.contains(&key.as_str()) { + *value = mask(value); + } else { + mask_attributes(attributes, value); + } + } + } + Value::Array(items) => items.iter_mut().for_each(|item| mask_attributes(attributes, item)), + _ => {} + } +} + +/// A version attribute's value with every version-like string in it masked. +fn mask(value: &Value) -> Value { static VERSION: std::sync::LazyLock = std::sync::LazyLock::new(|| { // A commit or digest only as a whole value or after `@` (a pinned action or image), not any hash in text. regex::Regex::new(r"^[0-9a-f]{40}$|^[0-9a-f]{64}$|@(?:sha256:)?[0-9a-f]{40,64}\b|\bv?\d+(?:\.\d+)+(?:[-+][0-9A-Za-z.-]+)?|\bv\d+\b") .expect("a valid pattern") }); - match item { + match value { Value::String(text) => Value::String(VERSION.replace_all(text, "").into_owned()), - Value::Array(items) => Value::Array(items.iter().map(masked).collect()), - Value::Object(fields) => Value::Object( - fields - .iter() - .filter(|(key, _)| key.as_str() != "evidence") - .map(|(key, value)| (key.clone(), masked(value))) - .collect(), - ), + Value::Array(items) => Value::Array(items.iter().map(mask).collect()), + Value::Object(fields) => Value::Object(fields.iter().map(|(key, value)| (key.clone(), mask(value))).collect()), other => other.clone(), } } diff --git a/packages/cli/src/sweep/signal.rs b/packages/cli/src/sweep/signal.rs index 462c9e1f7..30150d9b1 100644 --- a/packages/cli/src/sweep/signal.rs +++ b/packages/cli/src/sweep/signal.rs @@ -2,12 +2,27 @@ //! swept changes, and so whether it singles out the changes that reshape the //! system it shows. The Inspector's Explore view judges the same way //! (packages/host/inspector/src/sweep/stats.ts); keep the two together. +//! +//! Two kinds of change count for less. One that only moved versions +//! (`versionOnly` cells) doesn't count as a change at all. One a bot made +//! (`bot` cells, see [`super::bots`]) counts as a quarter of a change ([`BOT_SHARE`]), +//! both when it changed and when it didn't; and once a sweep has judged a +//! projection on enough changes people made ([`JUDGED_FROM`]), changing only on +//! bot changes leaves it quiet. Ranking is all these change: extractions, +//! comparisons and pictures are the same for every change. use serde_json::Value; /// Below this many judged changes (swept and not failed), a projection isn't judged. pub const JUDGED_FROM: usize = 4; +/// How much a bot change counts, as a share of a change people made: a quarter (1 / `BOT_SHARE`). A dependency bump, +/// translation sync or release commit says little about what a projection shows of the work a repository's people +/// do, but not nothing: a bump can still reshape a dependency graph. A quarter keeps a run of them (the 7 bumps of 20 +/// changes a busy repository's Renovate makes) from deciding a projection's signal, which then rests on the changes +/// people made, while a projection that changes on every bot change and every other change stays noisy. +pub const BOT_SHARE: usize = 4; + /// A projection's signal across a sweep, best first. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Signal { @@ -18,7 +33,7 @@ pub enum Signal { Unknown, /// Changed on four in five changes or more: likely noise. Noisy, - /// Never changed. + /// Never changed, apart from versions, or only on bot changes. Quiet, } @@ -39,49 +54,71 @@ impl Signal { pub struct Tally { /// Changes it changed on, apart from those where only versions moved. pub changed: usize, + /// Of those, the bot changes (`bot` cells). + pub bots: usize, /// Changes where only versions moved (`versionOnly` cells): a bump, not a change in what it shows. pub versions: usize, /// Changes it was extracted on both sides of, whether or not it changed. pub judged: usize, + /// Of those, the bot changes. + pub bots_judged: usize, pub failed: usize, pub signal: Signal, } +impl Tally { + /// Changes it changed on, weighted: each bot change counts as 1 / [`BOT_SHARE`] of a change. In shares. + pub fn weighted_changed(&self) -> usize { + (self.changed - self.bots) * BOT_SHARE + self.bots + } + + /// Changes it was judged on, weighted as [`Tally::weighted_changed`] is. + pub fn weighted_judged(&self) -> usize { + (self.judged - self.bots_judged) * BOT_SHARE + self.bots_judged + } +} + /// The tally of `projection`'s cells. pub fn tally<'a>(projection: &str, cells: impl IntoIterator) -> Tally { - let (mut changed, mut versions, mut judged, mut failed) = (0, 0, 0, 0); + let (mut changed, mut bots, mut versions, mut judged, mut bots_judged, mut failed) = (0, 0, 0, 0, 0, 0); for cell in cells.into_iter().filter(|cell| cell["projection"] == projection) { + let bot = cell["bot"] == true; + if cell["status"] != "failed" { + judged += 1; + bots_judged += usize::from(bot); + } match cell["status"].as_str() { Some("failed") => failed += 1, - Some("changed") if cell["versionOnly"] == true => { - versions += 1; - judged += 1; - } + Some("changed") if cell["versionOnly"] == true => versions += 1, Some("changed") => { changed += 1; - judged += 1; + bots += usize::from(bot); } - _ => judged += 1, + _ => {} } } - let signal = if judged < JUDGED_FROM { + let mut tally = Tally { + changed, + bots, + versions, + judged, + bots_judged, + failed, + signal: Signal::Unknown, + }; + let (weighted, of) = (tally.weighted_changed(), tally.weighted_judged()); + tally.signal = if judged < JUDGED_FROM { Signal::Unknown - } else if changed == 0 { + } else if changed == 0 || (changed == bots && judged - bots_judged >= JUDGED_FROM) { Signal::Quiet - } else if changed * 5 >= judged * 4 { + } else if weighted * 5 >= of * 4 { Signal::Noisy - } else if changed * 4 <= judged { + } else if weighted * 4 <= of { Signal::Rare } else { Signal::Steady }; - Tally { - changed, - versions, - judged, - failed, - signal, - } + tally } /// What a tally means, in words, when it means something: why a noisy @@ -93,6 +130,11 @@ pub fn note(tally: &Tally) -> Option { Adopt it only if every change really does; for a custom extractor, look for data that changes for unrelated reasons", tally.changed, tally.judged )), + Signal::Quiet if tally.bots > 0 => Some(format!( + "changed only on bot updates ({} of them), never on the {} other changes: nothing characteristic to show", + tally.bots, + tally.judged - tally.bots_judged + )), Signal::Quiet if tally.versions > 0 => Some(format!( "only versions changed on these {} changes (a dependency or action bump on {} of them): nothing structural to show", tally.judged, tally.versions @@ -123,7 +165,7 @@ pub fn ranked<'a>(rows: impl IntoIterator, cells: &[&Value]) - let (x, y) = (x.expect("ready rows are tallied"), y.expect("ready rows are tallied")); x.signal .cmp(&y.signal) - .then(y.changed.cmp(&x.changed)) + .then(y.weighted_changed().cmp(&x.weighted_changed())) .then(a["projection"].as_str().cmp(&b["projection"].as_str())) }); ready.extend(skipped); @@ -152,7 +194,9 @@ pub fn advice(ranked: &[(&Value, Option)]) -> String { let quiet = |bumped: bool| -> Vec<&str> { ranked .iter() - .filter(|(_, tally)| tally.is_some_and(|tally| tally.signal == Signal::Quiet && (tally.versions > 0) == bumped)) + .filter(|(_, tally)| { + tally.is_some_and(|tally| tally.signal == Signal::Quiet && tally.bots == 0 && (tally.versions > 0) == bumped) + }) .filter_map(|(row, _)| row["projection"].as_str()) .collect() }; @@ -163,11 +207,15 @@ pub fn advice(ranked: &[(&Value, Option)]) -> String { bumped.join(", ") )); } + let botted = names_where(ranked, |tally| tally.signal == Signal::Quiet && tally.bots > 0); + if !botted.is_empty() { + lines.push(format!("Changed only on bot updates: {}.", botted.join(", "))); + } let quiet = quiet(false); if !quiet.is_empty() { lines.push(format!("Never changed here: {}.", quiet.join(", "))); } - if worth.is_empty() && !(noisy.is_empty() && quiet.is_empty() && bumped.is_empty()) { + if worth.is_empty() && !(noisy.is_empty() && quiet.is_empty() && bumped.is_empty() && botted.is_empty()) { lines.push( "None of these singles out particular changes: build a projection of what this repository is about (projections help agents create-projection)." .to_owned(), @@ -175,3 +223,12 @@ pub fn advice(ranked: &[(&Value, Option)]) -> String { } lines.iter().map(|line| format!("{line}\n")).collect() } + +/// The projections whose tallies `wanted` accepts, in ranked order. +fn names_where<'a>(ranked: &[(&'a Value, Option)], wanted: impl Fn(&Tally) -> bool) -> Vec<&'a str> { + ranked + .iter() + .filter(|(_, tally)| tally.as_ref().is_some_and(&wanted)) + .filter_map(|(row, _)| row["projection"].as_str()) + .collect() +} diff --git a/packages/cli/src/sweep/tests.rs b/packages/cli/src/sweep/tests.rs index f46af112d..93047e1cc 100644 --- a/packages/cli/src/sweep/tests.rs +++ b/packages/cli/src/sweep/tests.rs @@ -79,6 +79,8 @@ fn squash_history_with_a_few_old_merges_sweeps_its_commits() { number: None, kind, date: String::new(), + author: None, + bot: false, }; let squashed: Vec<_> = (0..20).map(|_| change("commit")).collect(); assert!(!super::merges_dominate(&squashed)); @@ -104,6 +106,8 @@ fn failed_cells_keep_the_end_of_the_extractors_stderr() { number: Some(7), kind: "commit", date: String::new(), + author: None, + bot: false, }; let rows = vec![json!({"projection": "api", "status": "ready"})]; let cells = vec![json!({"projection": "api", "before": "a0", "after": "a1", "status": "failed", @@ -125,6 +129,8 @@ fn sweeps_rank_projections_by_signal_and_say_which_are_noise() { number: Some(index + 1), kind: "commit", date: String::new(), + author: None, + bot: false, }) .collect(); let rows: Vec<_> = ["map", "ci", "schema", "flags"] @@ -226,57 +232,147 @@ fn a_sweep_counts_its_failed_extractions() { assert!(!super::every_cell_failed(&[]), "a sweep that ran nothing didn't fail"); } +/// A comparison of `changes`: `(collection, id, status)`. +fn compared(changes: &[(&str, &str, &str)]) -> serde_json::Value { + json!({"comparison": {"changes": changes.iter().map(|(collection, id, status)| { + let mut change = json!({"collection": collection, "id": id, "status": status}); + if *status != "added" { + change["before"] = json!([id]); + } + if *status != "removed" { + change["after"] = json!([id]); + } + change + }).collect::>()}}) +} + #[test] -fn a_change_that_only_moves_versions_is_told_apart() { - let document = |reference: &str, version: &str| { +fn an_action_bump_only_moves_versions() { + use super::run::{Versioning, version_only}; + let document = |reference: &str, image: &str| { json!({"extraction": {"entities": [ {"id": "job:build", "kind": "job", "label": "build", - "data": {"steps": {"actions": [{"action": "actions/checkout", "ref": reference}]}}}, - {"id": "package:left", "kind": "package", "label": "left", "data": {"version": version, "requirement": format!("^{version}")}, - "evidence": [{"kind": "file", "source": "package.json"}]}, + "data": {"steps": {"actions": [{"action": "actions/checkout", "ref": reference}]}, + "container": {"image": image}}, + "evidence": [{"kind": "file", "source": ".github/workflows/ci.yml"}]}, ], "relationships": []}}) }; - let modified = |ids: &[&str]| { - json!({"comparison": {"changes": ids.iter().map(|id| json!({"collection": "entities", "id": id, - "status": "modified", "before": [id], "after": [id]})).collect::>()}}) - }; - let before = document("v4", "1.2.3"); - let both = modified(&["job:build", "package:left"]); - assert!(super::run::version_only(&both, &before, &document("v5", "1.3.0-beta.1"))); - let pinned = "11bd71901bbe5b1630ceea73d27597364c9af683"; - assert!(super::run::version_only( - &modified(&["job:build"]), + let job = compared(&[("entities", "job:build", "modified")]); + let actions = |before: &serde_json::Value, after: &serde_json::Value| version_only(Versioning::Actions, &job, before, after); + let before = document("v4", "node:20.1.0"); + assert!(actions(&before, &document("v5", "node:20.2.0"))); + assert!(actions( &before, - &document(pinned, "1.2.3") + &document("11bd71901bbe5b1630ceea73d27597364c9af683", "node:20.1.0") )); - // Anything else that changed, or an item added or removed, is a real change. - assert!(!super::run::version_only( - &modified(&["job:build"]), + let digest = |hash: &str| format!("node@sha256:{}", hash.repeat(64)); + assert!(actions(&document("v4", &digest("a")), &document("v4", &digest("b")))); + // Another ref, or anything outside the version attributes, is a real change. + assert!(!actions(&before, &document("main", "node:20.1.0"))); + let mut renamed = document("v5", "node:20.1.0"); + renamed["extraction"]["entities"][0]["label"] = json!("compile"); + assert!(!actions(&before, &renamed)); + let added = compared(&[("entities", "job:test", "added")]); + assert!(!version_only(Versioning::Actions, &added, &before, &before)); + assert!(!version_only(Versioning::Actions, &compared(&[]), &before, &before)); +} + +/// A Node workspace's dependency graph, as workspace-dependencies extracts it: the workspace `web` (at +/// `version`) declares `a`, which pulls in `b` at `transitive`, and `b` pulls in each of `extra`. +fn graph(version: &str, transitive: &str, extra: &[&str]) -> serde_json::Value { + let mut entities = vec![ + json!({"id": "workspace:web", "kind": "package", "label": "web", + "data": {"workspaceMember": true, "path": ".", "version": version}}), + json!({"id": "package:a", "kind": "external-package", "label": "a", "data": {"version": "1.0.0"}}), + json!({"id": "package:b", "kind": "external-package", "label": "b", "data": {"version": transitive}}), + ]; + let mut relationships = vec![ + json!({"id": "dependency:[\"web\",\"dependencies\",\"a\"]", "kind": "dependencies", "from": "workspace:web", + "to": "package:a", "label": "^1.0.0", "data": {"type": "dependencies", "version": "^1.0.0", "resolved": "1.0.0"}}), + json!({"id": "dependency:[\"package:a\",\"dependencies\",\"b\"]", "kind": "dependencies", "from": "package:a", + "to": "package:b", "label": format!("^{transitive}"), "data": {"type": "dependencies", "version": format!("^{transitive}")}, + "evidence": [{"kind": "file", "source": "package-lock.json"}]}), + ]; + for name in extra { + entities.push(json!({"id": format!("package:{name}"), "kind": "external-package", "label": name, "data": {"version": "0.1.0"}})); + relationships.push(json!({"id": format!("dependency:[\"package:b\",\"dependencies\",\"{name}\"]"), "kind": "dependencies", + "from": "package:b", "to": format!("package:{name}"), "label": "^0.1.0", "data": {"type": "dependencies", "version": "^0.1.0"}})); + } + json!({"extraction": {"entities": entities, "relationships": relationships}}) +} + +#[test] +fn lockfile_only_transitive_churn_only_moves_versions() { + use super::run::{Versioning, version_only}; + let dependencies = |changes: &[(&str, &str, &str)], before: &serde_json::Value, after: &serde_json::Value| { + version_only(Versioning::Dependencies, &compared(changes), before, after) + }; + let b_edge = "dependency:[\"package:a\",\"dependencies\",\"b\"]"; + let c_edge = "dependency:[\"package:b\",\"dependencies\",\"c\"]"; + let before = graph("1.0.0", "2.0.0", &[]); + // A Renovate bump that only rewrote the lockfile: a transitive package moved, pulling in another. + let churned = graph("1.0.0", "2.1.0", &["c"]); + let churn = [ + ("entities", "package:b", "modified"), + ("entities", "package:c", "added"), + ("relationships", b_edge, "modified"), + ("relationships", c_edge, "added"), + ]; + assert!(dependencies(&churn, &before, &churned)); + // And the reverse: the transitive package dropped. + let reverse = [ + ("entities", "package:b", "modified"), + ("entities", "package:c", "removed"), + ("relationships", b_edge, "modified"), + ("relationships", c_edge, "removed"), + ]; + assert!(dependencies(&reverse, &churned, &before)); + // A workspace's own version moving is a bump too. + assert!(dependencies( + &[("entities", "workspace:web", "modified")], &before, - &document("main", "1.2.3") - )); - // A hash in other text is content, not a pin; one after `@` pins an image. - let digest = |prefix: &str, hash: &str| format!("{prefix}sha256:{}", hash.repeat(64)); - let job = modified(&["job:build"]); - assert!(!super::run::version_only( - &job, - &document(&digest("", "a"), "1"), - &document(&digest("", "b"), "1") + &graph("1.1.0", "2.0.0", &[]) )); - assert!(super::run::version_only( - &job, - &document(&digest("node@", "a"), "1"), - &document(&digest("node@", "b"), "1") - )); - let mut renamed = document("v5", "1.2.3"); - renamed["extraction"]["entities"][0]["label"] = json!("compile"); - assert!(!super::run::version_only(&modified(&["job:build"]), &before, &renamed)); - let added = - json!({"comparison": {"changes": [{"collection": "entities", "id": "job:test", "status": "added", "after": ["job:test"]}]}}); - assert!(!super::run::version_only(&added, &before, &before)); - assert!(!super::run::version_only(&json!({"comparison": {"changes": []}}), &before, &before)); - // A projection that changed only versions is quiet, saying so, and not worth a look. + // A direct dependency added, or a workspace added or changed otherwise, is a real change. + let mut declared = graph("1.0.0", "2.0.0", &[]); + declared["extraction"]["relationships"].as_array_mut().unwrap().push(json!({ + "id": "dependency:[\"web\",\"dependencies\",\"d\"]", "kind": "dependencies", "from": "workspace:web", "to": "package:d", + "label": "^1.0.0", "data": {"type": "dependencies", "version": "^1.0.0"}})); + declared["extraction"]["entities"] + .as_array_mut() + .unwrap() + .push(json!({"id": "package:d", "kind": "external-package", "label": "d", "data": {"version": "1.0.0"}})); + let direct = [ + ("entities", "package:d", "added"), + ("relationships", "dependency:[\"web\",\"dependencies\",\"d\"]", "added"), + ]; + assert!(!dependencies(&direct, &before, &declared)); + assert!(!dependencies(&[("entities", "workspace:web", "removed")], &before, &before)); + let mut moved = before.clone(); + moved["extraction"]["entities"][0]["data"]["path"] = json!("apps/web"); + assert!(!dependencies(&[("entities", "workspace:web", "modified")], &before, &moved)); + // So is a package that changed in anything but its version, even a transitive one. + let mut sourced = before.clone(); + sourced["extraction"]["entities"][2]["data"]["source"] = json!("git+https://example.invalid/b.git"); + assert!(!dependencies(&[("entities", "package:b", "modified")], &before, &sourced)); + // Only dependency graphs add and drop transitive packages as churn. + assert!(!version_only(Versioning::Actions, &compared(&churn), &before, &churned)); +} + +#[test] +fn only_dependency_like_projections_are_version_only() { + use super::run::Versioning; + assert_eq!(Versioning::of(&json!({"renderer": "dependencies"})), Some(Versioning::Dependencies)); + assert_eq!(Versioning::of(&json!({"renderer": "github-actions"})), Some(Versioning::Actions)); + // A custom projection whose items carry versions (each release's, say) shows them: they are never only versions. + for renderer in [json!("graph"), json!("architecture"), json!({"bundle": "renderer.js"})] { + assert_eq!(Versioning::of(&json!({"renderer": renderer})), None, "{renderer}"); + } +} + +#[test] +fn a_projection_that_changed_only_versions_is_quiet() { let cell = |status: &str, versions: bool| json!({"projection": "ci", "status": status, "versionOnly": versions}); let cells: Vec<_> = (0..5) .map(|index| cell(if index < 2 { "changed" } else { "unchanged" }, index < 2)) @@ -299,6 +395,88 @@ fn a_change_that_only_moves_versions_is_told_apart() { assert!(!advice.contains("Worth a look"), "{advice}"); } +#[test] +fn bots_are_told_by_name_or_email() { + use super::bots::is_bot; + assert!(is_bot("renovate[bot]", "29139614+renovate[bot]@users.noreply.github.com")); + assert!(is_bot("dependabot[bot]", "49699333+dependabot[bot]@users.noreply.github.com")); + assert!(is_bot( + "github-actions[bot]", + "41898282+github-actions[bot]@users.noreply.github.com" + )); + assert!(is_bot("Renovate Bot", "bot@renovateapp.com")); + assert!(is_bot("semantic-release-bot", "semantic-release-bot@martynus.net")); + assert!(is_bot("Release", "release-please@example.com")); + // GitHub committing a squash merge, and people, aren't. + assert!(!is_bot("GitHub", "noreply@github.com")); + assert!(!is_bot("Claire", "claire@example.com")); + assert!(!is_bot("Robert", "bot.robert@example.com")); +} + +#[test] +fn bot_changes_count_a_quarter_in_a_ranking() { + use super::signal::{Signal, tally}; + // `human` and `bot` changes, the first `human_changed` and `bot_changed` of each changed. + let cells = |human: usize, human_changed: usize, bot: usize, bot_changed: usize| -> Vec { + let cell = + |changed: bool, bot: bool| json!({"projection": "deps", "status": if changed { "changed" } else { "unchanged" }, "bot": bot}); + (0..human) + .map(|index| cell(index < human_changed, false)) + .chain((0..bot).map(|index| cell(index < bot_changed, true))) + .collect() + }; + // Changing on every one of 7 bot bumps and 1 of 13 other changes: 8 of 20 would be steady; it's rare on the + // changes people made. + let busy = tally("deps", &cells(13, 1, 7, 7)); + assert_eq!((busy.changed, busy.bots, busy.judged, busy.bots_judged), (8, 7, 20, 7)); + assert_eq!(busy.signal, Signal::Rare); + // Changing on every change people made, and no bot bump: 13 of 20 would be steady; it's noisy. + assert_eq!(tally("deps", &cells(13, 13, 7, 0)).signal, Signal::Noisy); + // Changing only on bot changes is quiet, once enough other changes were judged, and says so. + let botted = tally("deps", &cells(13, 0, 7, 7)); + assert_eq!(botted.signal, Signal::Quiet); + assert!( + super::signal::note(&botted) + .unwrap() + .contains("changed only on bot updates (7 of them), never on the 13 other changes"), + "{:?}", + super::signal::note(&botted) + ); + let rows = [json!({"projection": "deps", "status": "ready"})]; + let swept = cells(13, 0, 7, 7); + let advice = super::signal::advice(&super::signal::ranked(&rows, &swept.iter().collect::>())); + assert!(advice.contains("Changed only on bot updates: deps."), "{advice}"); + assert!(!advice.contains("Worth a look"), "{advice}"); + // A sweep of mostly bot changes still judges by them, at their weight. + assert_eq!(tally("deps", &cells(2, 0, 18, 3)).signal, Signal::Rare); + // Within a signal, more weighted changes rank first: changes people made outweigh bot changes. + let rows = [ + json!({"projection": "bots", "status": "ready"}), + json!({"projection": "people", "status": "ready"}), + ]; + let mut swept: Vec = cells(16, 1, 4, 3); + swept.extend(cells(16, 2, 4, 0).into_iter().map(|mut cell| { + cell["projection"] = json!("people"); + cell + })); + for cell in swept.iter_mut().take(20) { + cell["projection"] = json!("bots"); + } + let ranked = super::signal::ranked(&rows, &swept.iter().collect::>()); + let order: Vec<_> = ranked.iter().map(|(row, _)| row["projection"].as_str().unwrap()).collect(); + assert_eq!(order, ["people", "bots"]); +} + +#[test] +fn a_sweep_says_how_many_changes_bots_made() { + assert_eq!(super::bot_note(0, 20), None); + assert_eq!( + super::bot_note(7, 20).unwrap(), + "7 of 20 changes were bot updates (Renovate, Dependabot, release bots), which count a quarter as much as other changes when ranking" + ); + assert!(super::bot_note(1, 20).unwrap().starts_with("1 of 20 changes was a bot update ")); +} + #[test] fn since_takes_a_date_or_a_duration_back_from_now() { assert_eq!(since("2026-11-01").unwrap(), "2026-11-01"); @@ -322,6 +500,8 @@ fn a_window_is_swept_at_evenly_spaced_changes_newest_and_oldest_included() { number: None, kind: "merge", date: String::new(), + author: None, + bot: false, }) .collect() }; @@ -379,6 +559,8 @@ fn a_history_without_pull_request_numbers_says_it_looks_rebase_merged() { number, kind, date: "2026-12-01T00:00:00Z".into(), + author: None, + bot: false, }; let rebased = vec![change(None, "commit"); 3]; let note = super::history_note(&rebased).unwrap(); diff --git a/packages/cli/templates/SKILL.md b/packages/cli/templates/SKILL.md index 952f128bc..4cabb0290 100644 --- a/packages/cli/templates/SKILL.md +++ b/packages/cli/templates/SKILL.md @@ -200,9 +200,15 @@ adopt. with `changes`, `steps` and `counts` by kind). Ready rows come best first, each with its `signal`: `rare` (changed on a quarter of the changes or fewer, likely the structural ones), `steady`, `noisy` (on four in five or - more), `quiet` (never) or `unknown` (fewer than four changes swept). A - cell marked `versionOnly` changed only version strings (a dependency or - action bump) and doesn't count as a change. On a busy repository, the last 20 merges may span only hours, leaving every + more), `quiet` (never, or only on bot changes) or `unknown` (fewer than + four changes swept). A cell marked `versionOnly` changed only versions (a + dependency or action bump, or a lockfile update that only moved transitive + packages) and doesn't count as a change; only projections drawn with the + `dependencies` or `github-actions` renderer can be version-only, so a + custom projection whose versions are what it shows always counts them. A + change marked `bot` (Renovate, Dependabot, a release bot; `botChanges` + counts them) counts a quarter as much. Both affect only the ranking, never + extractions, comparisons or pictures. On a busy repository, the last 20 merges may span only hours, leaving every projection `quiet`. Check the changes' dates and sweep again with `--since 30d` (a date or duration) to spread `--last N` changes evenly across that window. diff --git a/packages/cli/tests/authoring.rs b/packages/cli/tests/authoring.rs index a374c709e..187e094e0 100644 --- a/packages/cli/tests/authoring.rs +++ b/packages/cli/tests/authoring.rs @@ -1445,3 +1445,127 @@ fn a_package_manifest_or_lockfile_among_the_definitions_says_to_move_it_into_a_s .count(); assert_eq!(moved, 2, "{messages:?}"); } + +/// An npm package `web` at `version` depending on `a`, which pulls in `b` at `transitive` and `b` each of `extra`. +fn npm_workspace(root: &Path, version: &str, transitive: &str, extra: &[&str]) { + let manifest = json!({"name": "web", "version": version, "dependencies": {"a": "^1.0.0"}}); + fs::write(root.join("package.json"), format!("{manifest:#}\n")).unwrap(); + let mut packages = json!({ + "": {"name": "web", "version": version, "dependencies": {"a": "^1.0.0"}}, + "node_modules/a": {"version": "1.0.0", "dependencies": {"b": format!("^{transitive}")}}, + "node_modules/b": {"version": transitive, "dependencies": {}}, + }); + for name in extra { + packages["node_modules/b"]["dependencies"][*name] = json!("^0.1.0"); + packages[format!("node_modules/{name}")] = json!({"version": "0.1.0"}); + } + let lockfile = json!({"name": "web", "version": version, "lockfileVersion": 3, "requires": true, "packages": packages}); + fs::write(root.join("package-lock.json"), format!("{lockfile:#}\n")).unwrap(); +} + +#[test] +fn a_sweep_discounts_bot_updates_and_lockfile_churn_only_in_dependency_projections() { + let repo = repository(None); + let root = repo.path(); + // The same graph twice: as dependencies, and as a custom projection that draws it as a graph, whose versions are + // what it shows (as a projection of releases would be). + fs::create_dir_all(root.join(".github/projections")).unwrap(); + for (id, renderer) in [("deps", "dependencies"), ("releases", "graph")] { + let definition = json!({"id": id, "title": id, "extractor": "workspace-dependencies", "renderer": renderer}); + fs::write(root.join(format!(".github/projections/{id}.json")), format!("{definition:#}\n")).unwrap(); + } + npm_workspace(root, "1.0.0", "2.0.0", &[]); + git(root, &["add", "-A"]); + git(root, &["commit", "--quiet", "-m", "Start"]); + // Renovate updates the lockfile alone: a transitive package moves and pulls in another. + npm_workspace(root, "1.0.0", "2.1.0", &["c"]); + let renovate = "--author=renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>"; + git(root, &["commit", "--quiet", "-am", "Update dependency b to v2.1.0 (#2)", renovate]); + npm_workspace(root, "1.1.0", "2.1.0", &["c"]); + git(root, &["commit", "--quiet", "-am", "Release 1.1.0 (#3)"]); + for number in [4, 5] { + fs::write(root.join("README.md"), format!("# Web {number}\n")).unwrap(); + git(root, &["add", "-A"]); + git(root, &["commit", "--quiet", "-m", &format!("Write docs (#{number})")]); + } + + let swept: Value = serde_json::from_str(&succeed(cli( + root, + &["explore", "--sweep", "--json", "-p", "deps", "-p", "releases"], + ))) + .unwrap(); + assert_eq!(swept["botChanges"], 1, "{swept}"); + let changes = swept["changes"].as_array().unwrap(); + let bumped = changes.iter().find(|change| change["number"] == 2).unwrap(); + assert_eq!((&bumped["bot"], &bumped["author"]), (&json!(true), &json!("renovate[bot]"))); + let release = changes.iter().find(|change| change["number"] == 3).unwrap(); + assert_eq!(release["bot"], false); + let cell = |projection: &str, change: &Value| { + swept["cells"] + .as_array() + .unwrap() + .iter() + .find(|cell| cell["projection"] == projection && cell["after"] == change["after"]) + .unwrap() + .clone() + }; + // As dependencies, the lockfile churn and the release only moved versions: it's quiet. + assert_eq!( + (&cell("deps", bumped)["versionOnly"], &cell("deps", bumped)["bot"]), + (&json!(true), &json!(true)) + ); + assert_eq!(cell("deps", release)["versionOnly"], true); + let row = |id: &str| { + swept["projections"] + .as_array() + .unwrap() + .iter() + .find(|row| row["projection"] == id) + .unwrap() + .clone() + }; + assert_eq!((&row("deps")["signal"], &row("deps")["versionOnly"]), (&json!("quiet"), &json!(2))); + // The custom projection shows those versions: the release is a change, and it isn't degraded to quiet. + assert_eq!(cell("releases", release)["status"], "changed"); + assert!(cell("releases", release)["versionOnly"].is_null(), "{swept}"); + assert_eq!((&row("releases")["changed"], &row("releases")["bots"]), (&json!(2), &json!(1))); + assert_ne!(row("releases")["signal"], "quiet", "{swept}"); + + let text = succeed(cli(root, &["explore", "--sweep", "-p", "deps", "-p", "releases"])); + assert!(text.contains("1 of 4 changes was a bot update"), "{text}"); + assert!(text.contains("#2 (") && text.contains(", bot update)"), "{text}"); +} + +#[test] +fn a_merged_pull_request_is_a_bot_change_by_its_author_not_its_merger() { + let repo = swept_repository(); + let root = repo.path(); + git(root, &["checkout", "--quiet", "-b", "bump"]); + fs::write(root.join("README.md"), "# Docs, bumped\n").unwrap(); + let dependabot = "--author=dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>"; + git(root, &["commit", "--quiet", "-am", "Bump b from 2.0.0 to 2.1.0", dependabot]); + git(root, &["checkout", "--quiet", "-"]); + git( + root, + &[ + "merge", + "--quiet", + "--no-ff", + "bump", + "-m", + "Merge pull request #9 from acme/bump", + "-m", + "Bump b", + ], + ); + let swept: Value = serde_json::from_str(&succeed(cli(root, &["explore", "--sweep", "--json", "-p", "prisma-schema"]))).unwrap(); + let bots: Vec<_> = swept["changes"] + .as_array() + .unwrap() + .iter() + .map(|change| (change["number"].clone(), change["bot"].clone())) + .collect(); + assert_eq!(bots, [(json!(9), json!(true)), (json!(8), json!(false)), (json!(7), json!(false))]); + assert_eq!(swept["changes"][0]["author"], "dependabot[bot]"); + assert_eq!(swept["botChanges"], 1); +} diff --git a/packages/host/inspector/src/sweep/stats.ts b/packages/host/inspector/src/sweep/stats.ts index 868ada27d..e9cc27dfb 100644 --- a/packages/host/inspector/src/sweep/stats.ts +++ b/packages/host/inspector/src/sweep/stats.ts @@ -24,18 +24,29 @@ export interface ColumnStats { swept: number /** Changes it changed on, apart from those where only versions moved. */ changed: number + /** Of those, the bot changes: each counts a quarter as much when ranking. */ + bots: number + /** `changed`, with each bot change a quarter of a change. */ + weighted: number /** Changes where only versions moved: a dependency or action bump, not a change in what it shows. */ versionOnly: number failed: number /** The median change count among the changes it showed something on. */ median: number - /** `noisy`: changes on nearly every change; `rare`: only on a few, structural ones; `quiet`: never. */ + /** `noisy`: changes on nearly every change; `rare`: only on a few, structural ones; `quiet`: never, or only on bot changes. */ signal: 'noisy' | 'rare' | 'steady' | 'quiet' | 'unknown' } /** Below this many swept changes, a projection's signal isn't judged. */ const JUDGED_FROM = 4 +/** How much a bot change counts when ranking, as a share of another change (`BOT_SHARE` in the CLI's signal.rs). */ +const BOT_WEIGHT = 1 / 4 +/** + * How a projection fared across a sweep, judged as `explore --sweep` judges it (packages/cli/src/sweep/signal.rs): + * a change that only moved versions doesn't count, and a bot change counts a quarter; once enough other changes were + * judged, changing only on bot changes is quiet. + */ export function columnStats(projection: string, cells: readonly SweepCell[]): ColumnStats { const mine = cells.filter(cell => cell.projection === projection) const changed = mine.filter(cell => cell.status === 'changed' && !cell.versionOnly) @@ -43,24 +54,42 @@ export function columnStats(projection: string, cells: readonly SweepCell[]): Co const counts = changed.map(cell => cell.changes ?? 0).toSorted((a, b) => a - b) const middle = Math.floor(counts.length / 2) const median = counts.length === 0 ? 0 : counts.length % 2 ? counts[middle]! : (counts[middle - 1]! + counts[middle]!) / 2 - const judged = mine.filter(cell => cell.status !== 'failed').length - const ratio = judged ? changed.length / judged : 0 + const judgedCells = mine.filter(cell => cell.status !== 'failed') + const judged = judgedCells.length + const weight = (cell: SweepCell) => (cell.bot ? BOT_WEIGHT : 1) + const bots = changed.filter(cell => cell.bot).length + const others = judged - judgedCells.filter(cell => cell.bot).length + const weighted = changed.reduce((sum, cell) => sum + weight(cell), 0) + const of = judgedCells.reduce((sum, cell) => sum + weight(cell), 0) + const ratio = of ? weighted / of : 0 const signal = - judged < JUDGED_FROM ? 'unknown' : changed.length === 0 ? 'quiet' : ratio >= 0.8 ? 'noisy' : ratio <= 0.25 ? 'rare' : 'steady' - return {swept: mine.length, changed: changed.length, versionOnly, failed: mine.length - judged, median, signal} + judged < JUDGED_FROM + ? 'unknown' + : changed.length === 0 || (changed.length === bots && others >= JUDGED_FROM) + ? 'quiet' + : ratio >= 0.8 + ? 'noisy' + : ratio <= 0.25 + ? 'rare' + : 'steady' + return {swept: mine.length, changed: changed.length, bots, weighted, versionOnly, failed: mine.length - judged, median, signal} } /** A column's summary and hint, in words. */ export function statsText(stats: ColumnStats): {summary: string; hint?: string} { const summary = `Changed in ${stats.changed} of ${plural(stats.swept, 'change')}${ stats.changed ? ` · median ${plural(stats.median, 'change')}` : '' - }${stats.versionOnly ? ` · only versions on ${stats.versionOnly}` : ''}${stats.failed ? ` · failed on ${stats.failed}` : ''}` + }${stats.bots ? ` · ${plural(stats.bots, 'bot update')}` : ''}${stats.versionOnly ? ` · only versions on ${stats.versionOnly}` : ''}${ + stats.failed ? ` · failed on ${stats.failed}` : '' + }` const hint = { noisy: 'Changes on nearly every change; may be noisy', rare: 'Rarely changes; shows up for structural work', - quiet: stats.versionOnly - ? 'Only versions changed here (dependency or action bumps)' - : "Didn't change here; may not suit this repository", + quiet: stats.bots + ? 'Changed only on bot updates here' + : stats.versionOnly + ? 'Only versions changed here (dependency or action bumps)' + : "Didn't change here; may not suit this repository", steady: undefined, unknown: undefined, }[stats.signal] @@ -75,7 +104,7 @@ export function bySignal(rows: readonly SweepProjection[], cells: readonly Sweep return rows.toSorted( (a, b) => rank(a) - rank(b) || - columnStats(b.projection, cells).changed - columnStats(a.projection, cells).changed || + columnStats(b.projection, cells).weighted - columnStats(a.projection, cells).weighted || a.projection.localeCompare(b.projection), ) } diff --git a/packages/host/inspector/test/client.test.mjs b/packages/host/inspector/test/client.test.mjs index dc9781440..dcd698bbf 100644 --- a/packages/host/inspector/test/client.test.mjs +++ b/packages/host/inspector/test/client.test.mjs @@ -252,7 +252,16 @@ test('sweep columns summarize how often a projection changed and order by signal ...changes.map((after, index) => cell('deps', after, index < 2 ? 1 + index : 0)), ...changes.map(after => cell('quiet', after, 0)), ] - assert.deepEqual(columnStats('files', cells), {swept: 5, changed: 5, versionOnly: 0, failed: 0, median: 2, signal: 'noisy'}) + assert.deepEqual(columnStats('files', cells), { + swept: 5, + changed: 5, + bots: 0, + weighted: 5, + versionOnly: 0, + failed: 0, + median: 2, + signal: 'noisy', + }) assert.equal(columnStats('schema', cells).signal, 'rare') assert.equal(columnStats('deps', cells).median, 1.5) assert.equal(columnStats('deps', cells).signal, 'steady') @@ -279,12 +288,37 @@ test('sweep columns summarize how often a projection changed and order by signal assert.equal(counts.get('c'), undefined) // A change that only moved versions (a dependency or action bump) isn't a change in what it shows. const bumped = changes.map((after, index) => ({...cell('actions', after, index < 2 ? 1 : 0), versionOnly: index < 2})) - assert.deepEqual(columnStats('actions', bumped), {swept: 5, changed: 0, versionOnly: 2, failed: 0, median: 0, signal: 'quiet'}) + assert.deepEqual(columnStats('actions', bumped), { + swept: 5, + changed: 0, + bots: 0, + weighted: 0, + versionOnly: 2, + failed: 0, + median: 0, + signal: 'quiet', + }) assert.deepEqual(statsText(columnStats('actions', bumped)), { summary: 'Changed in 0 of 5 changes · only versions on 2', hint: 'Only versions changed here (dependency or action bumps)', }) assert.equal(signalCounts({cells: bumped, projections: [{projection: 'actions', status: 'ready'}]}).size, 0) + + // A bot change counts a quarter, as explore --sweep counts it: changing on 7 bot bumps and 1 of 13 other changes is + // rare, and changing only on the bumps is quiet. + const swept = (projection, otherChanged, botChanged) => [ + ...Array.from({length: 13}, (_, index) => cell(projection, `h${index}`, index < otherChanged ? 1 : 0)), + ...Array.from({length: 7}, (_, index) => ({...cell(projection, `b${index}`, index < botChanged ? 1 : 0), bot: true})), + ] + const busy = columnStats('deps', swept('deps', 1, 7)) + assert.deepEqual([busy.changed, busy.bots, busy.weighted, busy.signal], [8, 7, 2.75, 'rare']) + const botted = columnStats('deps', swept('deps', 0, 7)) + assert.equal(botted.signal, 'quiet') + assert.deepEqual(statsText(botted), { + summary: 'Changed in 7 of 20 changes · median 1 change · 7 bot updates', + hint: 'Changed only on bot updates here', + }) + assert.equal(columnStats('deps', swept('deps', 13, 0)).signal, 'noisy') }) test('choices are named for people: the ref, the commit subject and age, never a bare commit when the runner knows it', async () => { diff --git a/packages/schemas/internal/runner-api.json b/packages/schemas/internal/runner-api.json index c3f3c58f9..9f4794add 100644 --- a/packages/schemas/internal/runner-api.json +++ b/packages/schemas/internal/runner-api.json @@ -53,7 +53,15 @@ ] }, "kind": {"enum": ["merge", "commit", "pair"]}, - "date": {"type": "string"} + "date": {"type": "string"}, + "author": { + "type": "string", + "description": "Who made it: a commit's author, or the author of the pull request a merge merged." + }, + "bot": { + "type": "boolean", + "description": "A bot made it (Renovate, Dependabot, a release bot): it counts for less when ranking projections." + } } } } @@ -168,7 +176,15 @@ ] }, "kind": {"enum": ["merge", "commit", "pair"]}, - "date": {"type": "string"} + "date": {"type": "string"}, + "author": { + "type": "string", + "description": "Who made it: a commit's author, or the author of the pull request a merge merged." + }, + "bot": { + "type": "boolean", + "description": "A bot made it (Renovate, Dependabot, a release bot): it counts for less when ranking projections." + } } } }, @@ -206,7 +222,11 @@ "stderr": {"type": "string", "description": "The end of a failed extractor's stderr."}, "versionOnly": { "type": "boolean", - "description": "Changed, but only version strings moved (a dependency or action bump)." + "description": "Changed, but only versions moved (a dependency or action bump), in a projection whose renderer is `dependencies` or `github-actions`." + }, + "bot": { + "type": "boolean", + "description": "The change is a bot's: it counts a quarter as much when ranking." } } } diff --git a/packages/schemas/src/runner/api.ts b/packages/schemas/src/runner/api.ts index 1f076370c..9a4fed511 100644 --- a/packages/schemas/src/runner/api.ts +++ b/packages/schemas/src/runner/api.ts @@ -25,6 +25,10 @@ export const SweepChangeSchema = Type.Object({ number: Nullable(Type.Integer({description: 'The pull request number its message names, if any.'})), kind: Type.Enum(['merge', 'commit', 'pair']), date: Type.String(), + author: Type.Optional(Type.String({description: "Who made it: a commit's author, or the author of the pull request a merge merged."})), + bot: Type.Optional( + Type.Boolean({description: 'A bot made it (Renovate, Dependabot, a release bot): it counts for less when ranking projections.'}), + ), }) /** A swept projection: `ready`, or skipped because it needs `--trust`, or failed to prepare. */ @@ -46,7 +50,13 @@ export const SweepCellSchema = Type.Object({ counts: Type.Optional(Dictionary(Count, {description: 'Changes by status (`added`, `removed`, `modified`, …).'})), error: Type.Optional(Type.String()), stderr: Type.Optional(Type.String({description: "The end of a failed extractor's stderr."})), - versionOnly: Type.Optional(Type.Boolean({description: 'Changed, but only version strings moved (a dependency or action bump).'})), + versionOnly: Type.Optional( + Type.Boolean({ + description: + 'Changed, but only versions moved (a dependency or action bump), in a projection whose renderer is `dependencies` or `github-actions`.', + }), + ), + bot: Type.Optional(Type.Boolean({description: "The change is a bot's: it counts a quarter as much when ranking."})), }) /** A history sweep. */ diff --git a/tools/scripts/reference-docs/agents.mjs b/tools/scripts/reference-docs/agents.mjs index 42fac0ca1..769de80da 100644 --- a/tools/scripts/reference-docs/agents.mjs +++ b/tools/scripts/reference-docs/agents.mjs @@ -105,7 +105,8 @@ ${await agentBody('docs/setup/install.md')}`, "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.", 'Sweep: the `sweep` tool, or `projections explore --sweep --json`, runs each one on the last 20 merges into this branch (`--last N` for more). In a busy repository those may span only hours, leaving every projection `quiet`: check the changes’ dates and sweep again with `--since 30d`, which spreads the changes across that window. Projections that run repository code are skipped unless you pass `--trust`; ask the person first.', '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, or only version updates: a dependency or action bump marked `versionOnly`); and the pull requests where several changed. " + + "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, only on version updates (a dependency or action bump marked `versionOnly`), or only on bot updates); and the pull requests where several changed. " + + 'A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were), and in a dependency or GitHub Actions projection a lockfile update that only moved transitive packages is `versionOnly`; neither changes what a projection extracts, compares or draws. ' + 'Recommend projections that show something characteristic of this codebase (the picture a long-time maintainer would recognize as theirs), not just the ones that change least. Don’t add `repository-map` or `code-statistics`, which explore no longer proposes: they only show what Projections can draw, not this codebase. ' + 'To look at one yourself, draw it: `projections compare .. -p --png FILE` (a new file outside the repository).', '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.', From a1523db2088bc74bbe38e9ef1d18ec1c9fddb63f Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:11:09 +0000 Subject: [PATCH 2/7] Sweep: version-only classification, Git log parsing and bot authors in their own modules Keeps sweep/mod.rs and sweep/run.rs within the file complexity standard. A merge commit's committer (whoever merged it) never makes it a bot change. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/cli/src/sweep/bots.rs | 47 +++++++++ packages/cli/src/sweep/log.rs | 45 +++++++++ packages/cli/src/sweep/mod.rs | 83 +--------------- packages/cli/src/sweep/run.rs | 154 +---------------------------- packages/cli/src/sweep/tests.rs | 26 ++--- packages/cli/src/sweep/versions.rs | 153 ++++++++++++++++++++++++++++ packages/cli/src/sweep/window.rs | 5 +- 7 files changed, 272 insertions(+), 241 deletions(-) create mode 100644 packages/cli/src/sweep/log.rs create mode 100644 packages/cli/src/sweep/versions.rs diff --git a/packages/cli/src/sweep/bots.rs b/packages/cli/src/sweep/bots.rs index 559d9921f..efd3c4372 100644 --- a/packages/cli/src/sweep/bots.rs +++ b/packages/cli/src/sweep/bots.rs @@ -9,6 +9,9 @@ //! author of the pull request it merged (the merged branch's head commit), not //! whoever merged it. +use crate::runtime::Runner; +use std::{collections::HashMap, path::Path}; + /// Authors that are bots, by name or by email (compared without regard to /// case), besides any whose name or email carries GitHub's `[bot]` suffix /// (`renovate[bot]`, `dependabot[bot]`, `github-actions[bot]`, @@ -45,3 +48,47 @@ pub fn is_bot(name: &str, email: &str) -> bool { .iter() .any(|bot| *bot == name || *bot == email || email.split_once('@').is_some_and(|(local, _)| local == *bot)) } + +/// Who made a change, and whether a bot did: the author of the pull request a merge merged when Git knows it +/// (`merged`, from [`authors`]), else the commit's author, or for a commit that isn't a merge (a squash or rebase +/// merge) its author or its committer; a merge's committer is whoever merged it. `people` is the commit's author name +/// and email, then its committer's. +pub(super) fn author(merged: Option<&(String, String)>, merge: bool, people: &[&str]) -> (String, bool) { + if let Some((name, email)) = merged { + return (name.clone(), is_bot(name, email)); + } + let committer = !merge && is_bot(people[2], people[3]); + (people[0].to_owned(), is_bot(people[0], people[1]) || committer) +} + +/// Each commit's author name and email; none when Git can't say. +pub(super) fn authors(runner: &Runner, root: &Path, commits: &[&str]) -> HashMap { + if commits.is_empty() { + return HashMap::new(); + } + let mut args = vec!["log", "-z", "--no-walk=unsorted", "--format=%H%x09%an%x09%ae"]; + args.extend(commits); + let Ok(text) = runner.git_text(root, &args) else { + return HashMap::new(); + }; + text.split('\0') + .filter_map(|record| { + let mut parts = record.trim_start_matches('\n').splitn(3, '\t'); + let (commit, name, email) = (parts.next()?, parts.next()?, parts.next()?); + Some((commit.to_owned(), (name.to_owned(), email.trim_end().to_owned()))) + }) + .collect() +} + +/// How many of a sweep's changes bots made, when any did: `7 of 20 changes were bot updates`, and what that means +/// for the ranking. +pub fn note(bots: usize, changes: usize) -> Option { + (bots > 0).then(|| { + format!( + "{bots} of {changes} change{} {} bot update{} (Renovate, Dependabot, release bots), which count a quarter as much as other changes when ranking", + if changes == 1 { "" } else { "s" }, + if bots == 1 { "was a" } else { "were" }, + if bots == 1 { "" } else { "s" }, + ) + }) +} diff --git a/packages/cli/src/sweep/log.rs b/packages/cli/src/sweep/log.rs new file mode 100644 index 000000000..62558da16 --- /dev/null +++ b/packages/cli/src/sweep/log.rs @@ -0,0 +1,45 @@ +//! Changes as `git log` lists them, each with its title, pull request number and author. + +use super::{ + Change, bots, + titles::{number, subject_of, title}, +}; +use crate::runtime::Runner; +use std::path::Path; + +/// Changes from `git log -z --format=LOG_FORMAT`: each commit compared with its first parent. A merge's title comes +/// from its message, else from its merged branch's subject. +pub(super) const LOG_FORMAT: &str = "--format=%H%x09%P%x09%cI%x09%an%x09%ae%x09%cn%x09%ce%x09%s%x09%b"; + +pub(super) fn parse_log(runner: &Runner, root: &Path, text: &str) -> Vec { + let records: Vec> = text + .split('\0') + .map(|record| record.trim_start_matches('\n').splitn(9, '\t').collect()) + .filter(|parts: &Vec<&str>| parts.len() >= 8) + .collect(); + // A merge's pull request author is its merged branch's head author: every merge's, in one call. + let merged: Vec<&str> = records.iter().filter_map(|parts| parts[1].split(' ').nth(1)).collect(); + let authors = bots::authors(runner, root, &merged); + records + .into_iter() + .filter_map(|parts| { + let (commit, parents, date, subject) = (parts[0], parts[1], parts[2], parts[7]); + let body = parts.get(8).copied().unwrap_or_default(); + let mut parents = parents.split(' ').filter(|parent| !parent.is_empty()); + let parent = parents.next()?; + let second = parents.next(); + let merge = second.is_some(); + let (author, bot) = bots::author(second.and_then(|second| authors.get(second)), merge, &parts[3..7]); + Some(Change { + before: parent.to_owned(), + after: commit.to_owned(), + title: title(subject, body, merge, || second.and_then(|second| subject_of(runner, root, second))), + number: number(subject, merge), + kind: if merge { "merge" } else { "commit" }, + date: date.to_owned(), + author: Some(author), + bot, + }) + }) + .collect() +} diff --git a/packages/cli/src/sweep/mod.rs b/packages/cli/src/sweep/mod.rs index a254c48c5..2dc53f9b9 100644 --- a/packages/cli/src/sweep/mod.rs +++ b/packages/cli/src/sweep/mod.rs @@ -12,7 +12,7 @@ //! every projection, and at most [`DEFAULT_CONCURRENCY`] extractor processes //! run at once. //! -//! Bot changes ([`bots`]) and changes that only move versions are swept like +//! Bot changes ([`bots`]) and changes that only move versions ([`versions`]) are swept like //! any other; they only count for less, or not at all, when projections are //! ranked ([`signal`]). Neither changes an extraction, a comparison or a picture. @@ -26,13 +26,15 @@ use std::{ }; pub mod bots; +mod log; mod run; pub mod signal; mod titles; +mod versions; mod window; +use log::{LOG_FORMAT, parse_log}; pub use titles::{history_note, merge_title}; -use titles::{number, subject_of, title}; pub use run::run; pub use window::{shallow_window_note, since, spread, window_note}; @@ -80,68 +82,6 @@ impl Change { } } -/// Changes from `git log -z --format=LOG_FORMAT`: each commit compared with its first parent. A merge's title comes -/// from its message, else from its merged branch's subject. -pub(super) const LOG_FORMAT: &str = "--format=%H%x09%P%x09%cI%x09%an%x09%ae%x09%cn%x09%ce%x09%s%x09%b"; - -pub(super) fn parse_log(runner: &Runner, root: &Path, text: &str) -> Vec { - let records: Vec> = text - .split('\0') - .map(|record| record.trim_start_matches('\n').splitn(9, '\t').collect()) - .filter(|parts: &Vec<&str>| parts.len() >= 8) - .collect(); - // A merge's pull request author is its merged branch's head author: every merge's, in one call. - let merged: Vec<&str> = records.iter().filter_map(|parts| parts[1].split(' ').nth(1)).collect(); - let authors = authors(runner, root, &merged); - records - .into_iter() - .filter_map(|parts| { - let (commit, parents, date, subject) = (parts[0], parts[1], parts[2], parts[7]); - let body = parts.get(8).copied().unwrap_or_default(); - let mut parents = parents.split(' ').filter(|parent| !parent.is_empty()); - let parent = parents.next()?; - let second = parents.next(); - let merge = second.is_some(); - let (author, bot) = match second.and_then(|second| authors.get(second)) { - Some((name, email)) => (name.clone(), bots::is_bot(name, email)), - None => ( - parts[3].to_owned(), - bots::is_bot(parts[3], parts[4]) || (!merge && bots::is_bot(parts[5], parts[6])), - ), - }; - Some(Change { - before: parent.to_owned(), - after: commit.to_owned(), - title: title(subject, body, merge, || second.and_then(|second| subject_of(runner, root, second))), - number: number(subject, merge), - kind: if merge { "merge" } else { "commit" }, - date: date.to_owned(), - author: Some(author), - bot, - }) - }) - .collect() -} - -/// Each commit's author name and email; none when Git can't say. -fn authors(runner: &Runner, root: &Path, commits: &[&str]) -> HashMap { - if commits.is_empty() { - return HashMap::new(); - } - let mut args = vec!["log", "-z", "--no-walk=unsorted", "--format=%H%x09%an%x09%ae"]; - args.extend(commits); - let Ok(text) = runner.git_text(root, &args) else { - return HashMap::new(); - }; - text.split('\0') - .filter_map(|record| { - let mut parts = record.trim_start_matches('\n').splitn(3, '\t'); - let (commit, name, email) = (parts.next()?, parts.next()?, parts.next()?); - Some((commit.to_owned(), (name.to_owned(), email.trim_end().to_owned()))) - }) - .collect() -} - /// The last `last` changes into `HEAD`. They are the first-parent merges when /// merges are how this branch takes changes: at least half of its last `last` /// first-parent commits. Otherwise (a repository that squashes or rebases, @@ -311,7 +251,7 @@ pub fn text(changes: &[Change], rows: &[Value], cells: &[Value]) -> String { changes.len(), if changes.len() == 1 { "" } else { "s" } ); - if let Some(note) = bot_note(changes.iter().filter(|change| change.bot).count(), changes.len()) { + if let Some(note) = bots::note(changes.iter().filter(|change| change.bot).count(), changes.len()) { text.push_str(&format!(" {note}\n")); } let ranked = signal::ranked(rows, &cells.iter().collect::>()); @@ -336,19 +276,6 @@ pub fn text(changes: &[Change], rows: &[Value], cells: &[Value]) -> String { text } -/// How many of a sweep's changes bots made, when any did: `7 of 20 changes were bot updates`, and what that means -/// for the ranking. -pub fn bot_note(bots: usize, changes: usize) -> Option { - (bots > 0).then(|| { - format!( - "{bots} of {changes} change{} {} bot update{} (Renovate, Dependabot, release bots), which count a quarter as much as other changes when ranking", - if changes == 1 { "" } else { "s" }, - if bots == 1 { "was a" } else { "were" }, - if bots == 1 { "" } else { "s" }, - ) - }) -} - /// How many of a sweep's cells failed, and the first reason, when any did. pub fn failures(cells: &[Value]) -> Option { let failed: Vec<&Value> = cells.iter().filter(|cell| cell["status"] == "failed").collect(); diff --git a/packages/cli/src/sweep/run.rs b/packages/cli/src/sweep/run.rs index f1db500a6..ed0eccbbd 100644 --- a/packages/cli/src/sweep/run.rs +++ b/packages/cli/src/sweep/run.rs @@ -3,7 +3,10 @@ //! the shared cache, and each change's cells reported as soon as both of its //! revisions are done. -use super::{Cache, Cell, Change, Request}; +use super::{ + Cache, Cell, Change, Request, + versions::{Versioning, version_only}, +}; use crate::{ artifact, runtime::{Prepared, Runner, TrustRequired}, @@ -22,7 +25,7 @@ use std::{ /// finishes. Rows: `{projection, status: "ready"|"trust"|"failed", error?}`; /// cells: `{projection, before, after, status: "changed"|"unchanged"|"failed", changes, steps, counts, error?, stderr?, /// versionOnly?, bot?}`, `stderr` being the end of a failed extractor's stderr, `versionOnly` marking a change that -/// only moved versions ([`version_only`]) and `bot` one a bot made ([`super::bots`]). +/// only moved versions ([`super::versions`]) and `bot` one a bot made ([`super::bots`]). pub fn run(runner: &Runner, request: Request<'_>, on_row: &(dyn Fn(Value) + Sync), on_cell: &(dyn Fn(Cell) + Sync)) -> Result<()> { let root = runner.repository_root()?; let prepared = prepare(runner, &request.projections, on_row); @@ -249,153 +252,6 @@ fn compared(mut value: Value, comparison: Value) -> Cell { } } -/// How a dependency-like projection's items carry versions, the only projections whose changes can be version-only. -/// It is told by the definition's renderer, which says what its items are: `dependencies` (packages and the -/// dependencies between them, each with its `version`) or `github-actions` (jobs and the actions, reusable -/// workflows and images they pin). Any other projection, a custom one whose items happen to carry versions -/// included, is never version-only: a version there is what it shows. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Versioning { - Dependencies, - Actions, -} - -impl Versioning { - pub(super) fn of(definition: &Value) -> Option { - match definition["renderer"].as_str()? { - "dependencies" => Some(Self::Dependencies), - "github-actions" => Some(Self::Actions), - _ => None, - } - } - - /// The data fields that hold an item's version, at any depth. - fn attributes(self) -> &'static [&'static str] { - match self { - // A package's version, a declaration's range and the version it resolved to, a pinned revision. - Self::Dependencies => &["version", "resolved", "revision"], - // An action's ref, a reusable workflow's `@ref`, an image's tag or digest. - Self::Actions => &["ref", "uses", "image"], - } - } -} - -/// Entity kinds a dependency graph starts from besides workspace members: projects and their target frameworks, -/// and Swift packages' targets and products. Keep with the dependencies renderer's (`rootKinds` in -/// packages/renderers/graph/src/dependencies/kinds.ts). -const ROOT_KINDS: &[&str] = &["project", "target-framework", "target", "product"]; -/// Relationship kinds that record membership rather than a dependency: NuGet's `resolved`. -const MEMBERSHIP_KINDS: &[&str] = &["resolved"]; - -/// Whether every change a comparison found only moved versions, as a dependency or action bump does (`v4` to `v5`, -/// `1.2.3` to `1.3.0`, one pinned commit to another), for a projection that carries versions as `versioning` says. -/// -/// Every modified item must be the same once its version attributes are masked (and its label, where the label is -/// its version, as a dependency's declared range is). In a dependency graph, packages installed only transitively -/// and the dependencies between them may also be added or removed, as a lockfile's churn adds and drops them; but a -/// direct dependency (one a workspace member, project or target declares) added or removed, or a workspace member -/// added, removed or changed other than in its own version, is a real change. -pub(super) fn version_only(versioning: Versioning, comparison: &Value, before: &Value, after: &Value) -> bool { - let Some(changes) = comparison["comparison"]["changes"].as_array().filter(|changes| !changes.is_empty()) else { - return false; - }; - changes.iter().all(|change| { - let old = item(before, change, "before"); - let new = item(after, change, "after"); - match change["status"].as_str() { - Some("modified") => matches!( - (old, new), - (Some(old), Some(new)) if masked(versioning, old) == masked(versioning, new) - ), - Some("added") if versioning == Versioning::Dependencies => { - new.is_some_and(|new| transitive(after, change["collection"].as_str(), new)) - } - Some("removed") if versioning == Versioning::Dependencies => { - old.is_some_and(|old| transitive(before, change["collection"].as_str(), old)) - } - _ => false, - } - }) -} - -/// A changed item on one side of a comparison. -fn item<'a>(document: &'a Value, change: &Value, side: &str) -> Option<&'a Value> { - let id = change[side][0].as_str()?; - let collection = change["collection"].as_str()?; - document["extraction"][collection].as_array()?.iter().find(|item| item["id"] == id) -} - -/// Whether a dependency graph's entity is a root: a workspace member, or a project, framework or target. -fn root(entity: &Value) -> bool { - entity["data"]["workspaceMember"] == true || entity["kind"].as_str().is_some_and(|kind| ROOT_KINDS.contains(&kind)) -} - -/// Whether a dependency graph's item is only transitive: a package that isn't a root, or a dependency (or membership) -/// that no root declares. -fn transitive(document: &Value, collection: Option<&str>, item: &Value) -> bool { - match collection { - Some("entities") => !root(item), - Some("relationships") => { - item["kind"].as_str().is_some_and(|kind| MEMBERSHIP_KINDS.contains(&kind)) - || document["extraction"]["entities"] - .as_array() - .and_then(|entities| entities.iter().find(|entity| entity["id"] == item["from"])) - .is_some_and(|from| !root(from)) - } - _ => false, - } -} - -/// An item with the versions in its version attributes masked (and its label, where its label is its version), and -/// its evidence left out. -fn masked(versioning: Versioning, item: &Value) -> Value { - let mut item = item.clone(); - let Some(fields) = item.as_object_mut() else { - return item; - }; - fields.remove("evidence"); - let version = fields.get("data").and_then(|data| data["version"].as_str()).map(str::to_owned); - if version.is_some() && fields.get("label").and_then(Value::as_str) == version.as_deref() { - fields.insert("label".to_owned(), mask(&fields["label"])); - } - if let Some(data) = fields.get_mut("data") { - mask_attributes(versioning.attributes(), data); - } - item -} - -/// Masks every version attribute's value, at any depth. -fn mask_attributes(attributes: &[&str], value: &mut Value) { - match value { - Value::Object(fields) => { - for (key, value) in fields.iter_mut() { - if attributes.contains(&key.as_str()) { - *value = mask(value); - } else { - mask_attributes(attributes, value); - } - } - } - Value::Array(items) => items.iter_mut().for_each(|item| mask_attributes(attributes, item)), - _ => {} - } -} - -/// A version attribute's value with every version-like string in it masked. -fn mask(value: &Value) -> Value { - static VERSION: std::sync::LazyLock = std::sync::LazyLock::new(|| { - // A commit or digest only as a whole value or after `@` (a pinned action or image), not any hash in text. - regex::Regex::new(r"^[0-9a-f]{40}$|^[0-9a-f]{64}$|@(?:sha256:)?[0-9a-f]{40,64}\b|\bv?\d+(?:\.\d+)+(?:[-+][0-9A-Za-z.-]+)?|\bv\d+\b") - .expect("a valid pattern") - }); - match value { - Value::String(text) => Value::String(VERSION.replace_all(text, "").into_owned()), - Value::Array(items) => Value::Array(items.iter().map(mask).collect()), - Value::Object(fields) => Value::Object(fields.iter().map(|(key, value)| (key.clone(), mask(value))).collect()), - other => other.clone(), - } -} - /// A failed cell: `error`, and `stderr` when the extractor wrote some. fn failed(mut value: Value, failure: Value) -> Cell { value["status"] = json!("failed"); diff --git a/packages/cli/src/sweep/tests.rs b/packages/cli/src/sweep/tests.rs index 93047e1cc..a05b86e7f 100644 --- a/packages/cli/src/sweep/tests.rs +++ b/packages/cli/src/sweep/tests.rs @@ -1,4 +1,4 @@ -use super::{Cache, Change, number, since, spread}; +use super::{Cache, Change, since, spread, titles::number}; use serde_json::json; use std::sync::Arc; @@ -45,27 +45,27 @@ fn pull_request_numbers_come_from_messages() { fn merged_pull_requests_are_titled_by_their_own_title() { let none = || None; assert_eq!( - super::title("Merge pull request #4 from a/b", "Add posts\n\nMore", true, none), + super::titles::title("Merge pull request #4 from a/b", "Add posts\n\nMore", true, none), "Add posts" ); assert_eq!( - super::title("Merge pull request #4 from a/b", "", true, none), + super::titles::title("Merge pull request #4 from a/b", "", true, none), "Merge pull request #4 from a/b" ); - assert_eq!(super::title("Add posts (#4)", "Body", false, none), "Add posts (#4)"); + assert_eq!(super::titles::title("Add posts (#4)", "Body", false, none), "Add posts (#4)"); // A merge that says only what it merged is titled by the commit it merged in. let merged = || Some("Fix the layer switcher\n".to_owned()); assert_eq!( - super::title("Merge remote-tracking branch 'upstream/pull/7156'", "", true, merged), + super::titles::title("Merge remote-tracking branch 'upstream/pull/7156'", "", true, merged), "Fix the layer switcher" ); assert_eq!( - super::title("Merge pull request #4 from a/b", "Add posts", true, merged), + super::titles::title("Merge pull request #4 from a/b", "Add posts", true, merged), "Add posts" ); // A merge titled in words keeps its title. assert_eq!( - super::title("Merge authentication and billing fixes", "", true, merged), + super::titles::title("Merge authentication and billing fixes", "", true, merged), "Merge authentication and billing fixes" ); } @@ -248,7 +248,7 @@ fn compared(changes: &[(&str, &str, &str)]) -> serde_json::Value { #[test] fn an_action_bump_only_moves_versions() { - use super::run::{Versioning, version_only}; + use super::versions::{Versioning, version_only}; let document = |reference: &str, image: &str| { json!({"extraction": {"entities": [ {"id": "job:build", "kind": "job", "label": "build", @@ -303,7 +303,7 @@ fn graph(version: &str, transitive: &str, extra: &[&str]) -> serde_json::Value { #[test] fn lockfile_only_transitive_churn_only_moves_versions() { - use super::run::{Versioning, version_only}; + use super::versions::{Versioning, version_only}; let dependencies = |changes: &[(&str, &str, &str)], before: &serde_json::Value, after: &serde_json::Value| { version_only(Versioning::Dependencies, &compared(changes), before, after) }; @@ -362,7 +362,7 @@ fn lockfile_only_transitive_churn_only_moves_versions() { #[test] fn only_dependency_like_projections_are_version_only() { - use super::run::Versioning; + use super::versions::Versioning; assert_eq!(Versioning::of(&json!({"renderer": "dependencies"})), Some(Versioning::Dependencies)); assert_eq!(Versioning::of(&json!({"renderer": "github-actions"})), Some(Versioning::Actions)); // A custom projection whose items carry versions (each release's, say) shows them: they are never only versions. @@ -469,12 +469,12 @@ fn bot_changes_count_a_quarter_in_a_ranking() { #[test] fn a_sweep_says_how_many_changes_bots_made() { - assert_eq!(super::bot_note(0, 20), None); + assert_eq!(super::bots::note(0, 20), None); assert_eq!( - super::bot_note(7, 20).unwrap(), + super::bots::note(7, 20).unwrap(), "7 of 20 changes were bot updates (Renovate, Dependabot, release bots), which count a quarter as much as other changes when ranking" ); - assert!(super::bot_note(1, 20).unwrap().starts_with("1 of 20 changes was a bot update ")); + assert!(super::bots::note(1, 20).unwrap().starts_with("1 of 20 changes was a bot update ")); } #[test] diff --git a/packages/cli/src/sweep/versions.rs b/packages/cli/src/sweep/versions.rs new file mode 100644 index 000000000..2a4649eff --- /dev/null +++ b/packages/cli/src/sweep/versions.rs @@ -0,0 +1,153 @@ +//! Which changes only moved versions, as a dependency or action bump does. A sweep marks those cells +//! `versionOnly`, and they don't count when projections are ranked ([`super::signal`]); extractions, comparisons and +//! pictures are the same either way. Only dependency-like projections ([`Versioning`]) can be version-only, and only in +//! their version attributes: a custom projection whose items carry versions shows them. + +use serde_json::Value; + +/// How a dependency-like projection's items carry versions, the only projections whose changes can be version-only. +/// It is told by the definition's renderer, which says what its items are: `dependencies` (packages and the +/// dependencies between them, each with its `version`) or `github-actions` (jobs and the actions, reusable +/// workflows and images they pin). Any other projection, a custom one whose items happen to carry versions +/// included, is never version-only: a version there is what it shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Versioning { + Dependencies, + Actions, +} + +impl Versioning { + pub(super) fn of(definition: &Value) -> Option { + match definition["renderer"].as_str()? { + "dependencies" => Some(Self::Dependencies), + "github-actions" => Some(Self::Actions), + _ => None, + } + } + + /// The data fields that hold an item's version, at any depth. + fn attributes(self) -> &'static [&'static str] { + match self { + // A package's version, a declaration's range and the version it resolved to, a pinned revision. + Self::Dependencies => &["version", "resolved", "revision"], + // An action's ref, a reusable workflow's `@ref`, an image's tag or digest. + Self::Actions => &["ref", "uses", "image"], + } + } +} + +/// Entity kinds a dependency graph starts from besides workspace members: projects and their target frameworks, +/// and Swift packages' targets and products. Keep with the dependencies renderer's (`rootKinds` in +/// packages/renderers/graph/src/dependencies/kinds.ts). +const ROOT_KINDS: &[&str] = &["project", "target-framework", "target", "product"]; +/// Relationship kinds that record membership rather than a dependency: NuGet's `resolved`. +const MEMBERSHIP_KINDS: &[&str] = &["resolved"]; + +/// Whether every change a comparison found only moved versions, as a dependency or action bump does (`v4` to `v5`, +/// `1.2.3` to `1.3.0`, one pinned commit to another), for a projection that carries versions as `versioning` says. +/// +/// Every modified item must be the same once its version attributes are masked (and its label, where the label is +/// its version, as a dependency's declared range is). In a dependency graph, packages installed only transitively +/// and the dependencies between them may also be added or removed, as a lockfile's churn adds and drops them; but a +/// direct dependency (one a workspace member, project or target declares) added or removed, or a workspace member +/// added, removed or changed other than in its own version, is a real change. +pub(super) fn version_only(versioning: Versioning, comparison: &Value, before: &Value, after: &Value) -> bool { + let Some(changes) = comparison["comparison"]["changes"].as_array().filter(|changes| !changes.is_empty()) else { + return false; + }; + changes.iter().all(|change| { + let old = item(before, change, "before"); + let new = item(after, change, "after"); + match change["status"].as_str() { + Some("modified") => matches!( + (old, new), + (Some(old), Some(new)) if masked(versioning, old) == masked(versioning, new) + ), + Some("added") if versioning == Versioning::Dependencies => { + new.is_some_and(|new| transitive(after, change["collection"].as_str(), new)) + } + Some("removed") if versioning == Versioning::Dependencies => { + old.is_some_and(|old| transitive(before, change["collection"].as_str(), old)) + } + _ => false, + } + }) +} + +/// A changed item on one side of a comparison. +fn item<'a>(document: &'a Value, change: &Value, side: &str) -> Option<&'a Value> { + let id = change[side][0].as_str()?; + let collection = change["collection"].as_str()?; + document["extraction"][collection].as_array()?.iter().find(|item| item["id"] == id) +} + +/// Whether a dependency graph's entity is a root: a workspace member, or a project, framework or target. +fn root(entity: &Value) -> bool { + entity["data"]["workspaceMember"] == true || entity["kind"].as_str().is_some_and(|kind| ROOT_KINDS.contains(&kind)) +} + +/// Whether a dependency graph's item is only transitive: a package that isn't a root, or a dependency (or membership) +/// that no root declares. +fn transitive(document: &Value, collection: Option<&str>, item: &Value) -> bool { + match collection { + Some("entities") => !root(item), + Some("relationships") => { + item["kind"].as_str().is_some_and(|kind| MEMBERSHIP_KINDS.contains(&kind)) + || document["extraction"]["entities"] + .as_array() + .and_then(|entities| entities.iter().find(|entity| entity["id"] == item["from"])) + .is_some_and(|from| !root(from)) + } + _ => false, + } +} + +/// An item with the versions in its version attributes masked (and its label, where its label is its version), and +/// its evidence left out. +fn masked(versioning: Versioning, item: &Value) -> Value { + let mut item = item.clone(); + let Some(fields) = item.as_object_mut() else { + return item; + }; + fields.remove("evidence"); + let version = fields.get("data").and_then(|data| data["version"].as_str()).map(str::to_owned); + if version.is_some() && fields.get("label").and_then(Value::as_str) == version.as_deref() { + fields.insert("label".to_owned(), mask(&fields["label"])); + } + if let Some(data) = fields.get_mut("data") { + mask_attributes(versioning.attributes(), data); + } + item +} + +/// Masks every version attribute's value, at any depth. +fn mask_attributes(attributes: &[&str], value: &mut Value) { + match value { + Value::Object(fields) => { + for (key, value) in fields.iter_mut() { + if attributes.contains(&key.as_str()) { + *value = mask(value); + } else { + mask_attributes(attributes, value); + } + } + } + Value::Array(items) => items.iter_mut().for_each(|item| mask_attributes(attributes, item)), + _ => {} + } +} + +/// A version attribute's value with every version-like string in it masked. +fn mask(value: &Value) -> Value { + static VERSION: std::sync::LazyLock = std::sync::LazyLock::new(|| { + // A commit or digest only as a whole value or after `@` (a pinned action or image), not any hash in text. + regex::Regex::new(r"^[0-9a-f]{40}$|^[0-9a-f]{64}$|@(?:sha256:)?[0-9a-f]{40,64}\b|\bv?\d+(?:\.\d+)+(?:[-+][0-9A-Za-z.-]+)?|\bv\d+\b") + .expect("a valid pattern") + }); + match value { + Value::String(text) => Value::String(VERSION.replace_all(text, "").into_owned()), + Value::Array(items) => Value::Array(items.iter().map(mask).collect()), + Value::Object(fields) => Value::Object(fields.iter().map(|(key, value)| (key.clone(), mask(value))).collect()), + other => other.clone(), + } +} diff --git a/packages/cli/src/sweep/window.rs b/packages/cli/src/sweep/window.rs index 5ccfe250d..0fceeb3f3 100644 --- a/packages/cli/src/sweep/window.rs +++ b/packages/cli/src/sweep/window.rs @@ -1,6 +1,9 @@ //! A sweep's `--since` window: what it means, which of its changes are swept, and how many it held. -use super::{Change, LOG_FORMAT, MAX_LAST, parse_log}; +use super::{ + Change, MAX_LAST, + log::{LOG_FORMAT, parse_log}, +}; use crate::runtime::Runner; use anyhow::{Context, Result}; use std::path::Path; From df6744f2d77efaff4f0f84489e17629089561368 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:20:35 +0000 Subject: [PATCH 3/7] Sweep: the sweep tool says how many changes bots made; regenerate the agent briefs; describe ranking in the onboarding design Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/agents/create-projection.md | 12 +++++++++--- docs/agents/explore.md | 10 +++++++--- docs/design/onboarding-loop.md | 17 +++++++++++++++++ docs/runner/agent-tools.md | 5 +++-- packages/cli/src/tools/read/sweep.rs | 6 +++++- packages/cli/src/tools/tests.rs | 11 +++++++++++ tools/scripts/reference-docs/agents.mjs | 4 ++-- 7 files changed, 54 insertions(+), 11 deletions(-) diff --git a/docs/agents/create-projection.md b/docs/agents/create-projection.md index b2232453d..9fec43634 100644 --- a/docs/agents/create-projection.md +++ b/docs/agents/create-projection.md @@ -208,9 +208,15 @@ adopt. with `changes`, `steps` and `counts` by kind). Ready rows come best first, each with its `signal`: `rare` (changed on a quarter of the changes or fewer, likely the structural ones), `steady`, `noisy` (on four in five or - more), `quiet` (never) or `unknown` (fewer than four changes swept). A - cell marked `versionOnly` changed only version strings (a dependency or - action bump) and doesn't count as a change. On a busy repository, the last 20 merges may span only hours, leaving every + more), `quiet` (never, or only on bot changes) or `unknown` (fewer than + four changes swept). A cell marked `versionOnly` changed only versions (a + dependency or action bump, or a lockfile update that only moved transitive + packages) and doesn't count as a change; only projections drawn with the + `dependencies` or `github-actions` renderer can be version-only, so a + custom projection whose versions are what it shows always counts them. A + change marked `bot` (Renovate, Dependabot, a release bot; `botChanges` + counts them) counts a quarter as much. Both affect only the ranking, never + extractions, comparisons or pictures. On a busy repository, the last 20 merges may span only hours, leaving every projection `quiet`. Check the changes' dates and sweep again with `--since 30d` (a date or duration) to spread `--last N` changes evenly across that window. diff --git a/docs/agents/explore.md b/docs/agents/explore.md index 7836ad9f9..e807cecd4 100644 --- a/docs/agents/explore.md +++ b/docs/agents/explore.md @@ -10,7 +10,7 @@ This file guides you, a coding agent, to find the projections that apply to this 2. Check the CLI: `projections --version`. If it is missing, install it by following https://github.com/githubnext/projections/blob/v0.3.2/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 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). In a busy repository those may span only hours, leaving every projection `quiet`: check the changes’ dates and sweep again with `--since 30d`, which spreads the changes across that window. 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`), 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, or only version updates: a dependency or action bump marked `versionOnly`); and the pull requests where several changed. Recommend projections that show something characteristic of this codebase (the picture a long-time maintainer would recognize as theirs), not just the ones that change least. Don’t add `repository-map` or `code-statistics`, which explore no longer proposes: they only show what Projections can draw, not this codebase. To look at one yourself, draw it: `projections compare .. -p --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, or only on version updates marked `versionOnly`, such as a dependency or action bump, or only on bot updates); and the pull requests where several changed. A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were). Only dependency and GitHub Actions projections can be `versionOnly`, a lockfile update that only moved transitive packages included; in any other projection a version that changed counts. Neither changes what a projection extracts, compares or draws. Recommend projections that show something characteristic of this codebase (the picture a long-time maintainer would recognize as theirs), not just the ones that change least. Don’t add `repository-map` or `code-statistics`, which explore no longer proposes: they only show what Projections can draw, not this codebase. To look at one yourself, draw it: `projections compare .. -p --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 ... --dry-run`, then `projections adopt ...`. Built-in projections fit standard systems like Actions workflows, database schemas and package dependencies, but rarely cover what’s distinctive about a codebase. Name the characteristic systems they missed (its own registries, extension points, protocols, pipelines) and offer to build projections for them, usually with custom renderers. To build one, run `projections help agents create-projection` and follow what it prints. 8. Show them each adopted projection yourself: `projections view show -p --choice 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. @@ -85,8 +85,12 @@ projections explore --sweep The sweep reports how often each projection changed across those pull requests and distinguishes noisy ones (changing on nearly every pull request) from -structural ones (showing up only when a change reshapes something). Pass -`--json` if you want structured output for scripts or tools. +structural ones (showing up only when a change reshapes something). Dependency +bumps count for less: a pull request from Renovate, Dependabot or a release bot +counts a quarter as much, and in a dependency projection one that only moves +versions, transitive lockfile entries included, doesn't count. Neither changes +what a projection extracts or draws, only how the sweep ranks it. Pass `--json` +if you want structured output for scripts or tools. In a busy repository, the last 20 merges might cover only a few hours, so every projection looks quiet. Pass `--since` to widen the window: diff --git a/docs/design/onboarding-loop.md b/docs/design/onboarding-loop.md index 6b609606c..4a60f1e19 100644 --- a/docs/design/onboarding-loop.md +++ b/docs/design/onboarding-loop.md @@ -91,6 +91,23 @@ adopted instead. first-parent commits is compared against its parent. Changes are labeled with the pull request number from their commit message (`#123`), and GitHub merge commits use the pull request title from the first line of the message body. +- **Ranking.** A projection's signal (`rare`, `steady`, `noisy`, `quiet`) comes + from how many swept changes it changed on, and two kinds of change count for + less. A change a bot made (`[bot]` accounts, Renovate, Dependabot, + release-notes and changeset bots, listed in `packages/cli/src/sweep/bots.rs`) + counts a quarter as much. Its author decides: a commit's author or committer, + or for a merge commit the merged pull request's author. A bump says little + about the work a repository's people do, but it can still reshape a dependency + graph, so it counts for something. A quarter keeps a run of bumps (7 of 20 + changes on a busy repository) from deciding the signal. A change that only + moved versions (`versionOnly`) doesn't count at all, but only in projections + drawn with the `dependencies` or `github-actions` renderer, and only in their + version attributes. In a dependency graph, a lockfile update that only added, + removed or moved transitive packages is version-only, while a direct + dependency or workspace member added or removed is not. In any other + projection, such as a custom one whose items carry release versions, versions + are what it shows and always count. Neither rule changes an extraction, a + comparison or a picture, only the ranking. - **One definition.** Every revision is extracted with the working tree's definition (matching `compare --definition-revision working-tree`), so a sweep evaluates the projection you are tuning rather than whatever older definition diff --git a/docs/runner/agent-tools.md b/docs/runner/agent-tools.md index 9ec75df2d..f469bfef5 100644 --- a/docs/runner/agent-tools.md +++ b/docs/runner/agent-tools.md @@ -34,8 +34,9 @@ KB, never raw documents—alongside the same facts in `structuredContent`. - `sweep` reports how projections behaved across recent changes: for each projection, how many changes it moved on (N of M), its median change size, the changes where it showed the most, and the changes where several projections - moved together. `latest` summarizes the most recent sweep (such as one run in - the Explore view). + moved together. It says how many changes were bot updates, which count a + quarter as much when ranking. `latest` summarizes the most recent sweep (such + as one run in the Explore view). - `check` returns `projections check`'s report with pass, fail, warn, or skip per check; `render` includes the renderer checks. - `prepare` runs the environment's prepare steps (`projections prepare`) in the diff --git a/packages/cli/src/tools/read/sweep.rs b/packages/cli/src/tools/read/sweep.rs index a5991cd9b..61ccaf287 100644 --- a/packages/cli/src/tools/read/sweep.rs +++ b/packages/cli/src/tools/read/sweep.rs @@ -88,6 +88,10 @@ pub(in crate::tools) fn summarize_sweep(sweep: &Value) -> Outcome { "" } ); + let bots = changes.iter().filter(|change| change["bot"] == true).count(); + if let Some(note) = crate::sweep::bots::note(bots, total) { + let _ = writeln!(out, "{note}."); + } let mut projections = Vec::new(); let ranked = signal::ranked(rows.iter().copied(), &cells); for (row, tally) in &ranked { @@ -117,7 +121,7 @@ pub(in crate::tools) fn summarize_sweep(sweep: &Value) -> Outcome { .collect(); Outcome::new( out, - json!({"id": sweep["id"], "status": sweep["status"], "changes": total, "projections": projections, "busiest": busiest}), + json!({"id": sweep["id"], "status": sweep["status"], "changes": total, "botChanges": bots, "projections": projections, "busiest": busiest}), ) } diff --git a/packages/cli/src/tools/tests.rs b/packages/cli/src/tools/tests.rs index d627f1090..5223d0768 100644 --- a/packages/cli/src/tools/tests.rs +++ b/packages/cli/src/tools/tests.rs @@ -232,6 +232,17 @@ fn a_sweep_is_summarized_per_projection() { assert_eq!(projections[2]["projection"], "flags"); } +#[test] +fn a_sweep_summary_says_how_many_changes_bots_made() { + let changes: Vec = (1..=4) + .map(|number| json!({"before": format!("b{number}"), "after": format!("a{number}"), "number": number, "bot": number == 2})) + .collect(); + let sweep = json!({"id": "s", "status": "completed", "changes": changes, "cells": [], "projections": []}); + let outcome = summarize_sweep(&sweep); + assert!(outcome.text.contains("1 of 4 changes was a bot update "), "{}", outcome.text); + assert_eq!(outcome.structured["botChanges"], 1); +} + #[test] fn built_in_parts_are_described() { let extractor = describe_part(&json!({"part": "extractor", "id": "repository-map"})).unwrap(); diff --git a/tools/scripts/reference-docs/agents.mjs b/tools/scripts/reference-docs/agents.mjs index 769de80da..0b99789e5 100644 --- a/tools/scripts/reference-docs/agents.mjs +++ b/tools/scripts/reference-docs/agents.mjs @@ -105,8 +105,8 @@ ${await agentBody('docs/setup/install.md')}`, "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.", 'Sweep: the `sweep` tool, or `projections explore --sweep --json`, runs each one on the last 20 merges into this branch (`--last N` for more). In a busy repository those may span only hours, leaving every projection `quiet`: check the changes’ dates and sweep again with `--since 30d`, which spreads the changes across that window. Projections that run repository code are skipped unless you pass `--trust`; ask the person first.', '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, only on version updates (a dependency or action bump marked `versionOnly`), or only on bot updates); and the pull requests where several changed. " + - 'A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were), and in a dependency or GitHub Actions projection a lockfile update that only moved transitive packages is `versionOnly`; neither changes what a projection extracts, compares or draws. ' + + "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, or only on version updates marked `versionOnly`, such as a dependency or action bump, or only on bot updates); and the pull requests where several changed. " + + 'A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were). Only dependency and GitHub Actions projections can be `versionOnly`, a lockfile update that only moved transitive packages included; in any other projection a version that changed counts. Neither changes what a projection extracts, compares or draws. ' + 'Recommend projections that show something characteristic of this codebase (the picture a long-time maintainer would recognize as theirs), not just the ones that change least. Don’t add `repository-map` or `code-statistics`, which explore no longer proposes: they only show what Projections can draw, not this codebase. ' + 'To look at one yourself, draw it: `projections compare .. -p --png FILE` (a new file outside the repository).', '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.', From ec3a5fa4ff4e2c40d1c7db263b90fbb930bbe30f Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:27:12 +0000 Subject: [PATCH 4/7] Changelog fragment for #399 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/399.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 changelog.d/399.md diff --git a/changelog.d/399.md b/changelog.d/399.md new file mode 100644 index 000000000..b8354de4b --- /dev/null +++ b/changelog.d/399.md @@ -0,0 +1,6 @@ +--- +section: authoring +--- + +- **Sweeps count bot updates for less** (#399). `projections explore --sweep` now marks a change as a bot change when a bot authored it. For a squash or rebase merge, it checks the commit's author or committer; for a merge commit, it checks the merged pull request's author. Bots are `[bot]` accounts, Renovate, Dependabot, and common release-notes and changeset bots. A bot change is still swept, but counts a quarter as much when projections are ranked, so a run of dependency bumps no longer decides a projection's signal. A projection that changed only on bot updates is `quiet` once four other changes have been judged. The summary says how many changes were bot updates (for example "7 of 20 changes were bot updates"), as does the `sweep` agent tool. The JSON adds `botChanges`, each change's `author` and `bot`, each cell's `bot`, and each projection's `bots` count. The Explore view in the viewer ranks the same way. +- **Version-only changes apply only to dependency projections, and cover lockfile churn** (#399). A sweep now marks a change as `versionOnly` only in projections drawn with the `dependencies` or `github-actions` renderer, and only when their version attributes changed. In a dependency graph, a lockfile update that only moves, adds or removes transitive packages is now version-only, so it no longer makes a dependency projection rank `rare`. Adding or removing a direct dependency or a workspace member still counts as a change. In any other projection, such as a custom projection whose items carry release versions, a changed version always counts, so the projection is no longer ranked `quiet` for showing versions. Neither change affects what a projection extracts, compares or draws, only how a sweep ranks it. See [Commands](docs/runner/commands.md). From f63149321f58f54d71dd265735a52ba0a026da12 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:58:24 +0000 Subject: [PATCH 5/7] Sweep: version-only by the definition's presentation.versionAttributes, not its renderer A projection is version-only only in the data attributes its definition names; without the field, no change is. Explore writes the field into the built-in dependency and GitHub Actions templates. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/cli/src/artifact/presentation.rs | 27 +++++- packages/cli/src/sweep/run.rs | 5 +- packages/cli/src/sweep/tests.rs | 45 ++++++---- packages/cli/src/sweep/versions.rs | 99 +++++++++------------ packages/cli/tests/authoring.rs | 25 ++++-- packages/cli/tests/native.rs | 7 +- packages/extractors/catalog/src/lib.rs | 19 ++++ packages/schemas/internal/runner-api.json | 2 +- packages/schemas/schemas/definition/v0.json | 12 ++- packages/schemas/src/runner/api.ts | 2 +- packages/schemas/src/typebox/definition.ts | 11 ++- 11 files changed, 169 insertions(+), 85 deletions(-) diff --git a/packages/cli/src/artifact/presentation.rs b/packages/cli/src/artifact/presentation.rs index 95bada191..ecc855dec 100644 --- a/packages/cli/src/artifact/presentation.rs +++ b/packages/cli/src/artifact/presentation.rs @@ -9,7 +9,15 @@ use super::{fields, object, parse, values::safe_positive_integer}; pub(crate) fn presentation_defaults(value: &Value) -> Result { fields( value, - &["highlighting", "changesOnly", "mode", "durationMs", "rendererOptions", "kinds"], + &[ + "highlighting", + "changesOnly", + "mode", + "durationMs", + "rendererOptions", + "kinds", + "versionAttributes", + ], "presentation", )?; let choice = |key: &str, allowed: &[&str]| -> Result> { @@ -63,9 +71,26 @@ pub(crate) fn presentation_defaults(value: &Value) -> Result { if let Some(kinds) = value.get("kinds") { result["kinds"] = kind_presentation(kinds)?; } + if let Some(attributes) = value.get("versionAttributes") { + result["versionAttributes"] = version_attributes(attributes)?; + } Ok(result) } +/// `presentation.versionAttributes`: the data attributes that hold only versions, which `explore --sweep` reads to set +/// version bumps apart when it ranks projections. Viewers and comparisons ignore it. +fn version_attributes(value: &Value) -> Result { + let attributes = value.as_array().filter(|attributes| (1..=16).contains(&attributes.len())); + let names: Vec<&str> = attributes.into_iter().flatten().filter_map(Value::as_str).collect(); + ensure!( + attributes.is_some_and(|attributes| names.len() == attributes.len()) + && names.iter().all(|name| !name.is_empty() && name.chars().count() <= 64) + && names.iter().enumerate().all(|(index, name)| !names[..index].contains(name)), + "presentation.versionAttributes must be 1 to 16 different attribute names of 1 to 64 characters" + ); + Ok(json!(names)) +} + /// The colors a kind may take (`packages/schemas/src/constants.ts`, `kindColors`): meanings, then the categorical hues. const KIND_COLORS: &[&str] = &[ "danger", "warning", "success", "info", "neutral", "blue", "teal", "pink", "lime", "purple", "cyan", "indigo", "sky", "orange", diff --git a/packages/cli/src/sweep/run.rs b/packages/cli/src/sweep/run.rs index ed0eccbbd..9a9a306b5 100644 --- a/packages/cli/src/sweep/run.rs +++ b/packages/cli/src/sweep/run.rs @@ -5,7 +5,7 @@ use super::{ Cache, Cell, Change, Request, - versions::{Versioning, version_only}, + versions::{attributes, version_only}, }; use crate::{ artifact, @@ -226,8 +226,7 @@ impl Sweep<'_> { }; match artifact::compare_extractions_with(&before, &after, definition.rules.as_deref()) { Ok(comparison) => { - let versions = - Versioning::of(&definition.definition).is_some_and(|versioning| version_only(versioning, &comparison, &before, &after)); + let versions = version_only(&attributes(&definition.definition), &comparison, &before, &after); let mut cell = compared(base, comparison); if versions { cell.value["versionOnly"] = json!(true); diff --git a/packages/cli/src/sweep/tests.rs b/packages/cli/src/sweep/tests.rs index a05b86e7f..13216729f 100644 --- a/packages/cli/src/sweep/tests.rs +++ b/packages/cli/src/sweep/tests.rs @@ -246,9 +246,13 @@ fn compared(changes: &[(&str, &str, &str)]) -> serde_json::Value { }).collect::>()}}) } +/// The version attributes `projections explore` writes into the built-in GitHub Actions and dependency projections. +const ACTIONS: &[&str] = &["ref", "uses", "image"]; +const DEPENDENCIES: &[&str] = &["version", "resolved", "revision"]; + #[test] fn an_action_bump_only_moves_versions() { - use super::versions::{Versioning, version_only}; + use super::versions::version_only; let document = |reference: &str, image: &str| { json!({"extraction": {"entities": [ {"id": "job:build", "kind": "job", "label": "build", @@ -258,7 +262,7 @@ fn an_action_bump_only_moves_versions() { ], "relationships": []}}) }; let job = compared(&[("entities", "job:build", "modified")]); - let actions = |before: &serde_json::Value, after: &serde_json::Value| version_only(Versioning::Actions, &job, before, after); + let actions = |before: &serde_json::Value, after: &serde_json::Value| version_only(ACTIONS, &job, before, after); let before = document("v4", "node:20.1.0"); assert!(actions(&before, &document("v5", "node:20.2.0"))); assert!(actions( @@ -273,8 +277,8 @@ fn an_action_bump_only_moves_versions() { renamed["extraction"]["entities"][0]["label"] = json!("compile"); assert!(!actions(&before, &renamed)); let added = compared(&[("entities", "job:test", "added")]); - assert!(!version_only(Versioning::Actions, &added, &before, &before)); - assert!(!version_only(Versioning::Actions, &compared(&[]), &before, &before)); + assert!(!version_only(ACTIONS, &added, &before, &before)); + assert!(!version_only(ACTIONS, &compared(&[]), &before, &before)); } /// A Node workspace's dependency graph, as workspace-dependencies extracts it: the workspace `web` (at @@ -303,9 +307,9 @@ fn graph(version: &str, transitive: &str, extra: &[&str]) -> serde_json::Value { #[test] fn lockfile_only_transitive_churn_only_moves_versions() { - use super::versions::{Versioning, version_only}; + use super::versions::version_only; let dependencies = |changes: &[(&str, &str, &str)], before: &serde_json::Value, after: &serde_json::Value| { - version_only(Versioning::Dependencies, &compared(changes), before, after) + version_only(DEPENDENCIES, &compared(changes), before, after) }; let b_edge = "dependency:[\"package:a\",\"dependencies\",\"b\"]"; let c_edge = "dependency:[\"package:b\",\"dependencies\",\"c\"]"; @@ -356,19 +360,30 @@ fn lockfile_only_transitive_churn_only_moves_versions() { let mut sourced = before.clone(); sourced["extraction"]["entities"][2]["data"]["source"] = json!("git+https://example.invalid/b.git"); assert!(!dependencies(&[("entities", "package:b", "modified")], &before, &sourced)); - // Only dependency graphs add and drop transitive packages as churn. - assert!(!version_only(Versioning::Actions, &compared(&churn), &before, &churned)); + // Only dependency graphs, with roots, add and drop transitive packages as churn. + let mut rootless = churned.clone(); + rootless["extraction"]["entities"][0]["data"]["workspaceMember"] = json!(false); + assert!(!dependencies(&churn, &before, &rootless)); } #[test] -fn only_dependency_like_projections_are_version_only() { - use super::versions::Versioning; - assert_eq!(Versioning::of(&json!({"renderer": "dependencies"})), Some(Versioning::Dependencies)); - assert_eq!(Versioning::of(&json!({"renderer": "github-actions"})), Some(Versioning::Actions)); - // A custom projection whose items carry versions (each release's, say) shows them: they are never only versions. - for renderer in [json!("graph"), json!("architecture"), json!({"bundle": "renderer.js"})] { - assert_eq!(Versioning::of(&json!({"renderer": renderer})), None, "{renderer}"); +fn only_projections_that_name_their_version_attributes_are_version_only() { + use super::versions::{attributes, version_only}; + let declared = json!({"renderer": "dependencies", "presentation": {"versionAttributes": ["version", "resolved"]}}); + assert_eq!(attributes(&declared), ["version", "resolved"]); + // A custom projection whose items carry versions (each release's, say) shows them: without the field, even a change + // to nothing but a version is a change, whatever its renderer. + for definition in [ + json!({"renderer": "graph"}), + json!({"renderer": "dependencies"}), + json!({"renderer": "graph", "presentation": {}}), + ] { + assert!(attributes(&definition).is_empty(), "{definition}"); } + let bumped = graph("1.0.0", "2.1.0", &[]); + let bump = compared(&[("entities", "package:b", "modified")]); + assert!(!version_only(&[], &bump, &graph("1.0.0", "2.0.0", &[]), &bumped)); + assert!(version_only(&["version"], &bump, &graph("1.0.0", "2.0.0", &[]), &bumped)); } #[test] diff --git a/packages/cli/src/sweep/versions.rs b/packages/cli/src/sweep/versions.rs index 2a4649eff..371c48421 100644 --- a/packages/cli/src/sweep/versions.rs +++ b/packages/cli/src/sweep/versions.rs @@ -1,39 +1,21 @@ //! Which changes only moved versions, as a dependency or action bump does. A sweep marks those cells //! `versionOnly`, and they don't count when projections are ranked ([`super::signal`]); extractions, comparisons and -//! pictures are the same either way. Only dependency-like projections ([`Versioning`]) can be version-only, and only in -//! their version attributes: a custom projection whose items carry versions shows them. +//! pictures are the same either way. Only a projection whose definition names its version attributes +//! (`presentation.versionAttributes`, see [`attributes`]) can be version-only, and only in those attributes: any other +//! projection, a custom one whose items carry versions it shows included, counts every change. use serde_json::Value; -/// How a dependency-like projection's items carry versions, the only projections whose changes can be version-only. -/// It is told by the definition's renderer, which says what its items are: `dependencies` (packages and the -/// dependencies between them, each with its `version`) or `github-actions` (jobs and the actions, reusable -/// workflows and images they pin). Any other projection, a custom one whose items happen to carry versions -/// included, is never version-only: a version there is what it shows. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Versioning { - Dependencies, - Actions, -} - -impl Versioning { - pub(super) fn of(definition: &Value) -> Option { - match definition["renderer"].as_str()? { - "dependencies" => Some(Self::Dependencies), - "github-actions" => Some(Self::Actions), - _ => None, - } - } - - /// The data fields that hold an item's version, at any depth. - fn attributes(self) -> &'static [&'static str] { - match self { - // A package's version, a declaration's range and the version it resolved to, a pinned revision. - Self::Dependencies => &["version", "resolved", "revision"], - // An action's ref, a reusable workflow's `@ref`, an image's tag or digest. - Self::Actions => &["ref", "uses", "image"], - } - } +/// The data attributes a definition says hold only versions (`presentation.versionAttributes`): none, so never +/// version-only, when it doesn't say. `projections explore` writes them into the built-in dependency and GitHub +/// Actions projections it proposes (`VERSION_ATTRIBUTES` in packages/extractors/catalog/src/lib.rs). +pub(super) fn attributes(definition: &Value) -> Vec<&str> { + definition["presentation"]["versionAttributes"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect() } /// Entity kinds a dependency graph starts from besides workspace members: projects and their target frameworks, @@ -44,15 +26,18 @@ const ROOT_KINDS: &[&str] = &["project", "target-framework", "target", "product" const MEMBERSHIP_KINDS: &[&str] = &["resolved"]; /// Whether every change a comparison found only moved versions, as a dependency or action bump does (`v4` to `v5`, -/// `1.2.3` to `1.3.0`, one pinned commit to another), for a projection that carries versions as `versioning` says. +/// `1.2.3` to `1.3.0`, one pinned commit to another), in a projection whose version `attributes` these are. /// -/// Every modified item must be the same once its version attributes are masked (and its label, where the label is -/// its version, as a dependency's declared range is). In a dependency graph, packages installed only transitively -/// and the dependencies between them may also be added or removed, as a lockfile's churn adds and drops them; but a -/// direct dependency (one a workspace member, project or target declares) added or removed, or a workspace member -/// added, removed or changed other than in its own version, is a real change. -pub(super) fn version_only(versioning: Versioning, comparison: &Value, before: &Value, after: &Value) -> bool { - let Some(changes) = comparison["comparison"]["changes"].as_array().filter(|changes| !changes.is_empty()) else { +/// Every modified item must be the same once the versions in those attributes are masked (and its label, where the +/// label is one of their values, as a dependency's declared range is). In a dependency graph (one with roots: workspace +/// members, projects, frameworks or targets), packages installed only transitively and the dependencies between them +/// may also be added or removed, as a lockfile's churn adds and drops them; but a direct dependency (one a root +/// declares) added or removed, or a root added, removed or changed other than in its versions, is a real change. +pub(super) fn version_only(attributes: &[&str], comparison: &Value, before: &Value, after: &Value) -> bool { + let Some(changes) = comparison["comparison"]["changes"] + .as_array() + .filter(|changes| !changes.is_empty() && !attributes.is_empty()) + else { return false; }; changes.iter().all(|change| { @@ -61,14 +46,10 @@ pub(super) fn version_only(versioning: Versioning, comparison: &Value, before: & match change["status"].as_str() { Some("modified") => matches!( (old, new), - (Some(old), Some(new)) if masked(versioning, old) == masked(versioning, new) + (Some(old), Some(new)) if masked(attributes, old) == masked(attributes, new) ), - Some("added") if versioning == Versioning::Dependencies => { - new.is_some_and(|new| transitive(after, change["collection"].as_str(), new)) - } - Some("removed") if versioning == Versioning::Dependencies => { - old.is_some_and(|old| transitive(before, change["collection"].as_str(), old)) - } + Some("added") => new.is_some_and(|new| transitive(after, change["collection"].as_str(), new)), + Some("removed") => old.is_some_and(|old| transitive(before, change["collection"].as_str(), old)), _ => false, } }) @@ -87,14 +68,17 @@ fn root(entity: &Value) -> bool { } /// Whether a dependency graph's item is only transitive: a package that isn't a root, or a dependency (or membership) -/// that no root declares. +/// that no root declares. Never, in an extraction without roots: that isn't a dependency graph. fn transitive(document: &Value, collection: Option<&str>, item: &Value) -> bool { + let entities = document["extraction"]["entities"].as_array(); + if !entities.is_some_and(|entities| entities.iter().any(root)) { + return false; + } match collection { Some("entities") => !root(item), Some("relationships") => { item["kind"].as_str().is_some_and(|kind| MEMBERSHIP_KINDS.contains(&kind)) - || document["extraction"]["entities"] - .as_array() + || entities .and_then(|entities| entities.iter().find(|entity| entity["id"] == item["from"])) .is_some_and(|from| !root(from)) } @@ -102,20 +86,25 @@ fn transitive(document: &Value, collection: Option<&str>, item: &Value) -> bool } } -/// An item with the versions in its version attributes masked (and its label, where its label is its version), and -/// its evidence left out. -fn masked(versioning: Versioning, item: &Value) -> Value { +/// An item with the versions in its version attributes masked (and its label, where its label is one of their +/// values), and its evidence left out. +fn masked(attributes: &[&str], item: &Value) -> Value { let mut item = item.clone(); let Some(fields) = item.as_object_mut() else { return item; }; fields.remove("evidence"); - let version = fields.get("data").and_then(|data| data["version"].as_str()).map(str::to_owned); - if version.is_some() && fields.get("label").and_then(Value::as_str) == version.as_deref() { + let label = fields.get("label").cloned(); + if label.as_ref().is_some_and(|label| { + label.is_string() + && attributes + .iter() + .any(|key| fields.get("data").is_some_and(|data| data[*key] == *label)) + }) { fields.insert("label".to_owned(), mask(&fields["label"])); } if let Some(data) = fields.get_mut("data") { - mask_attributes(versioning.attributes(), data); + mask_attributes(attributes, data); } item } diff --git a/packages/cli/tests/authoring.rs b/packages/cli/tests/authoring.rs index 187e094e0..aedf6783b 100644 --- a/packages/cli/tests/authoring.rs +++ b/packages/cli/tests/authoring.rs @@ -1467,14 +1467,29 @@ fn npm_workspace(root: &Path, version: &str, transitive: &str, extra: &[&str]) { fn a_sweep_discounts_bot_updates_and_lockfile_churn_only_in_dependency_projections() { let repo = repository(None); let root = repo.path(); - // The same graph twice: as dependencies, and as a custom projection that draws it as a graph, whose versions are - // what it shows (as a projection of releases would be). + // The same graph twice: as the dependencies explore proposes, which name their version attributes, and as a custom + // projection that doesn't, whose versions are what it shows (as a projection of releases would be). + npm_workspace(root, "1.0.0", "2.0.0", &[]); + let candidates: Value = serde_json::from_str(&succeed(cli(root, &["explore", "--list", "--json"]))).unwrap(); + let proposed = candidates["candidates"] + .as_array() + .unwrap() + .iter() + .find(|candidate| candidate["id"] == "workspace-dependencies") + .unwrap(); + assert_eq!( + proposed["definition"]["presentation"]["versionAttributes"], + json!(["version", "resolved"]), + "{proposed}" + ); + let mut deps = proposed["definition"].clone(); + deps["id"] = json!("deps"); + let releases = json!({"id": "releases", "title": "releases", "extractor": "workspace-dependencies", "renderer": "graph"}); fs::create_dir_all(root.join(".github/projections")).unwrap(); - for (id, renderer) in [("deps", "dependencies"), ("releases", "graph")] { - let definition = json!({"id": id, "title": id, "extractor": "workspace-dependencies", "renderer": renderer}); + for definition in [deps, releases] { + let id = definition["id"].as_str().unwrap(); fs::write(root.join(format!(".github/projections/{id}.json")), format!("{definition:#}\n")).unwrap(); } - npm_workspace(root, "1.0.0", "2.0.0", &[]); git(root, &["add", "-A"]); git(root, &["commit", "--quiet", "-m", "Start"]); // Renovate updates the lockfile alone: a transitive package moves and pulls in another. diff --git a/packages/cli/tests/native.rs b/packages/cli/tests/native.rs index ef1c824fb..d14fe57be 100644 --- a/packages/cli/tests/native.rs +++ b/packages/cli/tests/native.rs @@ -1175,7 +1175,8 @@ fn presentation_defaults_pass_through_without_changing_the_definition_digest() { let a = commit(repo); let presentation = json!({"highlighting":"on","changesOnly":true,"mode":"side-by-side", "durationMs":4000,"rendererOptions":{"showFiles":false,"depth":2}, - "kinds":{"secret":{"color":"danger","noun":{"singular":"secret","plural":"secrets"}},"hidden":{"color":"teal"}}}); + "kinds":{"secret":{"color":"danger","noun":{"singular":"secret","plural":"secrets"}},"hidden":{"color":"teal"}}, + "versionAttributes":["version","resolved"]}); write(Some(presentation.clone())); fs::write(repo.join("second.txt"), "second").unwrap(); let b = commit(repo); @@ -1213,6 +1214,10 @@ fn presentation_defaults_pass_through_without_changing_the_definition_digest() { json!({"kinds":{"secret":{"noun":{"singular":"secret"}}}}), json!({"kinds":{"secret":{"tone":"danger"}}}), json!({"speed":2}), + json!({"versionAttributes":[]}), + json!({"versionAttributes":"version"}), + json!({"versionAttributes":["version","version"]}), + json!({"versionAttributes":[""]}), ] { write(Some(invalid.clone())); let (ok, stdout, stderr) = run(repo, path.path(), &["list", "--json"]); diff --git a/packages/extractors/catalog/src/lib.rs b/packages/extractors/catalog/src/lib.rs index 7370609f0..018843984 100644 --- a/packages/extractors/catalog/src/lib.rs +++ b/packages/extractors/catalog/src/lib.rs @@ -65,6 +65,22 @@ registry!( projections_extractor_command_output, ); +/// The data attributes that hold only versions, by built-in extractor: written into its template as +/// `presentation.versionAttributes`, so `explore --sweep` can tell a change that only moved versions (a dependency or +/// action bump) from one that changed what the projection shows. Extractors not listed are never version-only. +pub const VERSION_ATTRIBUTES: &[(&str, &[&str])] = &[ + // A package's version, and a declaration's range and the version it resolved to. + ("workspace-dependencies", &["version", "resolved"]), + ("cargo-dependencies", &["version"]), + ("nuget-dependencies", &["version"]), + // A pin's version or revision, and the requirement it was declared with. + ("swift-package-dependencies", &["version", "revision", "requirement"]), + // The same, and each project's pin where projects pin a package differently. + ("xcode-modules", &["version", "revision", "requirement", "resolved"]), + // An action's ref, a reusable workflow's `@ref`, an image's tag or digest. + ("github-actions-jobs", &["ref", "uses", "image"]), +]; + fn template(descriptor: &Descriptor) -> Value { let mut template = json!({"id":descriptor.id,"title":descriptor.title,"extractor":descriptor.id,"renderer":descriptor.renderer}); if let Some(inputs) = &descriptor.template_inputs { @@ -73,6 +89,9 @@ fn template(descriptor: &Descriptor) -> Value { if let Some(execution) = &descriptor.template_execution { template["execution"] = execution.clone(); } + if let Some((_, attributes)) = VERSION_ATTRIBUTES.iter().find(|(id, _)| *id == descriptor.id) { + template["presentation"] = json!({"versionAttributes": attributes}); + } template } diff --git a/packages/schemas/internal/runner-api.json b/packages/schemas/internal/runner-api.json index 9f4794add..1cde4c551 100644 --- a/packages/schemas/internal/runner-api.json +++ b/packages/schemas/internal/runner-api.json @@ -222,7 +222,7 @@ "stderr": {"type": "string", "description": "The end of a failed extractor's stderr."}, "versionOnly": { "type": "boolean", - "description": "Changed, but only versions moved (a dependency or action bump), in a projection whose renderer is `dependencies` or `github-actions`." + "description": "Changed, but only the versions in the definition’s `presentation.versionAttributes` moved (a dependency or action bump)." }, "bot": { "type": "boolean", diff --git a/packages/schemas/schemas/definition/v0.json b/packages/schemas/schemas/definition/v0.json index 00a02a112..3972c66cf 100644 --- a/packages/schemas/schemas/definition/v0.json +++ b/packages/schemas/schemas/definition/v0.json @@ -203,7 +203,7 @@ "propertyNames": {"minLength": 1, "maxLength": 256} }, "presentation": { - "description": "Initial host and renderer settings for viewers. Viewers can still change them.", + "description": "Initial host and renderer settings for viewers, and how a sweep ranks the projection. Viewers can still change them.", "type": "object", "additionalProperties": false, "properties": { @@ -229,7 +229,15 @@ "maxProperties": 32, "propertyNames": {"pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"} }, - "kinds": {"$ref": "#/$defs/kinds"} + "kinds": {"$ref": "#/$defs/kinds"}, + "versionAttributes": { + "description": "The data attributes of entities and relationships that hold only versions, such as `[\"version\"]` for a dependency graph. When a sweep (`projections explore --sweep`) ranks projections, a change that only moved the versions in these attributes counts as version-only, not as a change. Omitted, no change is version-only. Extractions, comparisons and pictures ignore it.", + "type": "array", + "items": {"type": "string", "minLength": 1, "maxLength": 64}, + "minItems": 1, + "maxItems": 16, + "uniqueItems": true + } } } } diff --git a/packages/schemas/src/runner/api.ts b/packages/schemas/src/runner/api.ts index 9a4fed511..a72c42eed 100644 --- a/packages/schemas/src/runner/api.ts +++ b/packages/schemas/src/runner/api.ts @@ -53,7 +53,7 @@ export const SweepCellSchema = Type.Object({ versionOnly: Type.Optional( Type.Boolean({ description: - 'Changed, but only versions moved (a dependency or action bump), in a projection whose renderer is `dependencies` or `github-actions`.', + 'Changed, but only the versions in the definition’s `presentation.versionAttributes` moved (a dependency or action bump).', }), ), bot: Type.Optional(Type.Boolean({description: "The change is a bot's: it counts a quarter as much when ranking."})), diff --git a/packages/schemas/src/typebox/definition.ts b/packages/schemas/src/typebox/definition.ts index b78389a2a..77c9aefc9 100644 --- a/packages/schemas/src/typebox/definition.ts +++ b/packages/schemas/src/typebox/definition.ts @@ -203,8 +203,17 @@ export const PresentationSettingsSchema = define( }), ), kinds: Type.Optional(KindsSchema), + versionAttributes: Type.Optional( + Type.Array(Type.String({minLength: 1, maxLength: 64}), { + minItems: 1, + maxItems: 16, + uniqueItems: true, + description: + 'The data attributes of entities and relationships that hold only versions, such as `["version"]` for a dependency graph. When a sweep (`projections explore --sweep`) ranks projections, a change that only moved the versions in these attributes counts as version-only, not as a change. Omitted, no change is version-only. Extractions, comparisons and pictures ignore it.', + }), + ), }, - {description: 'Initial host and renderer settings for viewers. Viewers can still change them.'}, + {description: 'Initial host and renderer settings for viewers, and how a sweep ranks the projection. Viewers can still change them.'}, ), ) From ff791538b593db28ce472355eadde8369ff92ce3 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:03:51 +0000 Subject: [PATCH 6/7] init: a built-in extractor's version attributes replace the definition's; its other presentation settings stay Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/cli/src/scaffold/parts.rs | 19 ++++++++++++++++++- packages/cli/src/scaffold/tests.rs | 9 +++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/scaffold/parts.rs b/packages/cli/src/scaffold/parts.rs index e1057c853..7ff444c45 100644 --- a/packages/cli/src/scaffold/parts.rs +++ b/packages/cli/src/scaffold/parts.rs @@ -80,10 +80,11 @@ impl Draft<'_> { for (key, value) in template.as_object().context("Invalid extractor template")? { if key == "execution" { merge_execution(&mut self.definition["execution"], value); - } else if key != "id" && key != "title" && (key != "renderer" || !self.existing) { + } else if key != "id" && key != "title" && key != "presentation" && (key != "renderer" || !self.existing) { self.definition[key] = value.clone(); } } + replace_version_attributes(&mut self.definition, &template); Ok(()) } @@ -134,6 +135,22 @@ impl Draft<'_> { } } +/// A built-in extractor's `presentation.versionAttributes` in place of the definition's, which described another +/// extractor's data; the definition's other presentation settings stay. +fn replace_version_attributes(definition: &mut Value, template: &Value) { + if let Some(presentation) = definition.get_mut("presentation").and_then(Value::as_object_mut) { + presentation.remove("versionAttributes"); + if presentation.is_empty() + && let Some(fields) = definition.as_object_mut() + { + fields.remove("presentation"); + } + } + if let Some(attributes) = template["presentation"].get("versionAttributes") { + definition["presentation"]["versionAttributes"] = attributes.clone(); + } +} + /// A template's `execution` settings added to a definition's own: settings it /// already has are kept, and the environment variables it grants are added to. fn merge_execution(execution: &mut Value, template: &Value) { diff --git a/packages/cli/src/scaffold/tests.rs b/packages/cli/src/scaffold/tests.rs index 68b6737df..da0f5ab34 100644 --- a/packages/cli/src/scaffold/tests.rs +++ b/packages/cli/src/scaffold/tests.rs @@ -173,18 +173,19 @@ fn definitions_are_pretty_and_keep_an_existing_files_layout() { .unwrap(); assert_eq!( fs::read_to_string(&path).unwrap(), - "{\n \"id\": \"deps\",\n \"title\": \"Deps\",\n \"extractor\": \"workspace-dependencies\",\n \"renderer\": \"graph\"\n}\n" + "{\n \"id\": \"deps\",\n \"title\": \"Deps\",\n \"extractor\": \"workspace-dependencies\",\n \"renderer\": \"graph\",\n \"presentation\": {\n \"versionAttributes\": [\n \"version\",\n \"resolved\"\n ]\n }\n}\n" ); - // Changing a part of a definition indented by four spaces keeps its indentation and order. + // Changing a part of a definition indented by four spaces keeps its indentation and order, and its presentation + // settings, but the new extractor's version attributes replace the old one's. fs::write( &path, - "{\n \"renderer\": \"graph\",\n \"extractor\": {\"command\": [\"node\", \"x.mjs\"]},\n \"title\": \"Deps\",\n \"id\": \"deps\"\n}\n", + "{\n \"renderer\": \"graph\",\n \"extractor\": {\"command\": [\"node\", \"x.mjs\"]},\n \"title\": \"Deps\",\n \"id\": \"deps\",\n \"presentation\": {\"mode\": \"diff\", \"versionAttributes\": [\"tag\"]}\n}\n", ) .unwrap(); init(options(None, Some(Extractor::Builtin("workspace-dependencies".into())))).unwrap(); assert_eq!( fs::read_to_string(&path).unwrap(), - "{\n \"renderer\": \"graph\",\n \"extractor\": \"workspace-dependencies\",\n \"title\": \"Deps\",\n \"id\": \"deps\"\n}\n" + "{\n \"renderer\": \"graph\",\n \"extractor\": \"workspace-dependencies\",\n \"title\": \"Deps\",\n \"id\": \"deps\",\n \"presentation\": {\n \"mode\": \"diff\",\n \"versionAttributes\": [\n \"version\",\n \"resolved\"\n ]\n }\n}\n" ); } From addc6846262ea6a56e30e2c209814fc1feb2c8eb Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:08:55 +0000 Subject: [PATCH 7/7] Docs, generated pages and changelog for presentation.versionAttributes Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/399-behaviour-changes.md | 5 ++ changelog.d/399.md | 2 +- docs/agents/create-projection.md | 8 ++- docs/agents/explore.md | 11 ++-- .../builtins/extractors/cargo-dependencies.md | 5 ++ .../extractors/github-actions-jobs.md | 7 +++ .../builtins/extractors/nuget-dependencies.md | 5 ++ .../extractors/swift-package-dependencies.md | 7 +++ .../extractors/workspace-dependencies.md | 6 ++ docs/builtins/extractors/xcode-modules.md | 8 +++ docs/builtins/renderers/github-actions.md | 7 +++ docs/builtins/renderers/graph.md | 6 ++ docs/contracts/definitions.md | 10 +++ docs/design/onboarding-loop.md | 18 +++--- docs/reference/extractors.md | 38 +++++++++++ docs/reference/schemas/definition.md | 3 +- docs/runner/commands.md | 63 ++++++++++--------- docs/setup/quick-start.md | 9 +-- packages/cli/templates/SKILL.md | 8 ++- tools/scripts/reference-docs/agents.mjs | 4 +- 20 files changed, 174 insertions(+), 56 deletions(-) create mode 100644 changelog.d/399-behaviour-changes.md diff --git a/changelog.d/399-behaviour-changes.md b/changelog.d/399-behaviour-changes.md new file mode 100644 index 000000000..8ca81a3cd --- /dev/null +++ b/changelog.d/399-behaviour-changes.md @@ -0,0 +1,5 @@ +--- +section: behaviour-changes +--- + +- **A sweep sets version bumps apart only where the definition names its version attributes** (#399). `projections explore --sweep` used to mark any change that only moved version-like strings as `versionOnly`, in any projection. It now does so only for projections whose definition sets `presentation.versionAttributes`. Projections that `projections explore` proposes or `projections init` writes for the built-in dependency and GitHub Actions extractors include the field. To keep dependency or action bumps from counting in a sweep's ranking, add the field to a definition you already adopted, for example `"presentation": {"versionAttributes": ["version", "resolved"]}` for `workspace-dependencies`, as its [page](docs/builtins/extractors/workspace-dependencies.md) shows. Extractions, comparisons and checks are unaffected. diff --git a/changelog.d/399.md b/changelog.d/399.md index b8354de4b..822fee089 100644 --- a/changelog.d/399.md +++ b/changelog.d/399.md @@ -3,4 +3,4 @@ section: authoring --- - **Sweeps count bot updates for less** (#399). `projections explore --sweep` now marks a change as a bot change when a bot authored it. For a squash or rebase merge, it checks the commit's author or committer; for a merge commit, it checks the merged pull request's author. Bots are `[bot]` accounts, Renovate, Dependabot, and common release-notes and changeset bots. A bot change is still swept, but counts a quarter as much when projections are ranked, so a run of dependency bumps no longer decides a projection's signal. A projection that changed only on bot updates is `quiet` once four other changes have been judged. The summary says how many changes were bot updates (for example "7 of 20 changes were bot updates"), as does the `sweep` agent tool. The JSON adds `botChanges`, each change's `author` and `bot`, each cell's `bot`, and each projection's `bots` count. The Explore view in the viewer ranks the same way. -- **Version-only changes apply only to dependency projections, and cover lockfile churn** (#399). A sweep now marks a change as `versionOnly` only in projections drawn with the `dependencies` or `github-actions` renderer, and only when their version attributes changed. In a dependency graph, a lockfile update that only moves, adds or removes transitive packages is now version-only, so it no longer makes a dependency projection rank `rare`. Adding or removing a direct dependency or a workspace member still counts as a change. In any other projection, such as a custom projection whose items carry release versions, a changed version always counts, so the projection is no longer ranked `quiet` for showing versions. Neither change affects what a projection extracts, compares or draws, only how a sweep ranks it. See [Commands](docs/runner/commands.md). +- **Definitions name the attributes that hold only versions** (#399). A new definition field, `presentation.versionAttributes`, lists the data attributes of entities and relationships that hold only versions, such as `["version", "resolved"]`. When `projections explore --sweep` ranks projections, a change that only moved the versions in those attributes is marked `versionOnly` and doesn't count. In a dependency graph, a lockfile update that only moves, adds or removes transitive packages now counts as version-only too, so it no longer makes a dependency projection rank `rare`. Adding or removing a direct dependency or a workspace member still counts as a change. `projections explore` and `projections init` fill in the field for the built-in dependency extractors (`workspace-dependencies`, `cargo-dependencies`, `nuget-dependencies`, `swift-package-dependencies`, `xcode-modules`) and for `github-actions-jobs`, and a custom projection can opt in. A projection without the field, such as a custom projection whose items carry release versions, counts every changed version, so it is no longer ranked `quiet` for showing versions. The field doesn't affect what a projection extracts, compares or draws. See [Definitions](docs/contracts/definitions.md). diff --git a/docs/agents/create-projection.md b/docs/agents/create-projection.md index 9fec43634..aed8e1386 100644 --- a/docs/agents/create-projection.md +++ b/docs/agents/create-projection.md @@ -211,9 +211,11 @@ adopt. more), `quiet` (never, or only on bot changes) or `unknown` (fewer than four changes swept). A cell marked `versionOnly` changed only versions (a dependency or action bump, or a lockfile update that only moved transitive - packages) and doesn't count as a change; only projections drawn with the - `dependencies` or `github-actions` renderer can be version-only, so a - custom projection whose versions are what it shows always counts them. A + packages) and doesn't count as a change. Only a projection whose definition + lists its version attributes in `presentation.versionAttributes` can be + version-only; explore fills it in for the built-in dependency and GitHub + Actions projections. A custom projection whose versions are what it shows + leaves it out and always counts them. A change marked `bot` (Renovate, Dependabot, a release bot; `botChanges` counts them) counts a quarter as much. Both affect only the ranking, never extractions, comparisons or pictures. On a busy repository, the last 20 merges may span only hours, leaving every diff --git a/docs/agents/explore.md b/docs/agents/explore.md index e807cecd4..d56525277 100644 --- a/docs/agents/explore.md +++ b/docs/agents/explore.md @@ -10,7 +10,7 @@ This file guides you, a coding agent, to find the projections that apply to this 2. Check the CLI: `projections --version`. If it is missing, install it by following https://github.com/githubnext/projections/blob/v0.3.2/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 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). In a busy repository those may span only hours, leaving every projection `quiet`: check the changes’ dates and sweep again with `--since 30d`, which spreads the changes across that window. 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`), 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, or only on version updates marked `versionOnly`, such as a dependency or action bump, or only on bot updates); and the pull requests where several changed. A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were). Only dependency and GitHub Actions projections can be `versionOnly`, a lockfile update that only moved transitive packages included; in any other projection a version that changed counts. Neither changes what a projection extracts, compares or draws. Recommend projections that show something characteristic of this codebase (the picture a long-time maintainer would recognize as theirs), not just the ones that change least. Don’t add `repository-map` or `code-statistics`, which explore no longer proposes: they only show what Projections can draw, not this codebase. To look at one yourself, draw it: `projections compare .. -p --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, or only on version updates marked `versionOnly`, such as a dependency or action bump, or only on bot updates); and the pull requests where several changed. A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were). Only projections whose definitions list their version attributes in `presentation.versionAttributes`, which explore fills in for the built-in dependency and GitHub Actions projections, can be `versionOnly`, a lockfile update that only moved transitive packages included; in any other projection a version that changed counts. Neither changes what a projection extracts, compares or draws. Recommend projections that show something characteristic of this codebase (the picture a long-time maintainer would recognize as theirs), not just the ones that change least. Don’t add `repository-map` or `code-statistics`, which explore no longer proposes: they only show what Projections can draw, not this codebase. To look at one yourself, draw it: `projections compare .. -p --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 ... --dry-run`, then `projections adopt ...`. Built-in projections fit standard systems like Actions workflows, database schemas and package dependencies, but rarely cover what’s distinctive about a codebase. Name the characteristic systems they missed (its own registries, extension points, protocols, pipelines) and offer to build projections for them, usually with custom renderers. To build one, run `projections help agents create-projection` and follow what it prints. 8. Show them each adopted projection yourself: `projections view show -p --choice 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. @@ -87,10 +87,11 @@ The sweep reports how often each projection changed across those pull requests and distinguishes noisy ones (changing on nearly every pull request) from structural ones (showing up only when a change reshapes something). Dependency bumps count for less: a pull request from Renovate, Dependabot or a release bot -counts a quarter as much, and in a dependency projection one that only moves -versions, transitive lockfile entries included, doesn't count. Neither changes -what a projection extracts or draws, only how the sweep ranks it. Pass `--json` -if you want structured output for scripts or tools. +counts a quarter as much. In the built-in dependency and GitHub Actions +projections, whose definitions name their version attributes, a change that only +moves versions, transitive lockfile entries included, doesn't count. Neither +changes what a projection extracts or draws, only how the sweep ranks it. Pass +`--json` if you want structured output for scripts or tools. In a busy repository, the last 20 merges might cover only a few hours, so every projection looks quiet. Pass `--since` to widen the window: diff --git a/docs/builtins/extractors/cargo-dependencies.md b/docs/builtins/extractors/cargo-dependencies.md index 41ac1836c..f0363ff06 100644 --- a/docs/builtins/extractors/cargo-dependencies.md +++ b/docs/builtins/extractors/cargo-dependencies.md @@ -114,6 +114,11 @@ each crate. }, "extractor": "cargo-dependencies", "id": "cargo-dependencies", + "presentation": { + "versionAttributes": [ + "version" + ] + }, "renderer": "dependencies", "title": "Cargo dependencies" } diff --git a/docs/builtins/extractors/github-actions-jobs.md b/docs/builtins/extractors/github-actions-jobs.md index 0325ee4c1..32132ec53 100644 --- a/docs/builtins/extractors/github-actions-jobs.md +++ b/docs/builtins/extractors/github-actions-jobs.md @@ -120,6 +120,13 @@ a plain job graph. "inputs": { "workflowPath": ".github/workflows/ci.yml" }, + "presentation": { + "versionAttributes": [ + "ref", + "uses", + "image" + ] + }, "renderer": "github-actions", "title": "GitHub Actions jobs" } diff --git a/docs/builtins/extractors/nuget-dependencies.md b/docs/builtins/extractors/nuget-dependencies.md index ada8970b8..ed5b84ef0 100644 --- a/docs/builtins/extractors/nuget-dependencies.md +++ b/docs/builtins/extractors/nuget-dependencies.md @@ -108,6 +108,11 @@ each package. }, "extractor": "nuget-dependencies", "id": "nuget-dependencies", + "presentation": { + "versionAttributes": [ + "version" + ] + }, "renderer": "dependencies", "title": "NuGet dependencies" } diff --git a/docs/builtins/extractors/swift-package-dependencies.md b/docs/builtins/extractors/swift-package-dependencies.md index aa7ced0fa..8c9c49468 100644 --- a/docs/builtins/extractors/swift-package-dependencies.md +++ b/docs/builtins/extractors/swift-package-dependencies.md @@ -127,6 +127,13 @@ Your package's targets and products sit on the left as the graph's roots. { "extractor": "swift-package-dependencies", "id": "swift-package-dependencies", + "presentation": { + "versionAttributes": [ + "version", + "revision", + "requirement" + ] + }, "renderer": "dependencies", "title": "Swift package dependencies" } diff --git a/docs/builtins/extractors/workspace-dependencies.md b/docs/builtins/extractors/workspace-dependencies.md index d2327a44a..09ce30aaf 100644 --- a/docs/builtins/extractors/workspace-dependencies.md +++ b/docs/builtins/extractors/workspace-dependencies.md @@ -91,6 +91,12 @@ packages") to keep the diff focused; toggle **All packages** to expand them. { "extractor": "workspace-dependencies", "id": "workspace-dependencies", + "presentation": { + "versionAttributes": [ + "version", + "resolved" + ] + }, "renderer": "dependencies", "title": "Workspace dependencies" } diff --git a/docs/builtins/extractors/xcode-modules.md b/docs/builtins/extractors/xcode-modules.md index e5b38416e..462399099 100644 --- a/docs/builtins/extractors/xcode-modules.md +++ b/docs/builtins/extractors/xcode-modules.md @@ -112,6 +112,14 @@ Your targets sit on the left as the graph's roots. { "extractor": "xcode-modules", "id": "xcode-modules", + "presentation": { + "versionAttributes": [ + "version", + "revision", + "requirement", + "resolved" + ] + }, "renderer": "dependencies", "title": "Xcode modules" } diff --git a/docs/builtins/renderers/github-actions.md b/docs/builtins/renderers/github-actions.md index 43d91b782..7191a9373 100644 --- a/docs/builtins/renderers/github-actions.md +++ b/docs/builtins/renderers/github-actions.md @@ -105,6 +105,13 @@ matrix results in more than one run per job (`2 jobs · 7 runs`). "inputs": { "workflowPath": ".github/workflows/ci.yml" }, + "presentation": { + "versionAttributes": [ + "ref", + "uses", + "image" + ] + }, "renderer": "github-actions", "title": "GitHub Actions jobs" } diff --git a/docs/builtins/renderers/graph.md b/docs/builtins/renderers/graph.md index c6e9fb31f..5102ab44f 100644 --- a/docs/builtins/renderers/graph.md +++ b/docs/builtins/renderers/graph.md @@ -355,6 +355,12 @@ table, where the details panel shows the change and any comparator summary. { "extractor": "workspace-dependencies", "id": "workspace-dependencies", + "presentation": { + "versionAttributes": [ + "version", + "resolved" + ] + }, "renderer": "dependencies", "title": "Workspace dependencies" } diff --git a/docs/contracts/definitions.md b/docs/contracts/definitions.md index 8bc9d2cc3..e172f331b 100644 --- a/docs/contracts/definitions.md +++ b/docs/contracts/definitions.md @@ -171,6 +171,16 @@ still override in the UI: also set a `noun`, `{"singular": …, "plural": …}` (1–64 characters each), for the summary bar's counts. A kind's key also names the matching flag wherever a renderer draws flags. Renderers ignore any kinds they don't draw. +- `versionAttributes` lists the data attributes of entities and relationships + that hold only versions (1–16 names, such as `["version", "resolved"]`). + Viewers ignore it. When `projections explore --sweep` ranks projections, a + change that only moved the versions in these attributes counts as version-only + (`versionOnly`), not as a change, and in a dependency graph so does a lockfile + update that only adds or drops transitive packages. Without it, no change is + version-only. `projections explore` and `projections init` fill it in for the + built-in dependency and GitHub Actions extractors. Leave it out of a + projection whose versions are what it shows, such as one of releases. It never + changes an extraction, a comparison or a picture. ```json "presentation": { diff --git a/docs/design/onboarding-loop.md b/docs/design/onboarding-loop.md index 4a60f1e19..fb5a9f99c 100644 --- a/docs/design/onboarding-loop.md +++ b/docs/design/onboarding-loop.md @@ -101,13 +101,17 @@ adopted instead. graph, so it counts for something. A quarter keeps a run of bumps (7 of 20 changes on a busy repository) from deciding the signal. A change that only moved versions (`versionOnly`) doesn't count at all, but only in projections - drawn with the `dependencies` or `github-actions` renderer, and only in their - version attributes. In a dependency graph, a lockfile update that only added, - removed or moved transitive packages is version-only, while a direct - dependency or workspace member added or removed is not. In any other - projection, such as a custom one whose items carry release versions, versions - are what it shows and always count. Neither rule changes an extraction, a - comparison or a picture, only the ranking. + whose definitions name their version attributes + (`presentation.versionAttributes`), and only in those attributes. Explore + writes the field into the built-in dependency and GitHub Actions templates, + and a custom projection can opt in. The definition says it, not the renderer, + because only the extractor's author knows which attributes are just versions. + In a dependency graph, a lockfile update that only added, removed or moved + transitive packages is version-only, while a direct dependency or workspace + member added or removed is not. In a projection without the field, such as a + custom one whose items carry release versions, versions are what it shows and + always count. Neither rule changes an extraction, a comparison or a picture, + only the ranking. - **One definition.** Every revision is extracted with the working tree's definition (matching `compare --definition-revision working-tree`), so a sweep evaluates the projection you are tuning rather than whatever older definition diff --git a/docs/reference/extractors.md b/docs/reference/extractors.md index 059a148b7..cd51c9486 100644 --- a/docs/reference/extractors.md +++ b/docs/reference/extractors.md @@ -63,6 +63,12 @@ A definition to start from: { "extractor": "workspace-dependencies", "id": "workspace-dependencies", + "presentation": { + "versionAttributes": [ + "version", + "resolved" + ] + }, "renderer": "dependencies", "title": "Workspace dependencies" } @@ -254,6 +260,11 @@ A definition to start from: }, "extractor": "cargo-dependencies", "id": "cargo-dependencies", + "presentation": { + "versionAttributes": [ + "version" + ] + }, "renderer": "dependencies", "title": "Cargo dependencies" } @@ -280,6 +291,13 @@ A definition to start from: { "extractor": "swift-package-dependencies", "id": "swift-package-dependencies", + "presentation": { + "versionAttributes": [ + "version", + "revision", + "requirement" + ] + }, "renderer": "dependencies", "title": "Swift package dependencies" } @@ -305,6 +323,14 @@ A definition to start from: { "extractor": "xcode-modules", "id": "xcode-modules", + "presentation": { + "versionAttributes": [ + "version", + "revision", + "requirement", + "resolved" + ] + }, "renderer": "dependencies", "title": "Xcode modules" } @@ -338,6 +364,11 @@ A definition to start from: }, "extractor": "nuget-dependencies", "id": "nuget-dependencies", + "presentation": { + "versionAttributes": [ + "version" + ] + }, "renderer": "dependencies", "title": "NuGet dependencies" } @@ -430,6 +461,13 @@ A definition to start from: "inputs": { "workflowPath": ".github/workflows/ci.yml" }, + "presentation": { + "versionAttributes": [ + "ref", + "uses", + "image" + ] + }, "renderer": "github-actions", "title": "GitHub Actions jobs" } diff --git a/docs/reference/schemas/definition.md b/docs/reference/schemas/definition.md index 3b890da71..938ef2852 100644 --- a/docs/reference/schemas/definition.md +++ b/docs/reference/schemas/definition.md @@ -106,7 +106,7 @@ Type: map of [`kindPresentation`](#kindpresentation). At most 64 properties. ### `presentation` -Initial host and renderer settings for viewers. Viewers can still change them. +Initial host and renderer settings for viewers, and how a sweep ranks the projection. Viewers can still change them. | Property | Type | Required | Description | |---|---|---|---| @@ -116,5 +116,6 @@ Initial host and renderer settings for viewers. Viewers can still change them. | `durationMs` | integer | | Playback duration from before to after at 1× speed, in milliseconds. Omitted, it scales with the number of steps. At least 500. At most 120000. | | `rendererOptions` | map of string or number or boolean | | Initial values of the renderer's declared controls, keyed by control ID. Hosts ignore unknown IDs and invalid values, with a notice. At most 32 properties. | | `kinds` | [`kinds`](#kinds) | | | +| `versionAttributes` | array of string | | The data attributes of entities and relationships that hold only versions, such as `["version"]` for a dependency graph. When a sweep (`projections explore --sweep`) ranks projections, a change that only moved the versions in these attributes counts as version-only, not as a change. Omitted, no change is version-only. Extractions, comparisons and pictures ignore it. At least 1 item. At most 16 items. Items are unique. | No other properties are allowed. diff --git a/docs/runner/commands.md b/docs/runner/commands.md index a997f5ac2..39a6f885b 100644 --- a/docs/runner/commands.md +++ b/docs/runner/commands.md @@ -64,38 +64,39 @@ projections validate /tmp/services.extraction.json (likely noise), and those that never changed, followed by a summary of which are worth a look. Fewer than four changes aren't judged. A change that only updates versions is marked `versionOnly` and doesn't count, so a projection - with only bumps is `quiet`. Only dependency-like projections, those drawn with - the `dependencies` or `github-actions` renderer, can be version-only: an item - must differ only in its version attributes (a package's `version`, a - dependency's range and `resolved` version, or an action's `ref`, a reusable - workflow's `@ref` and an image's tag), and in a dependency graph a lockfile - update may also add or drop transitive packages, as long as no direct + with only bumps is `quiet`. Only a projection whose definition names its + version attributes in `presentation.versionAttributes` can be version-only: an + item must differ only in the versions in those attributes (such as a package's + `version`, a dependency's range and `resolved` version, or an action's `ref`, + a reusable workflow's `@ref` and an image's tag). In a dependency graph, a + lockfile update may also add or drop transitive packages, as long as no direct dependency is added or removed and no workspace member changes other than in - its own version. A custom projection whose items carry versions (each - release's, say) always counts them. A change a bot made is marked `bot` and - counts a quarter as much: by its author for a squash or rebase merge (or its - committer), and by the pull request's author (the merged branch's head) for a - merge commit. Bots are `[bot]` accounts, Renovate, Dependabot and the common - release-notes and changeset bots, listed in one place, `BOT_AUTHORS` in - `packages/cli/src/sweep/bots.rs`. A quarter keeps a run of bumps from deciding - a projection's signal, which then rests on the changes people made; and once - four changes people made were judged, a projection that changed only on bot - changes is `quiet`. The summary says how many changes were bot updates - (`7 of 20 changes were bot updates`). Neither rule changes an extraction, a - comparison or a picture, only the ranking. Use `-p ID` to narrow the sweep, - and `--json` to print the `projections.sweep` document with `botChanges`, each - change's `author` and `bot`, and each ready projection's `signal` (`rare`, - `steady`, `unknown`, `noisy`, or `quiet`), `changed`, `bots`, `versionOnly` - and `failed` counts. While running, the sweep writes progress to standard - error (one line per change when stderr isn't a terminal). In a shallow clone, - it notes how many changes are missing from history and suggests - `git fetch --unshallow`. On a busy repository, where the last 100 merges may - span only a few hours, pass `--since` with a date (`2026-11-01`) or duration - (`30d`, `2w`, `3m`) to sweep `--last N` changes spaced evenly across all - changes since then. The sweep notes how many changes the window held. At the - end, it prints how many extractions failed and the first reason, exiting - nonzero if all failed. Projections that run repository code are skipped unless - `--trust` is passed. + its versions. Explore writes the field into the built-in dependency and GitHub + Actions projections it proposes. A projection without it, such as a custom one + whose items carry release versions, always counts them. A change a bot made is + marked `bot` and counts a quarter as much: by its author for a squash or + rebase merge (or its committer), and by the pull request's author (the merged + branch's head) for a merge commit. Bots are `[bot]` accounts, Renovate, + Dependabot and the common release-notes and changeset bots, listed in one + place, `BOT_AUTHORS` in `packages/cli/src/sweep/bots.rs`. A quarter keeps a + run of bumps from deciding a projection's signal, which then rests on the + changes people made; and once four changes people made were judged, a + projection that changed only on bot changes is `quiet`. The summary says how + many changes were bot updates (`7 of 20 changes were bot updates`). Neither + rule changes an extraction, a comparison or a picture, only the ranking. Use + `-p ID` to narrow the sweep, and `--json` to print the `projections.sweep` + document with `botChanges`, each change's `author` and `bot`, and each ready + projection's `signal` (`rare`, `steady`, `unknown`, `noisy`, or `quiet`), + `changed`, `bots`, `versionOnly` and `failed` counts. While running, the sweep + writes progress to standard error (one line per change when stderr isn't a + terminal). In a shallow clone, it notes how many changes are missing from + history and suggests `git fetch --unshallow`. On a busy repository, where the + last 100 merges may span only a few hours, pass `--since` with a date + (`2026-11-01`) or duration (`30d`, `2w`, `3m`) to sweep `--last N` changes + spaced evenly across all changes since then. The sweep notes how many changes + the window held. At the end, it prints how many extractions failed and the + first reason, exiting nonzero if all failed. Projections that run repository + code are skipped unless `--trust` is passed. - `adopt ID...` writes definitions for the chosen explore candidates into `.github/projections/ID.json` (or `.projections/` if the repository uses it, never overwriting an existing file) and adds the `--bookmarks N` (default 3) diff --git a/docs/setup/quick-start.md b/docs/setup/quick-start.md index e0b5245b7..76af0c65f 100644 --- a/docs/setup/quick-start.md +++ b/docs/setup/quick-start.md @@ -69,10 +69,11 @@ The sweep reports how often each projection changed across those pull requests and distinguishes noisy ones (changing on nearly every pull request) from structural ones (showing up only when a change reshapes something). Dependency bumps count for less: a pull request from Renovate, Dependabot or a release bot -counts a quarter as much, and in a dependency projection one that only moves -versions, transitive lockfile entries included, doesn't count. Neither changes -what a projection extracts or draws, only how the sweep ranks it. Pass `--json` -if you want structured output for scripts or tools. +counts a quarter as much. In the built-in dependency and GitHub Actions +projections, whose definitions name their version attributes, a change that only +moves versions, transitive lockfile entries included, doesn't count. Neither +changes what a projection extracts or draws, only how the sweep ranks it. Pass +`--json` if you want structured output for scripts or tools. In a busy repository, the last 20 merges might cover only a few hours, so every projection looks quiet. Pass `--since` to widen the window: diff --git a/packages/cli/templates/SKILL.md b/packages/cli/templates/SKILL.md index 4cabb0290..5009a8812 100644 --- a/packages/cli/templates/SKILL.md +++ b/packages/cli/templates/SKILL.md @@ -203,9 +203,11 @@ adopt. more), `quiet` (never, or only on bot changes) or `unknown` (fewer than four changes swept). A cell marked `versionOnly` changed only versions (a dependency or action bump, or a lockfile update that only moved transitive - packages) and doesn't count as a change; only projections drawn with the - `dependencies` or `github-actions` renderer can be version-only, so a - custom projection whose versions are what it shows always counts them. A + packages) and doesn't count as a change. Only a projection whose definition + lists its version attributes in `presentation.versionAttributes` can be + version-only; explore fills it in for the built-in dependency and GitHub + Actions projections. A custom projection whose versions are what it shows + leaves it out and always counts them. A change marked `bot` (Renovate, Dependabot, a release bot; `botChanges` counts them) counts a quarter as much. Both affect only the ranking, never extractions, comparisons or pictures. On a busy repository, the last 20 merges may span only hours, leaving every diff --git a/tools/scripts/reference-docs/agents.mjs b/tools/scripts/reference-docs/agents.mjs index 0b99789e5..27e19ab09 100644 --- a/tools/scripts/reference-docs/agents.mjs +++ b/tools/scripts/reference-docs/agents.mjs @@ -106,7 +106,9 @@ ${await agentBody('docs/setup/install.md')}`, 'Sweep: the `sweep` tool, or `projections explore --sweep --json`, runs each one on the last 20 merges into this branch (`--last N` for more). In a busy repository those may span only hours, leaving every projection `quiet`: check the changes’ dates and sweep again with `--since 30d`, which spreads the changes across that window. Projections that run repository code are skipped unless you pass `--trust`; ask the person first.', '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, or only on version updates marked `versionOnly`, such as a dependency or action bump, or only on bot updates); and the pull requests where several changed. " + - 'A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were). Only dependency and GitHub Actions projections can be `versionOnly`, a lockfile update that only moved transitive packages included; in any other projection a version that changed counts. Neither changes what a projection extracts, compares or draws. ' + + 'A change Renovate, Dependabot or a release bot made is marked `bot` and counts a quarter as much in the ranking (the sweep says how many there were). ' + + 'Only projections whose definitions list their version attributes in `presentation.versionAttributes`, which explore fills in for the built-in dependency and GitHub Actions projections, can be `versionOnly`, ' + + 'a lockfile update that only moved transitive packages included; in any other projection a version that changed counts. Neither changes what a projection extracts, compares or draws. ' + 'Recommend projections that show something characteristic of this codebase (the picture a long-time maintainer would recognize as theirs), not just the ones that change least. Don’t add `repository-map` or `code-statistics`, which explore no longer proposes: they only show what Projections can draw, not this codebase. ' + 'To look at one yourself, draw it: `projections compare .. -p --png FILE` (a new file outside the repository).', '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.',