-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpr.rs
More file actions
341 lines (317 loc) · 14.6 KB
/
Copy pathpr.rs
File metadata and controls
341 lines (317 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! PR-context contributor (v7).
//!
//! Activates on PR-triggered builds and stages a small focused set of
//! PR signals + appends a tailored prompt fragment to the agent prompt
//! file. The actual logic lives in the `exec-context-pr.js`
//! `ado-script` bundle — this Rust module's job is to emit a slim YAML
//! step that invokes it with the right env vars and condition gate.
//!
//! ## Artefacts (staged by the bundle on success)
//!
//! - `aw-context/pr/base.sha` — target merge-base SHA
//! - `aw-context/pr/head.sha` — PR head SHA
//!
//! On failure (validation or merge-base resolution failed):
//!
//! - `aw-context/pr/error.txt` — one-line failure reason
//!
//! ## Prompt injection
//!
//! `exec-context-pr.js` appends a success-or-failure prompt fragment
//! directly to `/tmp/awf-tools/agent-prompt.md` (created earlier by
//! the "Prepare agent prompt" step in `base.yml`). Short identifiers
//! (`PR_ID`, `PROJECT`, `REPO`) are interpolated into the prompt
//! literally so the agent sees natural English ("This is PR #4242 in
//! project 'OneBranch' / repository 'awesome-repo'.") + example ADO
//! MCP tool calls with the right arguments pre-filled.
//!
//! ## Trust boundary
//!
//! - `SYSTEM_ACCESSTOKEN` is mapped only into THIS step's `env:` block,
//! never the agent step's env. Within this step, Node inherits the
//! variable on its `process.env` (unavoidable — the ADO `env:` block
//! exports to the step process), but it is never logged, never
//! passed in argv, and never written to `.git/config`.
//! - The wrapping `GIT_CONFIG_*` env vars that actually carry the
//! bearer into `git`'s `http.extraheader` config (see
//! `scripts/ado-script/src/shared/git.ts::bearerEnv`) are
//! only ever set in the *spawned `git` child's* environment — not
//! in Node's global `process.env`. This is a strict improvement
//! over the v6.2 bash implementation, where the bearer also lived
//! in the wrapping shell's env (shared with the `fail()` function,
//! regex validation, etc.) on top of the same Node-step exposure.
//! - The token is never written to `.git/config`; `persistCredentials`
//! is never `true`; no checkout override is emitted.
//! - The step is gated by `condition: and(succeeded(),
//! eq(variables['Build.Reason'], 'PullRequest'))` so it never runs
//! after an earlier failure or on non-PR builds.
//!
//! ## Wiring
//!
//! The bundle's install + download is owned by `AdoScriptExtension`'s
//! Agent-job prepare declarations. It fires whenever EITHER the
//! runtime-import resolver (`import.js`) OR the PR contributor
//! (this module) is active. See
//! `src/compile/extensions/ado_script.rs::declarations` for the gate.
//!
//! `AdoScriptExtension` runs at `ExtensionPhase::System` and
//! `ExecContextExtension` runs at `ExtensionPhase::Tool`, so the
//! install/download always lands before the bundle invocation in the
//! emitted YAML.
use crate::compile::extensions::CompileContext;
use crate::compile::ado_bundle::{Bundle, TokenSource, apply_bundle_auth};
use crate::compile::extensions::ado_script::EXEC_CONTEXT_PR_PATH;
use crate::compile::ir::condition::{Condition, Expr};
use crate::compile::ir::env::EnvValue;
use crate::compile::ir::step::{BashStep, Step};
use crate::compile::types::PrContextConfig;
use super::contributor::{ContextContributor, succeeded_and};
/// PR-context contributor. Activates when `on.pr` is configured
/// (unless explicitly disabled via `execution-context.pr.enabled: false`).
pub(super) struct PrContextContributor {
config: PrContextConfig,
/// Whether `on.pr.mode == Synthetic` for this agent. Drives
/// emission of the coalesced `SYSTEM_PULLREQUEST_*` env vars so the
/// bundle reads either real PR identifiers (true PR builds) or the
/// `synthPr` Setup-job outputs (CI builds promoted via synth).
synthetic_pr_active: bool,
}
impl PrContextContributor {
pub(super) fn new(config: PrContextConfig, synthetic_pr_active: bool) -> Self {
Self {
config,
synthetic_pr_active,
}
}
}
impl ContextContributor for PrContextContributor {
fn name(&self) -> &str {
"pr"
}
fn should_activate(&self, ctx: &CompileContext) -> bool {
// MAINTENANCE: this MUST stay in lock-step with
// `super::pr_contributor_will_activate` (the shared helper used
// by `collect_extensions` to populate
// `AdoScriptExtension::exec_context_pr_active`). The divergence-
// trap tests in `super::tests` exercise the helper path; this
// method is the runtime-context-aware version used by the
// declarations path.
if ctx.front_matter.pr_trigger().is_none() {
return false;
}
match self.config.explicit_enabled() {
Some(false) => false,
Some(true) | None => true,
}
}
fn prepare_step_typed(&self, _ctx: &CompileContext) -> anyhow::Result<Option<Step>> {
// Synth-active path reads the Agent-job-level hoisted
// variables `AW_PR_ID` / `AW_PR_TARGETBRANCH` (populated by
// `agentic_pipeline::agent_job_variables_hoist` from the
// `synthPr` Setup-job step outputs) via the same-job `$(name)`
// macro form. Step-level `env:` does NOT reliably evaluate
// cross-job `$[ dependencies.<Job>.outputs[...] ]` runtime
// expressions (see PR #956 — empirically broken in
// msazuresphere/4x4 build #612528); the job-level
// `variables:` mapping is the only safe location for those
// refs.
//
// The bash gate collapses to a single `[ -z "$AW_PR_ID" ]`
// check: `synthPr` always runs and unifies real-PR
// `SYSTEM_PULLREQUEST_*` and synth-discovered PR identifiers
// into the `AW_PR_*` namespace, so an empty `AW_PR_ID` means
// "neither a real PR build nor a synth-promoted CI build" —
// which is exactly when this step should skip.
//
// Coexists with `prepare_step` until production callers switch.
let (prelude, condition) = if self.synthetic_pr_active {
(
" if [ -z \"$AW_PR_ID\" ]; then\n echo \"[aw-context] No PR identifier resolved (not a PR build and not synth-promoted); skipping exec-context-pr.\"\n exit 0\n fi\n",
Condition::Succeeded,
)
} else {
(
"",
succeeded_and(Condition::Eq(
Expr::Variable("Build.Reason".to_string()),
Expr::Literal("PullRequest".to_string()),
)),
)
};
let script = format!("set -euo pipefail\n{prelude}node '{EXEC_CONTEXT_PR_PATH}'\n");
// ADO auto-injects predefined System.*/Build.* context vars, so the
// bundle reads SYSTEM_TEAMPROJECT / BUILD_REPOSITORY_NAME /
// BUILD_SOURCESDIRECTORY (and, in real-PR mode, SYSTEM_PULLREQUEST_*)
// directly. Only the non-auto-injected SYSTEM_ACCESSTOKEN bearer and,
// in synth mode, the hoisted AW_PR_* overrides are projected.
let mut step = apply_bundle_auth(
BashStep::new("Stage PR execution context (aw-context/pr/*)", script)
.with_condition(condition),
Bundle::ExecContextPr,
TokenSource::SystemAccessToken,
);
if self.synthetic_pr_active {
step = step
.with_env(
"SYSTEM_PULLREQUEST_PULLREQUESTID",
EnvValue::pipeline_var("AW_PR_ID"),
)
.with_env(
"SYSTEM_PULLREQUEST_TARGETBRANCH",
EnvValue::pipeline_var("AW_PR_TARGETBRANCH"),
)
.with_env(
"SYSTEM_PULLREQUEST_SOURCEBRANCH",
EnvValue::pipeline_var("AW_PR_SOURCEBRANCH"),
);
}
Ok(Some(Step::Bash(step)))
}
fn bash_commands(&self) -> Vec<String> {
// Read-only git commands the agent needs to inspect the PR diff
// locally. Added unconditionally when this contributor activates
// (matches the runtime-extension pattern in
// `src/runtimes/*/extension.rs::required_bash_commands`).
vec![
"git".to_string(),
"git diff".to_string(),
"git log".to_string(),
"git show".to_string(),
"git status".to_string(),
"git rev-parse".to_string(),
"git symbolic-ref".to_string(),
]
}
}
#[cfg(test)]
mod tests {
//! Direct unit tests for `PrContextContributor::prepare_step` —
//! pins both the `mode: synthetic` (default) and `mode: policy`
//! emitted YAML shapes for the env-coalesce macros and the
//! step-level `condition:`. Catches accidental regressions of the
//! coalesce wiring without round-tripping through a full snapshot
//! fixture.
use super::*;
use crate::compile::extensions::CompileContext;
use crate::compile::types::{FrontMatter, PrContextConfig};
fn parse_fm(src: &str) -> FrontMatter {
let (fm, _) = crate::compile::common::parse_markdown(src).unwrap();
fm
}
fn pr_fm() -> FrontMatter {
parse_fm(
"---\nname: test\ndescription: test\non:\n pr:\n branches:\n include: [main]\n---\n",
)
}
// ── Typed-IR `prepare_step_typed` shape tests ──
/// Synth-active: the typed prepare step's env block consumes the
/// Agent-job-level unified pipeline variables populated from the
/// Setup-job synthPr outputs. This keeps step env in macro form —
/// no [`Step::RawYaml`], no hand-written `$[ coalesce(...) ]`
/// strings.
#[test]
fn prepare_step_typed_synth_active_consumes_unified_pipeline_vars() {
let contributor = PrContextContributor::new(PrContextConfig::default(), true);
let fm = pr_fm();
let ctx = CompileContext::for_test(&fm);
let step = contributor
.prepare_step_typed(&ctx)
.expect("typed prepare_step succeeds")
.expect("contributor activates");
let bash = match &step {
Step::Bash(b) => b,
other => panic!("expected Step::Bash, got {other:?}"),
};
// Condition: succeeded() — cross-job dep refs are illegal at
// step level, so the synth-active path gates in bash and
// keeps the step condition trivial.
assert!(
matches!(bash.condition, Some(Condition::Succeeded)),
"synth-active condition must be Succeeded; got {:?}",
bash.condition
);
// PR id env: PipelineVar reading the Agent-job-level hoisted
// `AW_PR_ID` variable (populated from synthPr Setup-job step
// output by `agentic_pipeline::agent_job_variables_hoist`). The
// step env reads the resolved variable via the same-job
// `$(name)` macro form — runtime `$[ ... ]` expressions are
// NOT evaluated inside step env (PR #956).
match bash.env.get("SYSTEM_PULLREQUEST_PULLREQUESTID") {
Some(EnvValue::PipelineVar(name)) => assert_eq!(name, "AW_PR_ID"),
other => panic!("expected PipelineVar(AW_PR_ID), got {other:?}"),
}
// Target branch env: same shape reading AW_PR_TARGETBRANCH.
match bash.env.get("SYSTEM_PULLREQUEST_TARGETBRANCH") {
Some(EnvValue::PipelineVar(name)) => assert_eq!(name, "AW_PR_TARGETBRANCH"),
other => panic!("expected PipelineVar(AW_PR_TARGETBRANCH), got {other:?}"),
}
// The synth-active path no longer projects AW_SYNTHETIC_PR
// or BUILD_REASON through the step env — the bash gate
// checks `[ -z "$AW_PR_ID" ]` instead (single empty-check
// that covers both "not a PR build" AND "not synth-promoted").
assert!(
!bash.env.contains_key("AW_SYNTHETIC_PR"),
"synth-active prepare step must not project AW_SYNTHETIC_PR (new gate uses AW_PR_ID empty-check)"
);
assert!(
!bash.env.contains_key("BUILD_REASON"),
"synth-active prepare step must not project BUILD_REASON (new gate uses AW_PR_ID empty-check)"
);
// SYSTEM_ACCESSTOKEN must still be in the step's env (the
// trust boundary that the bundle relies on), projected as a secret
// via the bundle-auth applier.
assert!(matches!(
bash.env.get("SYSTEM_ACCESSTOKEN"),
Some(EnvValue::Secret(v)) if v == "System.AccessToken"
));
}
/// Synth-inactive: the auto-injected `SYSTEM_PULLREQUEST_*` and
/// `SYSTEM_TEAMPROJECT` / `BUILD_*` context vars are NOT re-projected;
/// condition preserves the default success gate and then gates on PullRequest.
#[test]
fn prepare_step_typed_synth_inactive_uses_plain_macros_and_narrow_condition() {
let contributor = PrContextContributor::new(PrContextConfig::default(), false);
let fm = pr_fm();
let ctx = CompileContext::for_test(&fm);
let step = contributor
.prepare_step_typed(&ctx)
.expect("typed prepare_step succeeds")
.expect("contributor activates");
let bash = match &step {
Step::Bash(b) => b,
other => panic!("expected Step::Bash, got {other:?}"),
};
// In real-PR mode the bundle reads the auto-injected PR vars and
// context vars directly, so the step re-projects none of them.
for stripped in [
"SYSTEM_PULLREQUEST_PULLREQUESTID",
"SYSTEM_PULLREQUEST_TARGETBRANCH",
"SYSTEM_TEAMPROJECT",
"BUILD_REPOSITORY_NAME",
"BUILD_SOURCESDIRECTORY",
] {
assert!(
bash.env.get(stripped).is_none(),
"{stripped} is auto-injected and must not be re-projected"
);
}
// No BUILD_REASON / AW_SYNTHETIC_PR env entries (the bash
// guard isn't emitted on the synth-inactive path).
assert!(!bash.env.contains_key("BUILD_REASON"));
assert!(!bash.env.contains_key("AW_SYNTHETIC_PR"));
match bash.condition.as_ref().expect("condition required") {
Condition::And(parts) => {
assert!(matches!(parts.as_slice(), [Condition::Succeeded, _]));
let Condition::Eq(Expr::Variable(name), Expr::Literal(lit)) = &parts[1] else {
panic!(
"expected Condition::Eq(Variable, Literal), got {:?}",
parts[1]
);
};
assert_eq!(name, "Build.Reason");
assert_eq!(lit, "PullRequest");
}
other => panic!("expected succeeded And condition, got {other:?}"),
}
}
}