Skip to content

Commit d13c51f

Browse files
mtorpclaudemikolalysenko
authored
Report which hosted patch pins changed (#2307)
* Report which hosted patch pins changed Compare local pin records before and after the hosted rewrite so JSON consumers can tell which patch changed in a shared lockfile. Report an unknown result when the available records cannot establish the change. Assisted-by: Codex:GPT-6 * Preserve the hosted discovery API Keep the two variants of FinalDiscovery so existing Rust callers can still match on both. Give the CLI a separate way to read pins found on servers named by a grant. Keep the public discovery field empty when the grant adds a server. Assisted-by: Codex:GPT-6 * Simplify the hosted pin change report Reuse the existing check for whether the pin check's discovery matches the written disk, which also skips the report after a vlt store heal. Set pinChanged where the confirmed events are built, check that scan's discovery is still current once per run, and skip collecting created paths when no report will read them. Assisted-by: Claude Code:claude-opus-5-5 * Count shadowed pins and re-read the project for pinChanged The three JSON envelope tests that compare events exactly now expect `details.pinChanged: true` on the pin they write. A confirmed pin withheld from `refs` because an unpatched copy sits beside it is in `Discovery::shadowed`; count it so its change is reported instead of `null`. When a wet run's writes landed but the gate's overlay cannot stand for the project, discover it again with the same origins as the before snapshot. A dry run still reports `null` in that case, as CLI_CONTRACT.md describes. Assisted-by: Claude Code:claude-opus-5-5 --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Mikola Lysenko <mikolalysenko@gmail.com>
1 parent 6094f71 commit d13c51f

9 files changed

Lines changed: 252 additions & 37 deletions

File tree

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3111,11 +3111,13 @@ socket-patch scan --mode agent --json | jq '
31113111
'
31123112
```
31133113

3114-
Hosted pins a run wrote (dry run: `verified`), and why the rest were skipped:
3114+
Hosted `scan` and `get` report `details.pinChanged` on each confirmed pin. A wet run reports an `applied` event. A dry run reports the planned result on a `verified` event. The value is `true` when the local dependency files show a new or updated hosted reference for this package and patch UUID. It is `false` when the recorded references stayed the same or the run rewrote nothing. Changes to a sibling package in the same lockfile do not count. A `null` value means the CLI could not determine the change, for example when it could not attribute the final reference to a package version. Older releases omit the field.
3115+
3116+
To list confirmed pins and the changes the CLI could attribute:
31153117

31163118
```bash
31173119
socket-patch scan --mode hosted --json | jq '
3118-
{ pinned: [.events[] | select(.details.mode == "hosted" and .action == "applied") | .purl],
3120+
{ pinned: [.events[] | select(.details.mode == "hosted" and (.action == "applied" or .action == "verified")) | {purl, uuid, changed: .details.pinChanged}],
31193121
skipped: [.events[] | select(.action == "skipped") | {purl, code: .errorCode}],
31203122
files: .redirect.rewrittenFiles }
31213123
'

‎crates/socket-patch-cli/src/commands/scan/hosted.rs‎

Lines changed: 64 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ use socket_patch_core::formats::gem::GemBuild;
2424
use super::{discover_selected, emit_scan, scan_envelope, ScanArgs};
2525

2626
mod nuget;
27+
mod pin_changes;
2728
mod python;
2829
mod takeover;
2930

@@ -361,8 +362,9 @@ pub(super) fn record_hosted_events(
361362
unconfirmed: &[(String, String)],
362363
skipped: &[socket_patch_core::hosted::engine::SkippedPatch],
363364
dry_run: bool,
365+
changes: &pin_changes::PinChanges<'_>,
364366
) {
365-
for event in hosted_events(confirmed, unconfirmed, skipped, dry_run) {
367+
for event in hosted_events(confirmed, unconfirmed, skipped, dry_run, Some(changes)) {
366368
env.record(event);
367369
}
368370
}
@@ -375,6 +377,7 @@ fn hosted_events(
375377
unconfirmed: &[(String, String)],
376378
skipped: &[socket_patch_core::hosted::engine::SkippedPatch],
377379
dry_run: bool,
380+
changes: Option<&pin_changes::PinChanges<'_>>,
378381
) -> Vec<PatchEvent> {
379382
let pinned = if dry_run {
380383
PatchAction::Verified
@@ -383,7 +386,15 @@ fn hosted_events(
383386
};
384387
let mut events: Vec<PatchEvent> = confirmed
385388
.iter()
386-
.map(|(purl, uuid)| PatchEvent::new(pinned, purl.as_str()).with_uuid(uuid.as_str()))
389+
.map(|(purl, uuid)| {
390+
let event = PatchEvent::new(pinned, purl.as_str()).with_uuid(uuid.as_str());
391+
match changes {
392+
Some(changes) => event.with_details(serde_json::json!({
393+
"pinChanged": changes.get(&(purl.as_str(), uuid.as_str())),
394+
})),
395+
None => event,
396+
}
397+
})
387398
.chain(skipped.iter().map(|s| {
388399
let mut event =
389400
PatchEvent::new(PatchAction::Skipped, s.purl.as_str()).with_uuid(s.uuid.as_str());
@@ -1285,7 +1296,6 @@ fn discovery_after_writes<'d>(
12851296
discovery,
12861297
view_only,
12871298
}) => (Some(&**discovery), *view_only),
1288-
// The gate read `prior` itself (see `engine::rewrite`).
12891299
Some(FinalDiscovery::Prior) | None => (None, false),
12901300
};
12911301
let candidate = match written {
@@ -1719,6 +1729,16 @@ async fn run_redirect_selected_untracked(
17191729
// both consumers.
17201730
let mut vendor_state = socket_patch_core::vendor::load_state(&common.cwd).await;
17211731

1732+
let current_prior = rollout
1733+
.as_ref()
1734+
.and_then(|gate| gate.prior)
1735+
.and_then(|prior| prior.still_current());
1736+
let before_pins = if common.json && !candidates.is_empty() {
1737+
Some(pin_changes::before_rewrite(common, &candidates, current_prior).await)
1738+
} else {
1739+
None
1740+
};
1741+
17221742
// Every project write of this run — a takeover's vendored reverts, the
17231743
// hosted pins and the vendored ledger — is staged in one group commit
17241744
// and reaches the disk at once, after every check has passed (see
@@ -2034,11 +2054,7 @@ async fn run_redirect_selected_untracked(
20342054
// (a concurrent writer that finished before the lock was taken shows up
20352055
// here). It was made with `patch_server_origins`
20362056
// (`discover_wiring`).
2037-
let prior_discovery = rollout
2038-
.as_ref()
2039-
.and_then(|gate| gate.prior)
2040-
.filter(|_| !takeover.is_staged())
2041-
.and_then(|prior| prior.still_current());
2057+
let prior_discovery = current_prior.filter(|_| !takeover.is_staged());
20422058
// The cargo configs cargo reads for a build here (the project's, every
20432059
// parent directory's and `$CARGO_HOME`'s): a directory source or local
20442060
// registry in any of them refuses the cargo rewrite like a project one.
@@ -2239,7 +2255,7 @@ async fn run_redirect_selected_untracked(
22392255
// files the overlay creates or removes (see `discovery_after_writes`).
22402256
// Taken before the commit, while the disk is still as discovery saw it.
22412257
let mut created_paths: Vec<String> = Vec::new();
2242-
if !common.dry_run {
2258+
if !common.dry_run || before_pins.is_some() {
22432259
let on_disk = |rel: &str| {
22442260
let path = common.cwd.join(rel);
22452261
async move {
@@ -2671,7 +2687,7 @@ async fn run_redirect_selected_untracked(
26712687
done.rewritten.len(),
26722688
common.dry_run,
26732689
&crate::telemetry_outcomes::patch_outcomes_of(
2674-
&hosted_events(&confirmed, &unconfirmed, &skipped, common.dry_run),
2690+
&hosted_events(&confirmed, &unconfirmed, &skipped, common.dry_run, None),
26752691
socket_patch_core::telemetry::MODE_HOSTED,
26762692
),
26772693
&telemetry.auth,
@@ -2685,7 +2701,37 @@ async fn run_redirect_selected_untracked(
26852701
// tagged `details.mode: "hosted"`, the `redirect` payload, and the
26862702
// engine's warnings hoisted to the top-level `warnings`.
26872703
let mut env = scan_result.take().unwrap_or_else(|| scan_envelope(common));
2688-
record_hosted_events(&mut env, &confirmed, &unconfirmed, &skipped, common.dry_run);
2704+
let changes = if done.rewritten.is_empty() && takeover_files.is_empty() {
2705+
pin_changes::unchanged(&confirmed)
2706+
} else {
2707+
let created: Vec<&str> = created_paths.iter().map(String::as_str).collect();
2708+
let after = discovery_after_writes(
2709+
None,
2710+
done.pin_discovery(),
2711+
Written::Landed { created: &created },
2712+
vlt_stale.healed_store.as_ref(),
2713+
);
2714+
// A wet run's writes have landed: when the gate's overlay cannot
2715+
// stand for the project, read it again. A dry run has no disk to
2716+
// read and reports `null`.
2717+
let fresh;
2718+
let after = match after {
2719+
None if !common.dry_run && before_pins.is_some() => {
2720+
fresh = pin_changes::discover_now(common, &candidates).await;
2721+
Some(&fresh)
2722+
}
2723+
after => after,
2724+
};
2725+
pin_changes::compare(before_pins.as_deref(), after, &confirmed)
2726+
};
2727+
record_hosted_events(
2728+
&mut env,
2729+
&confirmed,
2730+
&unconfirmed,
2731+
&skipped,
2732+
common.dry_run,
2733+
&changes,
2734+
);
26892735
record_registry_cleanup(
26902736
&mut env,
26912737
&registry_removed,
@@ -4348,6 +4394,7 @@ mod tests {
43484394
&[("pkg:npm/a@1.0.0".to_string(), "ua".to_string())],
43494395
&skipped,
43504396
false,
4397+
&Default::default(),
43514398
);
43524399
env.set_extra("redirect", redirect_block(vec!["package-lock.json".into()]));
43534400
env.warnings.push(prune_ignored_warning());
@@ -4376,6 +4423,11 @@ mod tests {
43764423
("applied", "pkg:npm/minimist@1.2.2", None),
43774424
]
43784425
);
4426+
assert_eq!(
4427+
v["events"][2]["details"].get("pinChanged"),
4428+
Some(&serde_json::Value::Null)
4429+
);
4430+
assert!(v["events"][0]["details"].get("pinChanged").is_none());
43794431
assert_eq!(v["summary"]["applied"], 1);
43804432
assert_eq!(v["summary"]["skipped"], 2);
43814433
assert_eq!(
@@ -4392,6 +4444,7 @@ mod tests {
43924444
&[],
43934445
&[],
43944446
true,
4447+
&Default::default(),
43954448
);
43964449
assert_eq!(env.summary.verified, 1);
43974450
assert_eq!(env.summary.applied, 0);
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
use std::borrow::Cow;
2+
use std::collections::HashMap;
3+
4+
use socket_patch_core::hosted::engine::Candidate;
5+
use socket_patch_core::patch::redirect::upstream::foreign_dep_origins;
6+
use socket_patch_core::utils::purl_key::PurlKey;
7+
use socket_patch_core::vex::discover::{
8+
discover_patched_refs_with, Discovery, PatchedRef, WiringMode, DIAG_LOCKFILE_UNPARSEABLE,
9+
DIAG_LOCKFILE_UNREADABLE,
10+
};
11+
use socket_patch_core::vex::DiscoverOptions;
12+
13+
use crate::args::GlobalArgs;
14+
15+
/// `details.pinChanged` per confirmed `(purl, uuid)`. A missing key reports `null`.
16+
pub(super) type PinChanges<'a> = HashMap<(&'a str, &'a str), bool>;
17+
18+
/// `prior` is scan's discovery, already checked to still describe the disk.
19+
pub(super) async fn before_rewrite<'a>(
20+
common: &GlobalArgs,
21+
candidates: &[Candidate],
22+
prior: Option<&'a Discovery>,
23+
) -> Cow<'a, Discovery> {
24+
let configured = crate::commands::hosted_unwind::patch_server_origins(common);
25+
let foreign = foreign_dep_origins(candidates.iter().map(|c| &c.dep), &configured);
26+
if foreign.is_empty() {
27+
return match prior {
28+
Some(discovery) => Cow::Borrowed(discovery),
29+
None => Cow::Owned(crate::commands::discover_wiring(common, &common.cwd).await),
30+
};
31+
}
32+
let opts = DiscoverOptions {
33+
patch_server_origins: configured.into_iter().chain(foreign).collect(),
34+
};
35+
Cow::Owned(discover_patched_refs_with(&common.cwd, &opts).await)
36+
}
37+
38+
/// The project as it is now, discovered with the same origins as [`before_rewrite`].
39+
pub(super) async fn discover_now(common: &GlobalArgs, candidates: &[Candidate]) -> Discovery {
40+
before_rewrite(common, candidates, None).await.into_owned()
41+
}
42+
43+
pub(super) fn unchanged(confirmed: &[(String, String)]) -> PinChanges<'_> {
44+
confirmed
45+
.iter()
46+
.map(|(purl, uuid)| ((purl.as_str(), uuid.as_str()), false))
47+
.collect()
48+
}
49+
50+
fn refs_by_patch(discovery: &Discovery) -> HashMap<(PurlKey, &str), Vec<&PatchedRef>> {
51+
let mut pins: HashMap<_, Vec<_>> = HashMap::new();
52+
// A shadowed pin is still confirmed and managed (see `Discovery::shadowed`).
53+
for pin in discovery
54+
.refs
55+
.iter()
56+
.chain(&discovery.shadowed)
57+
.filter(|pin| pin.mode == WiringMode::Hosted)
58+
{
59+
pins.entry((PurlKey::new(&pin.purl), pin.uuid.as_str()))
60+
.or_default()
61+
.push(pin);
62+
}
63+
pins
64+
}
65+
66+
/// `after` is the project as this run left it (see `discovery_after_writes`).
67+
pub(super) fn compare<'a>(
68+
before: Option<&Discovery>,
69+
after: Option<&Discovery>,
70+
confirmed: &'a [(String, String)],
71+
) -> PinChanges<'a> {
72+
let (Some(before), Some(after)) = (before, after) else {
73+
return HashMap::new();
74+
};
75+
if [before, after].iter().any(|d| {
76+
d.diagnostics.iter().any(|diag| {
77+
matches!(
78+
diag.code,
79+
DIAG_LOCKFILE_UNPARSEABLE | DIAG_LOCKFILE_UNREADABLE
80+
)
81+
})
82+
}) {
83+
return HashMap::new();
84+
}
85+
let old_refs = refs_by_patch(before);
86+
let new_refs = refs_by_patch(after);
87+
confirmed
88+
.iter()
89+
.filter_map(|(purl, uuid)| {
90+
let key = (PurlKey::new(purl), uuid.as_str());
91+
let new = new_refs.get(&key)?;
92+
let old = old_refs.get(&key);
93+
if old.is_none() && before.recognizes(uuid, WiringMode::Hosted) {
94+
return None;
95+
}
96+
Some(((purl.as_str(), uuid.as_str()), old != Some(new)))
97+
})
98+
.collect()
99+
}

‎crates/socket-patch-cli/tests/common/envelope.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,20 @@ pub fn hosted_pins(envelope: &Value) -> Vec<(String, String)> {
177177
.collect()
178178
}
179179

180+
/// `(uuid, details.pinChanged)` of each [`hosted_pins`] event.
181+
pub fn hosted_pin_changes(envelope: &Value) -> Vec<(String, Option<bool>)> {
182+
mode_events(envelope, "hosted")
183+
.into_iter()
184+
.filter(|e| e["action"] == "applied" || e["action"] == "verified")
185+
.map(|e| {
186+
(
187+
e["uuid"].as_str().unwrap_or_default().to_string(),
188+
e["details"]["pinChanged"].as_bool(),
189+
)
190+
})
191+
.collect()
192+
}
193+
180194
/// The `{purl, uuid, reason, detail}` rows of the hosted `skipped` events
181195
/// (v5.0's `redirect.skipped[]`: `reason` is the event's `errorCode`).
182196
pub fn hosted_skips(envelope: &Value) -> Vec<(String, String)> {

‎crates/socket-patch-cli/tests/get/get_modes_e2e.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,10 @@ async fn get_uuid_hosted_json_envelope_nests_redirect() {
256256
assert_eq!(
257257
v["events"],
258258
serde_json::json!([
259-
{ "action": "applied", "purl": PURL1, "uuid": UUID1, "details": { "mode": "hosted" } }
259+
{
260+
"action": "applied", "purl": PURL1, "uuid": UUID1,
261+
"details": { "mode": "hosted", "pinChanged": true }
262+
}
260263
]),
261264
"{v:#}"
262265
);
@@ -599,7 +602,10 @@ async fn get_hosted_dry_run_json_envelope() {
599602
assert_eq!(
600603
v["events"],
601604
serde_json::json!([
602-
{ "action": "verified", "purl": PURL1, "uuid": UUID1, "details": { "mode": "hosted" } }
605+
{
606+
"action": "verified", "purl": PURL1, "uuid": UUID1,
607+
"details": { "mode": "hosted", "pinChanged": true }
608+
}
603609
]),
604610
"{v:#}"
605611
);

‎crates/socket-patch-cli/tests/in_process_redirect.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7163,7 +7163,8 @@ async fn hosted_json_reports_a_pinned_row_per_patch() {
71637163
assert_eq!(
71647164
env["events"],
71657165
serde_json::json!([{
7166-
"action": "applied", "purl": PURL, "uuid": UUID, "details": {"mode": "hosted"},
7166+
"action": "applied", "purl": PURL, "uuid": UUID,
7167+
"details": {"mode": "hosted", "pinChanged": true},
71677168
}]),
71687169
"{env:#}"
71697170
);

‎crates/socket-patch-cli/tests/scan/hosted_render.rs‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -654,7 +654,7 @@ async fn human_names_the_fixed_advisory_and_the_ones_left_unpatched() {
654654
/// earlier run already switched, counts one package as switched and says
655655
/// the other was already there. Before, it said "Switched 2 packages".
656656
#[tokio::test]
657-
async fn human_summary_counts_only_the_packages_this_run_switched() {
657+
async fn hosted_reports_only_the_packages_this_run_switched() {
658658
const SECOND: &str = "covgap-second";
659659
const SECOND_PURL: &str = "pkg:npm/covgap-second@1.0.0";
660660
const SECOND_UUID: &str = "55555555-5555-4555-8555-555555555555";
@@ -773,6 +773,23 @@ async fn human_summary_counts_only_the_packages_this_run_switched() {
773773
// The fixture's patch server is not Socket's: name it, so its pins are
774774
// recognised as hosted, as Socket's own are by default.
775775
const SERVER: [&str; 2] = ["--patch-server-url", "https://patch.test"];
776+
let lock = root.join("package-lock.json");
777+
let mixed_lock = std::fs::read(&lock).unwrap();
778+
let assert_changes = |args: &[&str], second_changed: bool| {
779+
let (code, doc) = scan_hosted_json(root, &second.uri(), args, &[]);
780+
assert_eq!(code, 0, "{doc:#}");
781+
assert_eq!(
782+
crate::common::envelope::hosted_pin_changes(&doc),
783+
[
784+
(UUID.to_string(), Some(false)),
785+
(SECOND_UUID.to_string(), Some(second_changed))
786+
],
787+
"{doc:#}"
788+
);
789+
};
790+
assert_changes(&[SERVER[0], SERVER[1], "--dry-run"], true);
791+
assert_eq!(std::fs::read(&lock).unwrap(), mixed_lock);
792+
776793
let (code, stdout, stderr) = scan_hosted(
777794
root,
778795
&second.uri(),
@@ -811,6 +828,14 @@ async fn human_summary_counts_only_the_packages_this_run_switched() {
811828
HIGH covgap-second@1.0.0\n",
812829
"stderr=\n{stderr}"
813830
);
831+
assert_changes(&SERVER, false);
832+
std::fs::write(&lock, mixed_lock).unwrap();
833+
assert_changes(&[], true);
834+
835+
let mut repaired: Value = serde_json::from_slice(&std::fs::read(&lock).unwrap()).unwrap();
836+
repaired["packages"][format!("node_modules/{SECOND}")]["integrity"] = json!(UPSTREAM_SHA512);
837+
std::fs::write(&lock, serde_json::to_vec(&repaired).unwrap()).unwrap();
838+
assert_changes(&SERVER, true);
814839
}
815840

816841
/// A granted patch whose package has no lock entry is listed by purl on

0 commit comments

Comments
 (0)