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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 68 additions & 14 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ or removing a command fails until the table changes in the same commit.
| `git.changelists` | Reduce local ChangeList metadata and project membership and commit scope |
| `git.shelf` | Capture or applies one guarded Shelf layer |
| `git.commitMessageContext` | Capture bounded AI commit evidence and recheck its Git state |
| `git.consolePresentation` | Pure IDEA-style configuration/progress folds, empty-output notices and search ranges over retained diagnostic snapshots |
| `git.consolePresentation` | Pure IDEA-style configuration/progress/query folds, empty-output notices and search ranges over retained diagnostic snapshots, shaped by the console's display choices |
| `git.remoteUrl` | Read a configured remote URL silently; a missing remote returns a null URL |
| `git.fetchPlan` | Validate Fetch choices; optionally inspect a repository to expand enabled per-remote commands |
| `git.executable` | Resolve the executable Git will run without requiring a repository |
Expand Down Expand Up @@ -1060,8 +1060,9 @@ is active; it does not wait behind a mutex outside its cancellation deadline.
Git requests may include optional envelope metadata `gitExecution`:
`{ executable?: string | null, interactive?: boolean, useCredentialHelper?: boolean,
fetchDefaults?: GitFetchOptions, detailedFetch?: boolean, source?: "user" | "background" | "unknown",
reportQueries?: boolean }`. Defaults are PATH, noninteractive, helper enabled, normal
Fetch defaults, legacy Fetch results, and silent internal queries.
consoleQueries?: QueryCategory[], queryCategory?: QueryCategory }`. Defaults are PATH,
noninteractive, helper enabled, normal Fetch defaults, legacy Fetch results, and no
recorded query category, which leaves every internal query silent as IDEA does.
An executable must be an absolute native path to Git 2.31 or newer. Interactive
commands require an event receiver. These values are request-scoped, including
nested requests, and never implicitly persist. Both current applications opt
Expand Down Expand Up @@ -1180,7 +1181,7 @@ Each event has `operationId` and `type`:
| Type | Additional fields |
| --- | --- |
| `requestStarted` | none; cancellation is registered before delivery |
| `started` | `invocationId`, `workingDirectory`, `arguments`, nullable resolved `executable`, `temporaryConfig` key/value pairs, `displayArguments`, `globalArguments`, `source`, `query` |
| `started` | `invocationId`, `workingDirectory`, `arguments`, nullable resolved `executable`, `temporaryConfig` key/value pairs, `displayArguments`, `globalArguments`, `source`, `query`, and a query's `queryCategory` when it has one |
| `output` | `invocationId`, `stream` (`stdout`/`stderr`), `text`, `progress`, `truncated`, optional `progressDetails` (`stage`, nullable `percent`, `completed`, `total`) |
| `finished` | `invocationId`, nullable `exitCode`, monotonic `durationMilliseconds`, nullable `error`, `expectedExit` |
| `requestFinished` | nullable `error`, including failures before a child started; `unconfirmedInvocations`, the started records without `finished`; `failureRecord`, true when `error` is set, is not a cancellation, and no record of the request failed or is unconfirmed, so the host shows the error as its own record |
Expand All @@ -1196,7 +1197,7 @@ Native journals track `requestStarted` separately from visible command records.
The native receiver retains the originating request directory so a failure before
`started` can be shown as an unconfirmed request with no fabricated arguments or
exit code. Successfully completed internal queries still produce no history row
unless they were reported through `gitExecution.reportQueries`.
unless their category is one the request's `gitExecution.consoleQueries` records.
A request that ends with the `cancelled` error before any command started was
superseded, not a Git failure, and also produces no row; a cancelled request that
had started a command keeps that command with the cancellation as its reason.
Expand All @@ -1213,25 +1214,78 @@ Notices require empty retained output, no progress, no truncation and no failure
zero `updatedReferenceCount` and `deletedReferenceCount`. Missing counts must not
be treated as zero. Other successful empty results use `completedWithoutOutput`.

`git.consolePresentation` accepts `{ records, search?: string, display?: { foldShortQueries?:
boolean, showCompletedWithoutOutput?: boolean, hideTemporaryConfig?: boolean,
hideRepository?: boolean } }`. Every display choice defaults to `false`, which is IDEA's
console: a query that wrote ten lines or fewer keeps them visible, `completedWithoutOutput`
is omitted (IDEA prints nothing after an empty command; `waitingForOutput` and
`fetchUnchanged` stay), temporary `-c` configuration is folded rather than left out, and each
entry is labelled with its repository. `foldShortQueries` folds a successful query's output
at any length. `hideTemporaryConfig` leaves Core's temporary configuration out of the command
fragments; `-c` pairs in the operation's own arguments still fold in place. `hideRepository`
returns an empty `repositoryLabel` and excludes the repository from search. A host persists
these as console preferences; they never change the retained records or copied commands.

Output folds only when it is longer than ten lines: a contiguous block of Git progress lines
(IDEA's progress grammar, remote phases included) becomes one `progress` fragment once it has
more than ten lines, and shorter blocks stay `text`. A failed record folds no output. A record
whose arguments delete something folds nothing at all, neither its `-c` configuration nor its
progress nor a query's output, whatever the display choices, so the console shows everything
a deletion ran with and reported; `hideTemporaryConfig` still leaves the temporary
configuration out. Deleting means, after the global options: `rm` and `clean` (a dry-run
`clean -n` lists what a clean deletes); `branch`, `tag`, `update-ref` or `symbolic-ref` with
`-d`, `-D` or `--delete`; `push` with `-d`, `--delete`, `--prune` or a refspec without a
source (`:refs/heads/topic`); `fetch` or `pull` with `-p`, `--prune`, `-P` or `--prune-tags`;
`remote remove`, `remote rm`, `remote prune` and `remote update --prune`; `config` with
`--unset`, `--unset-all`, `--remove-section`, `unset` or `remove-section`; `stash drop`,
`stash clear` and `stash pop`; and `worktree remove` and `worktree prune`. Only options
before `--` count. See the `deletions` table of `rust/fixtures/git/console-presentation-v1.json`.

`displayArguments` and `globalArguments` are additive console projections: the
former starts at the subcommand, and the latter contains temporary configuration
as `-c key=value` pairs followed by the original global argument prefix. Consoles
fold contiguous `-c` pairs at their original positions; other global arguments
stay visible. Raw `arguments` remain authoritative for copying and diagnostics. Older events without projections retain their legacy display.
Visible workflow commands and explicit `git.command` requests produce execution
events. Internal read-only queries remain silent in the console while retaining
normal workflow capture and result semantics, unless the request sets
`gitExecution.reportQueries`: then each query produces the same `started`, `output`
and `finished` events as a visible command, so the console records what the
workbench read. Their `started` event carries `query: true`; every visible command
normal workflow capture and result semantics, unless `gitExecution.consoleQueries`
records the request's query category: then each query produces the same `started`,
`output` and `finished` events as a visible command, so the console records what the
workbench read. A query category is `references` (background branch reads such as nested
repository references), `reload` (reads after an operation completes), `diffRefresh`
(reloading an open diff after a save), `diff`, `log`, `logPathFilter` (per-commit file
reads that filter the log by path), `annotate`, `panels` (worktree, stash, remote and
similar lists), or `checks` (pre-operation checks). The category is
`gitExecution.queryCategory` when the host names one for reads the command alone does not
tell apart; otherwise Core derives it from the request command: `diff` for `git.diff`,
`git.comparison` and `git.planDiffBlocks`; `log` for history, reference, tag, commit and
graph reads; `annotate` for `git.blame` and `git.lineHistory`; `panels` for worktree,
stash, remote, pull request, untracked directory, repository setup and execution inspection
reads; and `checks` for every other Git command. Commands outside Git have no category, and
neither have the queries of a `background` request that names none. The `queryCategories`
list of the fixture below names every category; `gitExecution` rejects any other name. A
reported query's `started` event carries its `queryCategory`, so a host that stops
recording a category can drop the successful queries of it that it kept; a visible command,
and a query of no category, carries none.
A query whose category the console does not record emits no events while it succeeds, so it
never consumes the console's capacity. If it fails (an error, or a nonzero exit that does not
answer its question) in a request whose provenance is not `background`, Core sends its
`started` event (`query: true`), its stderr lines and its `finished` event together once it
ends, so the console shows the command, diagnostics and exit that failed; its stdout is not
kept, and the request then needs no `failureRecord`. A cancelled query reports nothing, and a
background request's unrecorded queries stay silent even when they fail. See
`rust/fixtures/git/console-queries-v1.json`.
A reported query's `started` event carries `query: true`; every visible command
carries `query: false`. A host passes the flag back as the console record's
`query`, and `git.consolePresentation` then folds a query's whole output into one
`query` output fragment whose `count` labels it, the way IDEA keeps silent
handlers out of sight. A failed query and a query that wrote a single line keep
their output visible. Search still counts and locates every folded line, so a
host opens the fold on a hit. Queries of a request whose provenance is `background` (an
automatic refresh or watcher, which runs too often to record) stay silent even
then; provenance is `gitExecution.source`, or the envelope origin when that is
handlers out of sight. A failed query keeps its output visible, and so does a query
that wrote ten lines or fewer unless `display.foldShortQueries` is set, or a query that
deletes, such as `clean -n`. Search still
counts and locates every folded line, so a host opens the fold on a hit. Queries of a
request whose provenance is `background` (an automatic refresh or watcher, which runs too
often to record) stay silent unless the host names their `queryCategory`;
provenance is `gitExecution.source`, or the envelope origin when that is
unknown. Reported queries never authenticate or prompt; a query that needs
credentials fails as it does when silent. A query whose nonzero exit answers its
question, such as a missing optional config value, an absent ref or a path outside
Expand Down
6 changes: 5 additions & 1 deletion rust/crates/core/src/runtime/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,11 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
Ok(scope) => scope,
Err(error) => return CoreResponse::failure(id, error),
};
let _git_policy = match lithe_git::execution_policy::Scope::begin(parsed.git_execution) {
let _git_policy = match lithe_git::execution_policy::Scope::begin(
parsed
.git_execution
.map(|options| options.for_command(&parsed.command)),
) {
Ok(scope) => scope,
Err(error) => return CoreResponse::failure(id, error),
};
Expand Down
17 changes: 11 additions & 6 deletions rust/crates/core/src/tests/git_workspace_commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ fn reported_queries(root: &Path, command: &str, git_execution: Value) -> Vec<Val
events
}

/// A console that records what the workbench reads asks for it per request; without it,
/// and for an automatic refresh, the same query stays silent, and a reported query still
/// finishes every record it starts.
/// A console that records what the workbench reads names the categories it records per
/// request; without them, for another category and for an automatic refresh, the same query
/// stays silent, and a reported query still finishes every record it starts.
#[test]
fn git_internal_queries_report_events_only_when_the_request_asks() {
let repo = repository("workspace-report-queries");
Expand All @@ -89,12 +89,17 @@ fn git_internal_queries_report_events_only_when_the_request_asks() {
reported_queries(&repo.0, command, json!({})),
Vec::<Value>::new()
);
let refresh = json!({"reportQueries": true, "source": "background"});
let other = json!({"consoleQueries": ["log"], "source": "user"});
assert_eq!(
reported_queries(&repo.0, command, other),
Vec::<Value>::new()
);
let refresh = json!({"consoleQueries": ["checks"], "source": "background"});
assert_eq!(
reported_queries(&repo.0, command, refresh),
Vec::<Value>::new()
);
let user = json!({"reportQueries": true, "source": "user"});
let user = json!({"consoleQueries": ["checks"], "source": "user"});
let events = reported_queries(&repo.0, command, user);
let started: Vec<_> = events.iter().filter(|e| e["type"] == "started").collect();
let finished: Vec<_> = events.iter().filter(|e| e["type"] == "finished").collect();
Expand All @@ -115,7 +120,7 @@ fn git_reported_status_shows_each_record_on_its_own_line() {
fs::write(repo.0.join("first.txt"), "first").unwrap();
fs::write(repo.0.join("second.txt"), "second").unwrap();

let events = reported_queries(&repo.0, "git.status", json!({"reportQueries": true}));
let events = reported_queries(&repo.0, "git.status", json!({"consoleQueries": ["checks"]}));
let status = events
.iter()
.find(|e| {
Expand Down
37 changes: 37 additions & 0 deletions rust/crates/git/src/console/category.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! The console category of each Git request command's internal queries.
use super::types::QueryCategory;

/// The category a request command's internal queries read, or `None` outside Git. Commands
/// that only show what Git has go by what they show; previews, preflights, plans and the
/// operations themselves are checks, so a command not listed here counts as one.
pub fn of_command(command: &str) -> Option<QueryCategory> {
use QueryCategory::*;
let category = match command {
"git.diff" | "git.comparison" | "git.planDiffBlocks" => Diff,
"git.history"
| "git.historyQuery"
| "git.historyPage"
| "git.historyWindow"
| "git.historyLocate"
| "git.historyActionCapabilities"
| "git.references"
| "git.referenceTree"
| "git.graphProjection"
| "git.tags"
| "git.commit"
| "git.commitFiles"
| "git.changedFileGroups" => Log,
"git.blame" | "git.lineHistory" => Annotate,
"git.worktrees"
| "git.stashes"
| "git.remotes"
| "git.remoteUrl"
| "git.pullRequestContext"
| "git.untrackedDirectory"
| "git.repositorySetup"
| "git.executionInspect" => Panels,
command if command.starts_with("git.") => Checks,
_ => return None,
};
Some(category)
}
18 changes: 13 additions & 5 deletions rust/crates/git/src/console/command.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Conservative command compression: behavior-changing flags always remain visible.
use super::types::{CommandFragment, Record};
use super::types::{CommandFragment, Display, Record};
use crate::execution_policy::command_index;

pub(super) fn quote(value: &str) -> String {
Expand All @@ -22,13 +22,21 @@ fn join(values: &[String]) -> String {
}
/// Fold contiguous Git configuration arguments in place, as IDEA's console does.
/// Token boundaries preserve quoted values and avoid folding behavior flags or paths.
pub(super) fn project(record: &Record) -> Vec<CommandFragment> {
/// Hidden temporary configuration is left out; the arguments themselves always stay.
/// A command that `deletes` keeps its configuration open, so nothing of it hides.
pub(super) fn project(record: &Record, display: &Display, deletes: bool) -> Vec<CommandFragment> {
let mut args = Vec::new();
for (key, value) in &record.temporary_config {
args.extend(["-c".into(), format!("{key}={value}")]);
if !display.hide_temporary_config {
for (key, value) in &record.temporary_config {
args.extend(["-c".into(), format!("{key}={value}")]);
}
}
args.extend_from_slice(&record.arguments);
let command = command_index(&args).unwrap_or(0);
let command = if deletes {
0
} else {
command_index(&args).unwrap_or(0)
};
let mut result = Vec::new();
let mut index = 0;
while index < args.len() {
Expand Down
71 changes: 71 additions & 0 deletions rust/crates/git/src/console/deletion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//! Commands that delete something stay unfolded, so the console shows all a deletion did.
use crate::execution_policy::command_index;

/// Whether `arguments` delete branches, tags, references, remote branches, configuration,
/// files, stashes or worktrees, or list what a clean would delete. The console folds none
/// of such a command's configuration or output. Global options before the subcommand are
/// skipped, and only options before `--` count, so a path named like an option is a path.
pub(super) fn deletes(arguments: &[String]) -> bool {
let Some(index) = command_index(arguments) else {
return false;
};
let rest = &arguments[index + 1..];
let has = |names: &[&str]| {
rest.iter()
.take_while(|argument| argument.as_str() != "--")
.any(|argument| names.contains(&argument.as_str()))
};
let action = rest
.iter()
.find(|argument| !argument.starts_with('-'))
.map(String::as_str);
match arguments[index].as_str() {
// A dry-run clean lists what a clean deletes, so it is shown whole as well.
"rm" | "clean" => true,
"branch" | "tag" | "update-ref" | "symbolic-ref" => has(&["-d", "-D", "--delete"]),
// A refspec without a source, `:refs/heads/topic`, deletes the remote branch.
"push" => {
has(&["-d", "--delete", "--prune"])
|| rest
.iter()
.any(|argument| argument.starts_with(':') && argument.len() > 1)
}
"fetch" | "pull" => has(&["-p", "--prune", "-P", "--prune-tags"]),
"remote" => {
matches!(action, Some("remove" | "rm" | "prune"))
|| (action == Some("update") && has(&["-p", "--prune"]))
}
"config" => {
has(&["--unset", "--unset-all", "--remove-section"])
|| matches!(action, Some("unset" | "remove-section"))
}
// `pop` drops the entry it applied.
"stash" => matches!(action, Some("drop" | "clear" | "pop")),
"worktree" => matches!(action, Some("remove" | "prune")),
_ => false,
}
}

#[cfg(test)]
mod tests {
use super::deletes;
use serde_json::Value;

#[test]
fn deletions_match_the_shared_console_cases() {
let fixture: Value = serde_json::from_str(include_str!(
"../../../../fixtures/git/console-presentation-v1.json"
))
.unwrap();
let cases = fixture["deletions"].as_array().unwrap();
assert!(!cases.is_empty());
for case in cases {
let arguments: Vec<String> = serde_json::from_value(case["arguments"].clone()).unwrap();
assert_eq!(
deletes(&arguments),
case["deletes"].as_bool().unwrap(),
"{arguments:?}"
);
}
}
}
Loading
Loading