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
3 changes: 3 additions & 0 deletions .ripr/traceability.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13748,6 +13748,9 @@ tests = [
"xtask/src/work_portfolio.rs::tests::work_portfolio_bounded_wave_retrievable_without_reading_every_body",
"xtask/src/work_portfolio.rs::tests::work_portfolio_blocked_complete_or_low_ranked_campaign_never_hides_eligible_work",
"xtask/src/work_portfolio.rs::tests::work_portfolio_ranking_is_explicit_ordered_factors_without_hidden_score",
"xtask/src/work_portfolio.rs::tests::work_portfolio_serialized_ranking_key_reproduces_order",
"xtask/src/work_portfolio.rs::tests::work_portfolio_ranking_key_preserves_legacy_and_rejects_malformed_rows",
"xtask/src/work_portfolio.rs::tests::work_portfolio_ranking_key_preserves_first_issue_risk_lookup",
"xtask/src/work_portfolio.rs::tests::work_portfolio_explain_view_matches_snapshot_and_fails_closed",
"xtask/src/work_portfolio.rs::tests::work_portfolio_markdown_derives_from_same_dto_without_strengthening",
"xtask/src/work_portfolio.rs::tests::work_portfolio_markdown_renders_lists_as_plain_markdown_not_debug",
Expand Down
4 changes: 4 additions & 0 deletions changelog.d/7431-work-ranking-key.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<!-- section: Fixed -->
- Work portfolio JSON exposes the eight-integer key used to rank candidates;
Markdown names the key and candidate ID tie-break so consumers can reproduce
the order while retaining the existing factor explanations (#7431).
13 changes: 13 additions & 0 deletions docs/OUTPUT_SCHEMA.md
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,19 @@ object in `crates/ripr/src/domain/intervention_study.rs` owns study identity
projects JSON and Markdown. The protocol does not execute agents, grade
repairs, or claim intervention value.

## Work portfolio ranking keys

The read-only `cargo xtask work portfolio`, `work candidates`, and
`work explain` v1 JSON documents carry an additive candidate `ranking_key`
array of exactly eight integers, in the factor order declared by
[RIPR-SPEC-0234](specs/RIPR-SPEC-0234-work-portfolio-compiler.md).
Candidates sort by this key ascending lexicographically, then by
`candidate_id` ascending. The existing `ranking_factors` retain their prose
and source references. Legacy rows can omit the key; omission or null means
unavailable, not zero. Regenerated portfolio identities include the key.
Markdown displays the same key and tie-break; this advisory ordering does
not select work or grant authority.

## JSON object key ordering

JSON object key order is not part of the semantic contract for ordinary
Expand Down
13 changes: 12 additions & 1 deletion docs/specs/RIPR-SPEC-0234-work-portfolio-compiler.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ relationship; dependencies and blockers; semantic conflict resources and
overlapping work; proof/review/CI cost classes (`not_proven` when
unsourced); lane/capacity state; explicitly sourced readiness contribution
and regression risks; the ordered ranking factors with per-factor
contributions and source references; confidence with named partial-data
contributions and source references and their exact eight-integer
`ranking_key`; confidence with named partial-data
reasons; and the recommended packet compiler entrypoint
(`cargo xtask work explain --candidate <id>`). The portfolio preserves the
complete candidate set; ranking is advisory and inspectable.
Expand Down Expand Up @@ -149,6 +150,16 @@ active claim; a merged PR alone is finished work (`verify_current_head` /
when sourced from explicit accepted artifacts, marked advisory, and never
changes the factor order.

The compiler emits `ranking_key` in the existing v1 portfolio, candidates,
and explain JSON, alongside the unchanged factor prose. It computes the key
once and sorts by that same value in ascending lexicographic order; equal
keys sort by `candidate_id` ascending. Markdown names the key and tie-break.
Legacy candidate JSON without the additive field still deserializes and
round-trips without it; absence means unavailable, never an invented zero
key. A present non-null key must contain exactly eight integers. Adding the
field changes regenerated portable identity digests, whose candidate DTO
inputs now include the key, without changing candidate order or authority.

### Determinism, budgets and portability

Fixed captured inputs produce byte-stable normalized JSON independent of
Expand Down
163 changes: 156 additions & 7 deletions xtask/src/work_portfolio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
//! Ranking law: candidates order by the eight explicit factors from #1704 in
//! exactly that order, each factor inspectable on the candidate with its
//! contribution and source references; the sort is a lexicographic
//! application of the declared factor sequence and no hidden numeric score
//! exists anywhere in the DTOs.
//! application of the declared factor sequence. The emitted ranking key is
//! that sequence, not a weighted score; ties use the stable candidate id.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
Expand Down Expand Up @@ -849,6 +849,10 @@ pub(crate) struct WorkCandidateV1 {
pub readiness: Option<WorkReadinessV1>,
pub regression_risks: Vec<String>,
pub ranking_factors: Vec<WorkRankingFactorV1>,
/// Exact ascending lexicographic sort key. Legacy rows omit this rather
/// than inventing values that cannot be recovered from factor prose.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ranking_key: Option<[i64; 8]>,
pub confidence: WorkConfidenceV1,
pub confidence_reasons: Vec<String>,
pub single_agent_preferred: bool,
Expand Down Expand Up @@ -1360,8 +1364,8 @@ fn lane_rank(lane_state: WorkLaneStateV1) -> i64 {
}

/// The lexicographic ranking tuple: one entry per declared factor, in the
/// #1704 order. Smaller is earlier. Never serialized — the factors on the
/// candidate are the inspectable record of exactly these entries.
/// #1704 order. Smaller is earlier. Computed once for sorting and serialization;
/// the factors retain their human explanation of these entries.
fn ranking_tuple(
candidate: &WorkCandidateV1,
honesty_risk: Option<&str>,
Expand Down Expand Up @@ -2459,6 +2463,7 @@ pub(crate) fn compile_work_portfolio(
readiness: readiness_for(issue),
regression_risks,
ranking_factors: Vec::new(),
ranking_key: None,
confidence,
confidence_reasons: confidence_reasons
.iter()
Expand Down Expand Up @@ -2494,9 +2499,12 @@ pub(crate) fn compile_work_portfolio(
.any(|pr| pr.state == "open" && pr.linked_issues.contains(&candidate.issue));
ranking_tuple(candidate, risk, has_open_pr)
};
for candidate in &mut candidates {
candidate.ranking_key = Some(rank_key(candidate));
}
candidates.sort_by(|left, right| {
rank_key(left)
.cmp(&rank_key(right))
left.ranking_key
.cmp(&right.ranking_key)
.then_with(|| left.candidate_id.cmp(&right.candidate_id))
});

Expand Down Expand Up @@ -3065,15 +3073,17 @@ pub(crate) fn work_portfolio_markdown(snapshot: &WorkPortfolioSnapshotV1) -> Str
body.push('\n');

body.push_str("## Candidates (ranked, advisory)\n\n");
body.push_str("Ranking keys use ascending lexicographic; ties by `candidate_id`.\n\n");
body.push_str(&md_table_row(&[
"rank".to_string(),
"candidate".to_string(),
"kind".to_string(),
"stage".to_string(),
"lane".to_string(),
"confidence".to_string(),
"ranking key".to_string(),
]));
body.push_str("\n| --- | --- | --- | --- | --- | --- |\n");
body.push_str("\n| --- | --- | --- | --- | --- | --- | --- |\n");
for (rank, candidate) in snapshot.candidates.iter().enumerate() {
body.push_str(&md_table_row(&[
(rank + 1).to_string(),
Expand All @@ -3082,6 +3092,10 @@ pub(crate) fn work_portfolio_markdown(snapshot: &WorkPortfolioSnapshotV1) -> Str
wire_label(&candidate.lifecycle_stage),
candidate.lane.clone(),
wire_label(&candidate.confidence),
candidate
.ranking_key
.map(|key| format!("`{key:?}`"))
.unwrap_or_else(|| "unavailable (legacy artifact)".to_string()),
]));
body.push('\n');
}
Expand Down Expand Up @@ -3184,6 +3198,13 @@ fn candidate_markdown(candidate: &WorkCandidateV1, heading: &str) -> String {
&candidate.regression_risks,
));
}
if let Some(key) = candidate.ranking_key {
body.push_str(&format!(
"- ranking key: `{key:?}` (ascending lexicographic; ties by `candidate_id`)\n"
));
} else {
body.push_str("- ranking key: unavailable (legacy artifact)\n");
}
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
body.push_str("- ranking factors (ordered, no hidden score):\n");
for factor in &candidate.ranking_factors {
body.push_str(&format!(
Expand Down Expand Up @@ -3836,6 +3857,134 @@ mod tests {
})
}

#[test]
fn work_portfolio_serialized_ranking_key_reproduces_order() -> Result<(), String> {
let snapshot = committed()?;
let json: Value = serde_json::from_str(&work_portfolio_json(&snapshot)?)
.map_err(|error| error.to_string())?;
let rows = json["candidates"]
.as_array()
.ok_or("candidate array missing")?;
assert_eq!(rows.len(), 12);
let mut ranked = Vec::new();
for row in rows {
let key: [i64; 8] = serde_json::from_value(row["ranking_key"].clone())
.map_err(|error| format!("{} ranking key: {error}", row["candidate_id"]))?;
let id = row["candidate_id"].as_str().ok_or("candidate id missing")?;
ranked.push((key, id.to_string()));
}
let expected = ranked.clone();
// Start in the opposite order so equal-key rows exercise the id tie-break.
ranked.reverse();
ranked.sort();
assert_eq!(ranked, expected);
assert_eq!(expected[0].0, [0, 0, 0, 0, 0, 2, 1, 0]);
assert_eq!(expected[11].0, [1, 1, 1, 3, 2, 2, 3, 0]);
assert_eq!(expected[6].0, [1, 1, 0, 1, 0, 2, 0, 0]);
assert_eq!(expected[3].0, [0, 1, 0, 2, 1, 2, 0, 1]);
assert_eq!(expected[6].0, expected[7].0);
assert_eq!(expected[6].1, "candidate:issue:9105");
assert_eq!(expected[7].1, "candidate:issue:9106");
let view = build_candidates_view(&snapshot, None, None, 12, None)?;
let view_json: Value = serde_json::from_str(&work_portfolio_json(&view)?)
.map_err(|error| error.to_string())?;
assert_eq!(view_json["candidates"], json["candidates"]);
let explain = build_explain_view(&snapshot, &expected[0].1)?;
let explain_json: Value = serde_json::from_str(&work_portfolio_json(&explain)?)
.map_err(|error| error.to_string())?;
assert_eq!(explain_json["candidate"], rows[0]);
let portfolio_md = work_portfolio_markdown(&snapshot);
assert!(portfolio_md.contains("| ranking key |"));
assert!(portfolio_md.contains("ascending lexicographic; ties by `candidate_id`"));
for (key, id) in &expected {
let row = portfolio_md
.lines()
.find(|line| line.contains(id))
.ok_or("portfolio Markdown candidate row missing")?;
assert!(row.contains(&format!("| `{key:?}` |")));
}
for markdown in [
work_candidates_markdown(&view),
work_explain_markdown(&explain),
] {
assert!(markdown.contains("ranking key: `[0, 0, 0, 0, 0, 2, 1, 0]`"));
assert!(markdown.contains("ascending lexicographic; ties by `candidate_id`"));
}
Ok(())
}

#[test]
fn work_portfolio_ranking_key_preserves_legacy_and_rejects_malformed_rows() -> Result<(), String>
{
let snapshot = committed()?;
let mut row =
serde_json::to_value(candidate(&snapshot, 9101)?).map_err(|error| error.to_string())?;
let object = row.as_object_mut().ok_or("candidate object missing")?;
object.remove("ranking_key");
let legacy: WorkCandidateV1 =
serde_json::from_value(row.clone()).map_err(|error| error.to_string())?;
assert_eq!(legacy.ranking_key, None);
let roundtrip = serde_json::to_value(&legacy).map_err(|error| error.to_string())?;
assert_eq!(roundtrip, row);
let mut legacy_snapshot = snapshot.clone();
legacy_snapshot.candidates[0].ranking_key = None;
assert!(
work_portfolio_markdown(&legacy_snapshot).contains("| unavailable (legacy artifact) |")
);
assert!(
candidate_markdown(&legacy, "# Legacy")
.contains("ranking key: unavailable (legacy artifact)")
);
for malformed in [
serde_json::json!([]),
serde_json::json!([0, 0, 0, 0, 0, 0, 0]),
serde_json::json!([0, 0, 0, 0, 0, 0, 0, 0, 0]),
serde_json::json!([0, 0, 0, 0, 0, 0, 0, "0"]),
] {
row["ranking_key"] = malformed;
if serde_json::from_value::<WorkCandidateV1>(row.clone()).is_ok() {
return Err(format!(
"malformed ranking key accepted: {}",
row["ranking_key"]
));
}
}
let empty =
build_candidates_view(&snapshot, Some("campaign-infra-hardening"), None, 10, None)?;
assert!(empty.candidates.is_empty());
let empty_json: Value = serde_json::from_str(&work_portfolio_json(&empty)?)
.map_err(|error| error.to_string())?;
assert_eq!(empty_json["candidates"], serde_json::json!([]));
Ok(())
}

#[test]
fn work_portfolio_ranking_key_preserves_first_issue_risk_lookup() -> Result<(), String> {
let mut captured =
load_work_captured_dir(&workspace_path("fixtures/work_portfolio/corpus"))?;
let issues = &mut captured.issues.as_mut().ok_or("issues missing")?.issues;
let mut duplicate = issues
.iter()
.find(|issue| issue.number == 9105)
.ok_or("issue 9105 missing")?
.clone();
duplicate.honesty_risk = Some("high".to_string());
issues.push(duplicate);
let snapshot = compile_work_portfolio(&captured, None)?;
let rows: Vec<_> = snapshot
.candidates
.iter()
.filter(|candidate| candidate.issue == 9105)
.collect();
assert_eq!(rows.len(), 2);
// The pre-existing sorter resolves risk by the first matching issue,
// even when captured input repeats an issue with conflicting metadata.
for row in rows {
assert_eq!(row.ranking_key, Some([1, 1, 0, 1, 0, 2, 0, 0]));
}
Ok(())
}

/// Box 1 + fixture rows 1/2/10/11: multiple campaigns with eligible
/// issues in different surfaces appear in one snapshot, one lane full of
/// collisions and one independent available lane, an empty campaign that
Expand Down
Loading