From 295b10bb9167e9775359d521ec903752cc0d15e8 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Tue, 13 Oct 2026 17:36:30 +0200 Subject: [PATCH 1/8] fix(#8192): read mint_url from config.yaml/config.base.yaml in fullsend run Signed-off-by: fmuntean --- internal/cli/run.go | 43 +++++-- internal/cli/run_test.go | 196 +++++++++++++++++++++++++++++ internal/config/defaults.go | 5 + internal/config/defaults_test.go | 2 + internal/config/interfaces.go | 22 ++++ internal/config/interfaces_test.go | 34 +++++ internal/config/load_test.go | 42 +++++++ 7 files changed, 333 insertions(+), 11 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 9d53ec970c..29ce3524f7 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -869,10 +869,8 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // credential (Poller/Analyst/Coder or a custom role) and export // GITLAB_TOKEN / PUSH_TOKEN from that CI/CD variable. Missing role // credentials fail closed; there is no shared-token fallback. #6865 #7499. - mintURL := sOpts.mintURL - if mintURL == "" { - mintURL = os.Getenv("FULLSEND_MINT_URL") - } + // Precedence: flag > config.yaml/config.base.yaml mint_url > env (#8192). + mintURL := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) runtimeLevel := h.PrivilegeLevelForStage(harness.PrivilegeStageRuntime) var minted bool var mintCleanup func() @@ -6084,7 +6082,8 @@ func titleCase(s string) string { func setupStatusNotifier(fullsendDir string, role string, forgePlatform string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { var notifyCfg config.StatusNotificationConfig orgConfigPath := filepath.Join(fullsendDir, "config.yaml") - if fsCfg := tryLoadFullsendConfig(orgConfigPath, printer); fsCfg != nil { + fsCfg := tryLoadFullsendConfig(orgConfigPath, printer) + if fsCfg != nil { // StatusNotifications is part of the shared ConfigReader interface, // so this works for both orgConfig and perRepoConfig. if sn := fsCfg.StatusNotifications(); sn != nil { @@ -6109,17 +6108,14 @@ func setupStatusNotifier(fullsendDir string, role string, forgePlatform string, if forgePlatform == "gitlab" { return setupStatusNotifierGitLab(notifyCfg, owner, repo, sOpts, printer) } - return setupStatusNotifierGitHub(notifyCfg, owner, repo, role, sOpts, printer) + return setupStatusNotifierGitHub(notifyCfg, fsCfg, owner, repo, role, sOpts, printer) } // setupStatusNotifierGitHub creates a status notifier for GitHub. It mints // a fresh token via the mint service for each API call and reads SHA/run ID // from GitHub Actions environment variables. -func setupStatusNotifierGitHub(notifyCfg config.StatusNotificationConfig, owner, repo, role string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { - mintURL := sOpts.mintURL - if mintURL == "" { - mintURL = os.Getenv("FULLSEND_MINT_URL") - } +func setupStatusNotifierGitHub(notifyCfg config.StatusNotificationConfig, orgCfg config.ConfigReader, owner, repo, role string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { + mintURL := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) if mintURL == "" { return nil, fmt.Errorf("no mint URL available (set --mint-url or FULLSEND_MINT_URL)") } @@ -6537,6 +6533,31 @@ func maybeRemintAgentTokenForStage(ctx context.Context, h *harness.Harness, mint }, nil } +// resolveMintURL resolves the token mint URL with the precedence order +// documented in docs/contributing/config-source-inventory.md's mint_url +// row: an explicit flag value wins outright (one-run override); then +// config.yaml/config.base.yaml's mint_url ("file should win" over the +// variable kept for older workflows/binaries); then FULLSEND_MINT_URL; +// then "" so callers keep today's warn-and-skip-minting behavior. The +// compiled default (DefaultPerRepoMintURL) is deliberately not consulted +// here — ConfigMintURLFromFile stops short of it, so an installed repo +// that never configured mint_url anywhere still resolves to "". +// +// orgCfg may be nil (no config loaded) or may not implement +// PerRepoConfigReader (e.g. deprecated org-mode config); both cases +// simply skip the file layer and fall through to the environment. +func resolveMintURL(flagValue string, orgCfg config.ConfigReader, getenv func(string) string) string { + if flagValue != "" { + return flagValue + } + if prc, ok := orgCfg.(config.PerRepoConfigReader); ok { + if u := prc.ConfigMintURLFromFile(); u != "" { + return u + } + } + return getenv("FULLSEND_MINT_URL") +} + // mintAgentToken mints a write-level GitHub App installation token for the // agent's role. Callers that select a privilege level (ADR 0073) should use // mintAgentTokenAtLevel instead. Existing tests and status-adjacent helpers diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index dac69e6b08..f7d184df64 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -5031,6 +5031,41 @@ func TestSetupStatusNotifier_MintURLFromEnv(t *testing.T) { assert.True(t, n.HasClientFactory(), "client factory should be set from FULLSEND_MINT_URL env var") } +func TestSetupStatusNotifier_MintURLFileWinsOverEnv(t *testing.T) { + tmpDir := t.TempDir() + printer := ui.New(io.Discard) + + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, "config.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, "config.yaml's mint_url must win over FULLSEND_MINT_URL") + return &mintclient.MintResult{Token: "ghs_test_minted"}, nil + } + + sOpts := statusOpts{ + statusRepo: "org/repo", + statusNum: 7, + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("GITHUB_ACTIONS", "true") + + n, err := setupStatusNotifier(tmpDir, "code", "", sOpts, printer) + require.NoError(t, err) + require.NotNil(t, n) + + client, err := n.InvokeClientFactory(context.Background()) + require.NoError(t, err) + assert.NotNil(t, client) +} + func TestSetupStatusNotifier_NoMintURL(t *testing.T) { tmpDir := t.TempDir() printer := ui.New(io.Discard) @@ -7332,6 +7367,167 @@ func TestRunAgent_FallsBackToFULLSEND_MINT_URL(t *testing.T) { assert.True(t, mintCalled, "should have used FULLSEND_MINT_URL env var fallback") } +func TestRunAgent_MintURLFileWinsOverEnv(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + + var mintCalled bool + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalled = true + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, "config.yaml's mint_url must win over FULLSEND_MINT_URL") + return &mintclient.MintResult{Token: "ghs_file_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + + // A stale/different value in the environment — simulating a + // repository variable set at install time that the file has since + // overridden without anyone updating the variable. + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "openshell") + assert.True(t, mintCalled, "should have minted using config.yaml's mint_url") +} + +func TestRunAgent_MintURLFromBaseFileWinsOverEnv(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + // config.base.yaml carries mint_url; config.yaml is present (so the + // repo is in layered mode) but does not override it. + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.base.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-base.example.com\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + + var mintCalled bool + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalled = true + assert.Equal(t, "https://mint-from-base.example.com", req.MintURL, "config.base.yaml's mint_url must win over FULLSEND_MINT_URL when config.yaml is silent") + return &mintclient.MintResult{Token: "ghs_base_file_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "openshell") + assert.True(t, mintCalled, "should have minted using config.base.yaml's mint_url") +} + +func TestRunAgent_MintURLFlagWinsOverFile(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + + var mintCalled bool + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalled = true + assert.Equal(t, "https://mint-from-flag.example.com", req.MintURL, "--mint-url flag must win over config.yaml's mint_url") + return &mintclient.MintResult{Token: "ghs_flag_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + sOpts := statusOpts{mintURL: "https://mint-from-flag.example.com"} + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, sOpts, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "openshell") + assert.True(t, mintCalled, "should have minted using the --mint-url flag") +} + func TestRunAgent_MintsRuntimePrivilegeLevel(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() diff --git a/internal/config/defaults.go b/internal/config/defaults.go index d9996e4a40..5d4a8b1fe5 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -65,6 +65,11 @@ func (d *perRepoDefaults) IsOwnersFileAuthEnabled() bool { return false } // ConfigMintURL returns the default mint URL (hosted public mint). func (d *perRepoDefaults) ConfigMintURL() string { return DefaultPerRepoMintURL } +// ConfigMintURLFromFile returns "" — the compiled-defaults layer has no +// file to read from, so it is always the terminal "nothing in the file" +// case for ConfigMintURLFromFile's overlay/base-only chain. +func (d *perRepoDefaults) ConfigMintURLFromFile() string { return "" } + // ConfigInferenceProvider returns the default inference provider. func (d *perRepoDefaults) ConfigInferenceProvider() string { return DefaultPerRepoInferenceProvider } diff --git a/internal/config/defaults_test.go b/internal/config/defaults_test.go index 995aa27311..57187df173 100644 --- a/internal/config/defaults_test.go +++ b/internal/config/defaults_test.go @@ -31,6 +31,7 @@ func TestPerRepoDefaults_CodeDefaults(t *testing.T) { // Mint/inference operational defaults. assert.Equal(t, DefaultPerRepoMintURL, d.ConfigMintURL()) + assert.Empty(t, d.ConfigMintURLFromFile(), "the defaults layer has no file to read from") assert.Equal(t, DefaultPerRepoInferenceProvider, d.ConfigInferenceProvider()) assert.Equal(t, "", d.ConfigInferenceProject(), "project has no code default") assert.Equal(t, DefaultPerRepoInferenceRegion, d.ConfigInferenceRegion()) @@ -54,6 +55,7 @@ func TestPerRepoConfig_EmptyConfigResolvesDefaults(t *testing.T) { // Mint/inference fields fall through to code defaults. assert.Equal(t, DefaultPerRepoMintURL, cfg.ConfigMintURL()) + assert.Empty(t, cfg.ConfigMintURLFromFile(), "neither file sets mint_url, and the defaults layer is not a file") assert.Equal(t, DefaultPerRepoInferenceProvider, cfg.ConfigInferenceProvider()) assert.Equal(t, "", cfg.ConfigInferenceProject(), "project has no code default") assert.Equal(t, DefaultPerRepoInferenceRegion, cfg.ConfigInferenceRegion()) diff --git a/internal/config/interfaces.go b/internal/config/interfaces.go index 05835d2aa8..39653f575f 100644 --- a/internal/config/interfaces.go +++ b/internal/config/interfaces.go @@ -66,6 +66,14 @@ type PerRepoConfigReader interface { ConfigForge() string ConfigTracker() string ConfigMintURL() string + // ConfigMintURLFromFile returns the mint URL as set in config.yaml or + // config.base.yaml only. Empty means neither file sets mint_url — the + // compiled default is not consulted here (contrast with + // ConfigMintURL, which falls all the way through to the compiled + // default). Callers that need to distinguish "the file is silent" from + // "the file resolves to the default" (e.g. fullsend run's + // warn-and-skip-minting fallback) use this instead of ConfigMintURL. + ConfigMintURLFromFile() string ConfigKeepHistory() bool ConfigInferenceProvider() string ConfigInferenceProject() string @@ -412,6 +420,20 @@ func (c *perRepoConfig) ConfigMintURL() string { return "" } +// ConfigMintURLFromFile returns the mint URL as set in config.yaml or +// config.base.yaml only; see the PerRepoConfigReader doc comment for why +// this stops short of the compiled default that ConfigMintURL falls +// through to. +func (c *perRepoConfig) ConfigMintURLFromFile() string { + if c.MintURL != "" { + return c.MintURL + } + if c.parent != nil { + return c.parent.ConfigMintURLFromFile() + } + return "" +} + // ConfigInferenceProvider returns the inference provider (e.g. "vertex"). func (c *perRepoConfig) ConfigInferenceProvider() string { if c.Inference != nil && c.Inference.Provider != "" { diff --git a/internal/config/interfaces_test.go b/internal/config/interfaces_test.go index 6d3ddd3ae2..2b52af3c2b 100644 --- a/internal/config/interfaces_test.go +++ b/internal/config/interfaces_test.go @@ -353,6 +353,40 @@ func TestPerRepoConfig_MintURL_Fallback(t *testing.T) { }) } +// TestPerRepoConfig_MintURLFromFile_Fallback +// checks thatConfigMintURLFromFile stops at "" instead of reaching the compiled +// default — it never asks the perRepoDefaults layer for a value. +func TestPerRepoConfig_MintURLFromFile_Fallback(t *testing.T) { + t.Run("empty falls through to parent", func(t *testing.T) { + parent := &perRepoConfig{ + MintURL: "https://mint.example.com", + parent: &perRepoDefaults{}, + } + overlay := &perRepoConfig{parent: parent} + assert.Equal(t, "https://mint.example.com", overlay.ConfigMintURLFromFile()) + }) + + t.Run("local overrides parent", func(t *testing.T) { + parent := &perRepoConfig{ + MintURL: "https://base-mint.example.com", + parent: &perRepoDefaults{}, + } + overlay := &perRepoConfig{ + MintURL: "https://overlay-mint.example.com", + parent: parent, + } + assert.Equal(t, "https://overlay-mint.example.com", overlay.ConfigMintURLFromFile()) + }) + + t.Run("empty when neither file sets it, unlike ConfigMintURL", func(t *testing.T) { + cfg := &perRepoConfig{parent: &perRepoDefaults{}} + assert.Empty(t, cfg.ConfigMintURLFromFile()) + // Sanity check that this genuinely differs from ConfigMintURL, + // not just a copy-paste of the same assertion. + assert.Equal(t, DefaultPerRepoMintURL, cfg.ConfigMintURL()) + }) +} + // --- Inference provider fallback --- func TestPerRepoConfig_InferenceProvider_Fallback(t *testing.T) { diff --git a/internal/config/load_test.go b/internal/config/load_test.go index 4c35c9534c..a500485146 100644 --- a/internal/config/load_test.go +++ b/internal/config/load_test.go @@ -486,6 +486,7 @@ inference: // Overlay overrides mint_url. assert.Equal(t, "https://overlay-mint.example.com", pcr.ConfigMintURL()) + assert.Equal(t, "https://overlay-mint.example.com", pcr.ConfigMintURLFromFile()) // Inference fields fall through to base. assert.Equal(t, "vertex", pcr.ConfigInferenceProvider()) assert.Equal(t, "base-project", pcr.ConfigInferenceProject()) @@ -493,6 +494,47 @@ inference: assert.Equal(t, "projects/123/locations/global/workloadIdentityPools/pool/providers/prov", pcr.ConfigInferenceWIFProvider()) } +// TestConfigMintURLFromFile_BaseOnly checks that when the overlay +// is silent on mint_url, ConfigMintURLFromFile falls through to the base +// file, same as ConfigMintURL. +func TestConfigMintURLFromFile_BaseOnly(t *testing.T) { + dir := t.TempDir() + base := "version: \"1\"\nmint_url: https://base-mint.example.com\n" + overlay := "version: \"1\"\n" + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte(base), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(overlay), 0o644)) + + cfg, err := LoadConfig(dir, LoadOpts{}) + require.NoError(t, err) + + pcr, ok := cfg.(PerRepoConfigReader) + require.True(t, ok) + + assert.Equal(t, "https://base-mint.example.com", pcr.ConfigMintURL()) + assert.Equal(t, "https://base-mint.example.com", pcr.ConfigMintURLFromFile()) +} + +// TestConfigMintURLFromFile_NeitherSet is the critical divergence from +// ConfigMintURL: when neither config.yaml nor config.base.yaml sets +// mint_url, ConfigMintURL falls through to the compiled default +// (DefaultPerRepoMintURL), but ConfigMintURLFromFile stops at "" — it +// never consults the compiled-defaults layer. This is what lets +// fullsend run distinguish "the file is silent" from "the file resolves +// to the default". +func TestConfigMintURLFromFile_NeitherSet(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("version: \"1\"\n"), 0o644)) + + cfg, err := LoadConfig(dir, LoadOpts{}) + require.NoError(t, err) + + pcr, ok := cfg.(PerRepoConfigReader) + require.True(t, ok) + + assert.Equal(t, DefaultPerRepoMintURL, pcr.ConfigMintURL()) + assert.Empty(t, pcr.ConfigMintURLFromFile()) +} + func TestLoadConfig_OnlyBase_MintInference(t *testing.T) { dir := t.TempDir() base := `version: "1" From 4fcebc0a044dface2e269de4f85e4e30009e1185 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Thu, 15 Oct 2026 12:21:30 +0200 Subject: [PATCH 2/8] fix(#8192): honor config.base.yaml-only mint_url in status notifier setupStatusNotifier loaded config via tryLoadFullsendConfig, which stats config.yaml and returns nil when that overlay is absent, never consulting config.base.yaml. runAgent instead resolves mint_url through loadLockConfig, which honors a base-only layout. In a base-only repo the agent would mint with the base file's mint_url while the notifier fell back to FULLSEND_MINT_URL (a possibly different mint) or failed with 'no mint URL available'. Add tryLoadLayeredFullsendConfig, a best-effort loader that calls config.LoadConfigWriter directly (like loadLockConfig) instead of gating on config.yaml's existence, and wire it into setupStatusNotifier. Add tests: tryLoadLayeredFullsendConfig unit tests (base-only, neither file, overlay-wins, malformed base) and two setupStatusNotifier tests covering a config.base.yaml-only mint_url winning over FULLSEND_MINT_URL, with and without that env var set. Verified both new notifier tests fail without the fix and pass with it. Signed-off-by: fmuntean Co-authored-by: Cursor --- internal/cli/orgconfig.go | 21 +++++++ internal/cli/run.go | 3 +- internal/cli/run_test.go | 116 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+), 2 deletions(-) diff --git a/internal/cli/orgconfig.go b/internal/cli/orgconfig.go index 82f17a09a2..f292b19c50 100644 --- a/internal/cli/orgconfig.go +++ b/internal/cli/orgconfig.go @@ -32,6 +32,27 @@ func tryLoadFullsendConfig(path string, printer *ui.Printer) config.ConfigWriter // tryLoadOrgConfig is an alias of tryLoadFullsendConfig (best-effort). var tryLoadOrgConfig = tryLoadFullsendConfig +// tryLoadLayeredFullsendConfig attempts to load the layered fullsend +// config (config.yaml over config.base.yaml) from fullsendDir. +// Unlike tryLoadFullsendConfig, it does not require config.yaml to +// exist on disk: a base-only layout (config.base.yaml present, +// config.yaml absent) is honored, matching loadLockConfig's semantics. +// Returns nil without error when neither layer exists, or when the +// config is malformed (best-effort, with a warning printed via +// printer in the malformed case). The returned ConfigWriter has +// ensured defaults. +func tryLoadLayeredFullsendConfig(fullsendDir string, printer *ui.Printer) config.ConfigWriter { + writer, err := config.LoadConfigWriter(fullsendDir, config.LoadOpts{MissingOK: false}) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + printer.StepWarn("Config malformed (remote resource allowlist unavailable): " + err.Error()) + } + return nil + } + writer.SetAllowedRemoteResources(config.EnsureDefaultAllowedRemoteResources(writer.AllowedResources())) + return writer +} + // requireFullsendConfig loads a .fullsend config.yaml from the // given path with strict error handling. Returns differentiated errors // for missing files, unreadable files, and parse failures. diff --git a/internal/cli/run.go b/internal/cli/run.go index 4622697a1e..953ad3f7a9 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -6103,8 +6103,7 @@ func titleCase(s string) string { // code-hosting forge (ADR 0093). func setupStatusNotifier(fullsendDir string, role string, forgePlatform string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { var notifyCfg config.StatusNotificationConfig - orgConfigPath := filepath.Join(fullsendDir, "config.yaml") - fsCfg := tryLoadFullsendConfig(orgConfigPath, printer) + fsCfg := tryLoadLayeredFullsendConfig(fullsendDir, printer) if fsCfg != nil { // StatusNotifications is part of the shared ConfigReader interface, // so this works for both orgConfig and perRepoConfig. diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index f7d184df64..71efc705d9 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -549,6 +549,51 @@ func TestTryLoadFullsendConfig_OmittedAllowlist(t *testing.T) { "omitted field must get defaults") } +func TestTryLoadLayeredFullsendConfig_BaseOnly(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte( + "version: \"1\"\nmint_url: https://mint-from-base.example.com\n", + ), 0o644)) + + printer := ui.New(io.Discard) + cfg := tryLoadLayeredFullsendConfig(dir, printer) + require.NotNil(t, cfg, "config.base.yaml alone (no config.yaml) must be honored") + prc, ok := cfg.(config.PerRepoConfigReader) + require.True(t, ok) + assert.Equal(t, "https://mint-from-base.example.com", prc.ConfigMintURLFromFile()) +} + +func TestTryLoadLayeredFullsendConfig_NeitherFileExists(t *testing.T) { + dir := t.TempDir() + printer := ui.New(io.Discard) + assert.Nil(t, tryLoadLayeredFullsendConfig(dir, printer)) +} + +func TestTryLoadLayeredFullsendConfig_OverlayWinsOverBase(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte( + "version: \"1\"\nmint_url: https://mint-from-base.example.com\n", + ), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte( + "version: \"1\"\nmint_url: https://mint-from-overlay.example.com\n", + ), 0o644)) + + printer := ui.New(io.Discard) + cfg := tryLoadLayeredFullsendConfig(dir, printer) + require.NotNil(t, cfg) + prc, ok := cfg.(config.PerRepoConfigReader) + require.True(t, ok) + assert.Equal(t, "https://mint-from-overlay.example.com", prc.ConfigMintURLFromFile()) +} + +func TestTryLoadLayeredFullsendConfig_MalformedBase(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte("[[[not yaml"), 0o644)) + + printer := ui.New(io.Discard) + assert.Nil(t, tryLoadLayeredFullsendConfig(dir, printer)) +} + func TestRequireFullsendConfig_OrgGetsDefaultAllowlist(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "config.yaml") @@ -5066,6 +5111,77 @@ func TestSetupStatusNotifier_MintURLFileWinsOverEnv(t *testing.T) { assert.NotNil(t, client) } +// TestSetupStatusNotifier_MintURLFromBaseFileWinsOverEnv covers the +// base-only layout (config.base.yaml present, config.yaml absent from +// disk) that tryLoadFullsendConfig used to silently drop entirely, +// since it gated on config.yaml's mere existence before ever +// consulting config.base.yaml. setupStatusNotifier must resolve +// mint_url from the base file and prefer it over FULLSEND_MINT_URL, +// matching runAgent's resolveMintURL precedence +// (TestRunAgent_MintURLFromBaseFileWinsOverEnv). +func TestSetupStatusNotifier_MintURLFromBaseFileWinsOverEnv(t *testing.T) { + tmpDir := t.TempDir() + printer := ui.New(io.Discard) + + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, "config.base.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-base.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + assert.Equal(t, "https://mint-from-base.example.com", req.MintURL, + "config.base.yaml's mint_url must win over FULLSEND_MINT_URL when config.yaml is absent") + return &mintclient.MintResult{Token: "ghs_base_test_minted"}, nil + } + + sOpts := statusOpts{ + statusRepo: "org/repo", + statusNum: 7, + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("GITHUB_ACTIONS", "true") + + n, err := setupStatusNotifier(tmpDir, "code", "", sOpts, printer) + require.NoError(t, err) + require.NotNil(t, n) + + client, err := n.InvokeClientFactory(context.Background()) + require.NoError(t, err) + assert.NotNil(t, client) +} + +// TestSetupStatusNotifier_MintURLFromBaseFileWithoutEnv confirms the +// base-only mint_url is honored even when FULLSEND_MINT_URL is unset, +// so the file layer is genuinely consulted rather than the test only +// passing by coincidence of the env-var fallback. +func TestSetupStatusNotifier_MintURLFromBaseFileWithoutEnv(t *testing.T) { + tmpDir := t.TempDir() + printer := ui.New(io.Discard) + + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, "config.base.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-base.example.com\n"), + 0o644, + )) + + sOpts := statusOpts{ + statusRepo: "org/repo", + statusNum: 7, + } + + t.Setenv("GITHUB_RUN_ID", "run-42") + + n, err := setupStatusNotifier(tmpDir, "review", "", sOpts, printer) + require.NoError(t, err) + assert.NotNil(t, n) + assert.True(t, n.HasClientFactory(), "client factory should be set from config.base.yaml's mint_url with no env var set") +} + func TestSetupStatusNotifier_NoMintURL(t *testing.T) { tmpDir := t.TempDir() printer := ui.New(io.Discard) From 1a2084b19998de26949af94ec1d2729363b3290c Mon Sep 17 00:00:00 2001 From: fmuntean Date: Thu, 15 Oct 2026 15:31:05 +0200 Subject: [PATCH 3/8] fix(#8192): fail-closed mint_url precedence for local runs and reconcile-status - runAgent: a mint_url sourced only from config.yaml/config.base.yaml now warns and skips minting (falling back to the ambient GH_TOKEN) when GitHub Actions OIDC env is unavailable, instead of hard-failing local runs. An explicit --mint-url flag or FULLSEND_MINT_URL still fails closed. - reconcile-status now resolves mint_url through the same resolveMintURL precedence as fullsend run (flag > layered file > env) when --fullsend-dir is given, so the two agree on a mint endpoint within the same CI job. - Update config-source-inventory.md and cli-internals.md to match. Signed-off-by: fmuntean Co-authored-by: Cursor --- docs/contributing/config-source-inventory.md | 2 +- docs/guides/dev/cli-internals.md | 6 +- internal/cli/reconcilestatus.go | 67 +++--- internal/cli/reconcilestatus_test.go | 51 ++++- internal/cli/run.go | 59 ++++- internal/cli/run_test.go | 221 +++++++++++++++++++ 6 files changed, 365 insertions(+), 41 deletions(-) diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 8b577b8e28..54ba710f6f 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -110,7 +110,7 @@ The Go accessor layers these. The bash steps in `.github/workflows/reusable-disp | `runtime`, and per-agent `agents[].runtime` | Which runtime runs (`claude`, `pi`, `codex`, `dummy`) | `--runtime`, `FULLSEND_RUNTIME` (repository variable copied by `setup-agent-env.sh`), agent entry, repo `runtime:`, compiled `claude` | Flag, then `FULLSEND_RUNTIME`, then the agent entry, then repo `runtime:`, then `claude` (`docs/cli/run.md`) | `fullsend run` | File should win. Flag stays first. `FULLSEND_RUNTIME` stays as the fallback | Yes, for the fleet default. | | `agents[].model` | Model for one agent | `--model`, `FULLSEND_MODEL`, then `FULLSEND_PI_MODEL` or `FULLSEND_CODEX_MODEL` when that runtime is selected, agent entry, harness, frontmatter | Flag, then `FULLSEND_MODEL`, then the runtime-scoped alias, then the agent entry | `fullsend run` | File should win. Same fallback rule | The shared default can live on the base-file agent entry. | | `agents[].effort` | Effort for one agent | `--effort`, `FULLSEND_EFFORT`, agent entry, harness | Flag, then `FULLSEND_EFFORT`, then the agent entry | `fullsend run` | File should win. Same fallback rule | Same as model. | -| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | On `fullsend run`: flag, then `FULLSEND_MINT_URL`. The accessor is not consulted on that path. Workflows pass `vars.FULLSEND_MINT_URL` in as the `mint-url` input, so the flag is set | `fullsend run`, mint-token action. GitLab jobs never mint; `forgePlatform == "gitlab"` skips that path throughout `run.go`, and the GitLab scaffold has no mint reference | File should win once the binary reads `mint_url` before the variable. The workflow must keep passing `mint-url` until old binaries read the file. Setup already copies the effective file value into `FULLSEND_MINT_URL` | Yes. | +| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | `fullsend run` and `reconcile-status --fullsend-dir`: flag, then layered `mint_url`, then `FULLSEND_MINT_URL` (`resolveMintURL`, #8400). A file-sourced value warns and skips minting, rather than failing, when GitHub Actions OIDC is unavailable; flag/env stay fail-closed. `mint token` has no `--fullsend-dir`, so it stays flag then env | `fullsend run`, `reconcile-status`, `mint token`. GitLab never mints | File should win: done for `run` and `reconcile-status`. Workflows still pass `mint-url` every stage, so the flag wins until the `route` job computes it from the file itself. `mint token` stays flag-then-env; it has no directory to layer from | Yes. | | `inference.region` | GCP region for inference | Layered `inference.region`, compiled `global`. Workflows pass `vars.FULLSEND_GCP_REGION` as `gcp_region`, which becomes `CLOUD_ML_REGION`. GitLab `run-agent-job.sh` exports `CLOUD_ML_REGION` from `FULLSEND_GCP_REGION` | The job environment, not the file. Setup writes the file's effective region into `FULLSEND_GCP_REGION` at install time. A later edit to the file does not change the variable | Vertex client via `CLOUD_ML_REGION`. The accessor is used at install and converge | File should win for the binary. Keep `FULLSEND_GCP_REGION` as the fallback and as the value old workflows still pass | Yes. | | `inference.project` | GCP project for inference | Layered `inference.project` (no compiled default), secret `FULLSEND_GCP_PROJECT_ID` | The secret. Workflows export it as `ANTHROPIC_VERTEX_PROJECT_ID`. `setup-gcp` uses the same secret to authenticate before the binary runs | Google auth action and the Vertex client | Leave the secret for the auth action. The file should be what the binary reads, with the secret as fallback. Do not put the secret value only in git if the auth action still needs it | Yes for the project id the binary uses. The secret remains for the auth action. | | `inference.wif_provider` | Workload Identity provider resource name | Layered `inference.wif_provider` (no compiled default), secret `FULLSEND_GCP_WIF_PROVIDER` | The secret. `setup-gcp` reads it | Google auth action | Leave the secret for the auth action. The file should describe the provider the binary needs. Same split as the project id | Yes for the non-secret resource name. The credential material stays a secret. | diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 5fae01007b..07f61f00f5 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -207,10 +207,10 @@ fullsend ├── --run-url # Workflow run URL (optional) ├── --sha # Commit SHA (optional) ├── --reason # Termination reason: terminated or cancelled (default: terminated) - ├── --mint-url # Mint service URL for on-demand token (default: $FULLSEND_MINT_URL) - ├── --role # Agent role for minting (required with --mint-url) + ├── --mint-url # Mint service URL for on-demand token (default: layered mint_url from --fullsend-dir, then $FULLSEND_MINT_URL) + ├── --role # Agent role for minting (required to mint a token) ├── --forge # Forge platform (github, gitlab); auto-detected from CI env - ├── --fullsend-dir # Path to fullsend config directory (completion mode detection and tracker routing) + ├── --fullsend-dir # Path to fullsend config directory (completion mode detection, layered mint_url resolution, and tracker routing) ├── --job-status # Job outcome from CI runner (e.g. success, failure, cancelled) └── --was-skipped # Pre-script decided to skip the run; forces synthesis under on_failure ``` diff --git a/internal/cli/reconcilestatus.go b/internal/cli/reconcilestatus.go index 63d83154ef..8a95681583 100644 --- a/internal/cli/reconcilestatus.go +++ b/internal/cli/reconcilestatus.go @@ -95,6 +95,31 @@ finalized, this is a no-op.`, return fmt.Errorf("--number must be a positive integer, got %d", number) } + // Loaded once, before mint-URL resolution and completion-mode + // lookup below, so both consult the same layered config.yaml/ + // config.base.yaml snapshot. orgCfg stays nil when + // --fullsend-dir was not provided or the config failed to + // load; downstream readers treat that as "no file layer". + var orgCfg config.ConfigReader + completionMode := "" + if fullsendDir != "" { + writer, err := config.LoadConfigWriter(fullsendDir, config.LoadOpts{MissingOK: true}) + switch { + case err != nil: + fmt.Fprintf(os.Stderr, "WARNING: could not load config from %s: %v; using default completion mode\n", fullsendDir, err) + default: + orgCfg = writer + // ConfigWriter embeds StatusNotificationsReader (via + // ConfigReader) directly, so no type assertion is + // needed. + if sn := writer.StatusNotifications(); sn != nil { + completionMode = sn.Comment.Completion + } else { + fmt.Fprintf(os.Stderr, "WARNING: no status_notifications configured at %s; using default completion mode\n", fullsendDir) + } + } + } + if trackerSource == "jira" { var jErr error tc, jErr = reconcileNewJiraTrackerClient() @@ -122,7 +147,7 @@ finalized, this is a no-op.`, } } else { var githubErr error - forgeClient, githubErr = reconcileGitHubClient(cmd, mintURL, role, repoName) + forgeClient, githubErr = reconcileGitHubClient(cmd, mintURL, role, repoName, orgCfg) if githubErr != nil { return githubErr } @@ -140,24 +165,6 @@ finalized, this is a no-op.`, termReason = statuscomment.ReasonTerminated } - completionMode := "" - if fullsendDir != "" { - writer, err := config.LoadConfigWriter(fullsendDir, config.LoadOpts{MissingOK: true}) - switch { - case err != nil: - fmt.Fprintf(os.Stderr, "WARNING: could not load config from %s: %v; using default completion mode\n", fullsendDir, err) - default: - // ConfigWriter embeds StatusNotificationsReader (via - // ConfigReader) directly, so no type assertion is - // needed. - if sn := writer.StatusNotifications(); sn != nil { - completionMode = sn.Comment.Completion - } else { - fmt.Fprintf(os.Stderr, "WARNING: no status_notifications configured at %s; using default completion mode\n", fullsendDir) - } - } - } - agentDescription := titleCase(strings.ReplaceAll(role, "-", " ")) return reconcileOrphaned(cmd.Context(), tc, project, number, runID, runURL, sha, termReason, completionMode, jobStatus, wasSkipped, agentDescription) @@ -170,10 +177,10 @@ finalized, this is a no-op.`, cmd.Flags().StringVar(&runURL, "run-url", "", "URL to the workflow run (optional)") cmd.Flags().StringVar(&sha, "sha", "", "commit SHA (optional, shown as short hash)") cmd.Flags().StringVar(&reason, "reason", "terminated", "termination reason: terminated or cancelled") - cmd.Flags().StringVar(&mintURL, "mint-url", "", "mint service URL for on-demand token (default: $FULLSEND_MINT_URL)") - cmd.Flags().StringVar(&role, "role", "", "agent role for minting (required with --mint-url)") + cmd.Flags().StringVar(&mintURL, "mint-url", "", "mint service URL for on-demand token (default: layered mint_url from --fullsend-dir, then $FULLSEND_MINT_URL)") + cmd.Flags().StringVar(&role, "role", "", "agent role for minting (required to mint a token)") cmd.Flags().StringVar(&forgeFlag, "forge", "", `forge platform (e.g. "github", "gitlab"); auto-detected from CI env vars when omitted`) - cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", "", "path to fullsend config directory (used to detect completion mode and read normalized event for tracker routing)") + cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", "", "path to fullsend config directory (used to detect completion mode, resolve a layered mint_url, and read normalized event for tracker routing)") cmd.Flags().StringVar(&jobStatus, "job-status", "", "job outcome from the CI runner (e.g. success, failure, cancelled)") cmd.Flags().BoolVar(&wasSkipped, "was-skipped", false, "whether the pre-script decided to skip the run (forces synthesis under on_failure even when --job-status is success)") _ = cmd.MarkFlagRequired("run-id") @@ -182,16 +189,20 @@ finalized, this is a no-op.`, } // reconcileGitHubClient mints a GitHub token and returns a forge client. -func reconcileGitHubClient(cmd *cobra.Command, mintURL, role, repoName string) (forge.Client, error) { - if mintURL == "" { - mintURL = os.Getenv("FULLSEND_MINT_URL") - } +// mintURL resolution mirrors fullsend run's precedence (flag > layered +// config.yaml/config.base.yaml mint_url > FULLSEND_MINT_URL) so that +// reconcile-status agrees with run on which mint endpoint to use when both +// are invoked with the same --fullsend-dir in the same CI job (#8400). +// orgCfg may be nil when --fullsend-dir was not provided or its config +// failed to load; resolveMintURL treats that the same as "no file layer". +func reconcileGitHubClient(cmd *cobra.Command, mintURL, role, repoName string, orgCfg config.ConfigReader) (forge.Client, error) { + mintURL, _ = resolveMintURL(mintURL, orgCfg, os.Getenv) if mintURL == "" { - return nil, fmt.Errorf("--mint-url or FULLSEND_MINT_URL required") + return nil, fmt.Errorf("--mint-url, a layered mint_url in config.yaml/config.base.yaml, or FULLSEND_MINT_URL required") } if role == "" { - return nil, fmt.Errorf("--role is required when using --mint-url") + return nil, fmt.Errorf("--role is required to mint a token") } result, err := reconcileMintToken(cmd.Context(), mintclient.MintRequest{ MintURL: mintURL, diff --git a/internal/cli/reconcilestatus_test.go b/internal/cli/reconcilestatus_test.go index 4a64508208..e481a4b601 100644 --- a/internal/cli/reconcilestatus_test.go +++ b/internal/cli/reconcilestatus_test.go @@ -55,7 +55,7 @@ func TestNewReconcileStatusCmd_ValidationErrors(t *testing.T) { { name: "missing mint-url", args: []string{"--repo", "org/repo", "--number", "7", "--run-id", "run-1"}, - wantErr: "--mint-url or FULLSEND_MINT_URL required", + wantErr: "--mint-url, a layered mint_url in config.yaml/config.base.yaml, or FULLSEND_MINT_URL required", }, { name: "invalid number", @@ -70,7 +70,7 @@ func TestNewReconcileStatusCmd_ValidationErrors(t *testing.T) { { name: "mint-url without role", args: []string{"--repo", "org/repo", "--number", "7", "--run-id", "run-1", "--mint-url", "https://mint.example.com"}, - wantErr: "--role is required when using --mint-url", + wantErr: "--role is required to mint a token", }, } for _, tt := range tests { @@ -111,6 +111,53 @@ func TestNewReconcileStatusCmd_MintURLFromEnv(t *testing.T) { assert.Contains(t, err.Error(), "minting status token") } +// TestNewReconcileStatusCmd_MintURLFromFile checks that reconcile-status must resolve mint_url from the +// same layered config.yaml/config.base.yaml that fullsend run reads via +// --fullsend-dir, not just --mint-url/FULLSEND_MINT_URL, so the two agree +// on a mint endpoint within the same CI job. +func TestNewReconcileStatusCmd_MintURLFromFile(t *testing.T) { + dir := t.TempDir() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte("[]")) + })) + defer srv.Close() + + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("version: \"1\"\nmint_url: "+srv.URL+"\n"), 0o644)) + + var capturedMintURL string + origMint := reconcileMintToken + reconcileMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + capturedMintURL = req.MintURL + return &mintclient.MintResult{Token: "ghs_file_minted_token"}, nil + } + defer func() { reconcileMintToken = origMint }() + + origForge := reconcileNewForgeClient + reconcileNewForgeClient = func(token string) forge.Client { + return gh.New(token).WithBaseURL(srv.URL) + } + defer func() { reconcileNewForgeClient = origForge }() + + // A stale/different value in the environment — simulating a repository + // variable the file has since overridden — must lose to the file. + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + + cmd := newReconcileStatusCmd() + cmd.SetArgs([]string{ + "--repo", "org/repo", + "--number", "7", + "--run-id", "run-1", + "--role", "review", + "--fullsend-dir", dir, + }) + + err := cmd.Execute() + require.NoError(t, err) + assert.Equal(t, srv.URL, capturedMintURL, "config.yaml's mint_url must win over FULLSEND_MINT_URL") +} + func TestNewReconcileStatusCmd_TokenFlagRemoved(t *testing.T) { cmd := newReconcileStatusCmd() f := cmd.Flags().Lookup("token") diff --git a/internal/cli/run.go b/internal/cli/run.go index 953ad3f7a9..7998e11c88 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -878,7 +878,18 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // GITLAB_TOKEN / PUSH_TOKEN from that CI/CD variable. Missing role // credentials fail closed; there is no shared-token fallback. #6865 #7499. // Precedence: flag > config.yaml/config.base.yaml mint_url > env (#8192). - mintURL := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) + mintURL, mintSource := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) + // A mint_url that only came from the file layer is an implicit default + // meant to make CI convenient; it must not turn a previously-safe local + // run into a hard failure by attempting a GitHub Actions OIDC exchange + // that isn't available outside Actions. A flag or FULLSEND_MINT_URL is + // an explicit signal from the operator, so those stay fail-closed below + // (#8400). + mintSkipWarning := "" + if mintSource == mintURLSourceFile && !hasActionsOIDCEnv(os.Getenv) { + mintSkipWarning = "config.yaml/config.base.yaml sets mint_url, but GitHub Actions OIDC is unavailable (not running in Actions, or missing id-token: write); skipping token minting for role " + h.Role + mintURL = "" + } runtimeLevel := h.PrivilegeLevelForStage(harness.PrivilegeStageRuntime) var minted bool var mintCleanup func() @@ -893,7 +904,10 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep if mintErr != nil { return fmt.Errorf("agent token minting failed: %w", mintErr) } - if !minted && mintURL == "" { + switch { + case mintSkipWarning != "": + printer.StepWarn(mintSkipWarning) + case !minted && mintURL == "": printer.StepWarn("No --mint-url provided; skipping token minting for role " + h.Role) } } @@ -6136,7 +6150,7 @@ func setupStatusNotifier(fullsendDir string, role string, forgePlatform string, // a fresh token via the mint service for each API call and reads SHA/run ID // from GitHub Actions environment variables. func setupStatusNotifierGitHub(notifyCfg config.StatusNotificationConfig, orgCfg config.ConfigReader, owner, repo, role string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { - mintURL := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) + mintURL, _ := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) if mintURL == "" { return nil, fmt.Errorf("no mint URL available (set --mint-url or FULLSEND_MINT_URL)") } @@ -6554,6 +6568,22 @@ func maybeRemintAgentTokenForStage(ctx context.Context, h *harness.Harness, mint }, nil } +// mintURLSource identifies where resolveMintURL's returned value came +// from. Callers with a fail-closed mint path (e.g. runAgent) use this to +// distinguish an explicit signal — a flag or FULLSEND_MINT_URL, where an +// operator deliberately asked for minting — from the implicit file layer, +// so a config.yaml/config.base.yaml-sourced mint_url does not turn a +// previously-safe local run into a hard failure when GitHub Actions OIDC +// isn't available (#8400). +type mintURLSource int + +const ( + mintURLSourceNone mintURLSource = iota + mintURLSourceFlag + mintURLSourceFile + mintURLSourceEnv +) + // resolveMintURL resolves the token mint URL with the precedence order // documented in docs/contributing/config-source-inventory.md's mint_url // row: an explicit flag value wins outright (one-run override); then @@ -6567,16 +6597,31 @@ func maybeRemintAgentTokenForStage(ctx context.Context, h *harness.Harness, mint // orgCfg may be nil (no config loaded) or may not implement // PerRepoConfigReader (e.g. deprecated org-mode config); both cases // simply skip the file layer and fall through to the environment. -func resolveMintURL(flagValue string, orgCfg config.ConfigReader, getenv func(string) string) string { +func resolveMintURL(flagValue string, orgCfg config.ConfigReader, getenv func(string) string) (string, mintURLSource) { if flagValue != "" { - return flagValue + return flagValue, mintURLSourceFlag } if prc, ok := orgCfg.(config.PerRepoConfigReader); ok { if u := prc.ConfigMintURLFromFile(); u != "" { - return u + return u, mintURLSourceFile } } - return getenv("FULLSEND_MINT_URL") + if u := getenv("FULLSEND_MINT_URL"); u != "" { + return u, mintURLSourceEnv + } + return "", mintURLSourceNone +} + +// hasActionsOIDCEnv reports whether the GitHub Actions OIDC request +// environment variables are present. mintclient.MintToken's only +// credential path is exchanging a GitHub Actions OIDC JWT +// (ACTIONS_ID_TOKEN_REQUEST_URL / ACTIONS_ID_TOKEN_REQUEST_TOKEN), so +// their absence means any mint attempt is guaranteed to fail with a +// generic "is this running in GitHub Actions" error. Callers use this to +// decide whether to downgrade an implicit (file-sourced) mint attempt to +// a warn-and-skip instead of a hard failure (#8400). +func hasActionsOIDCEnv(getenv func(string) string) bool { + return getenv("ACTIONS_ID_TOKEN_REQUEST_URL") != "" && getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN") != "" } // mintAgentToken mints a write-level GitHub App installation token for the diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index 71efc705d9..3e4d8bef5b 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -7483,6 +7483,118 @@ func TestRunAgent_FallsBackToFULLSEND_MINT_URL(t *testing.T) { assert.True(t, mintCalled, "should have used FULLSEND_MINT_URL env var fallback") } +// TestResolveMintURL_Source verifies resolveMintURL reports where its +// returned value came from, which runAgent (#8400 follow-up) relies on to +// decide whether a missing GitHub Actions OIDC environment should warn-and- +// skip (file source) or stay fail-closed (flag/env source). +func TestResolveMintURL_Source(t *testing.T) { + fileCfgDir := t.TempDir() + require.NoError(t, os.WriteFile( + filepath.Join(fileCfgDir, "config.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + fileCfg, err := config.LoadConfigWriter(fileCfgDir, config.LoadOpts{MissingOK: true}) + require.NoError(t, err) + + emptyCfgDir := t.TempDir() + emptyCfg, err := config.LoadConfigWriter(emptyCfgDir, config.LoadOpts{MissingOK: true}) + require.NoError(t, err) + + getenvWith := func(v string) func(string) string { + return func(key string) string { + if key == "FULLSEND_MINT_URL" { + return v + } + return "" + } + } + + tests := []struct { + name string + flagValue string + orgCfg config.ConfigReader + getenv func(string) string + wantURL string + wantSource mintURLSource + }{ + { + name: "flag wins over file and env", + flagValue: "https://mint-from-flag.example.com", + orgCfg: fileCfg, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-flag.example.com", + wantSource: mintURLSourceFlag, + }, + { + name: "file wins over env when no flag", + flagValue: "", + orgCfg: fileCfg, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-file.example.com", + wantSource: mintURLSourceFile, + }, + { + name: "env used when file is silent", + flagValue: "", + orgCfg: emptyCfg, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-env.example.com", + wantSource: mintURLSourceEnv, + }, + { + name: "env used when orgCfg is nil", + flagValue: "", + orgCfg: nil, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-env.example.com", + wantSource: mintURLSourceEnv, + }, + { + name: "none when nothing is set", + flagValue: "", + orgCfg: emptyCfg, + getenv: getenvWith(""), + wantURL: "", + wantSource: mintURLSourceNone, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotURL, gotSource := resolveMintURL(tt.flagValue, tt.orgCfg, tt.getenv) + assert.Equal(t, tt.wantURL, gotURL) + assert.Equal(t, tt.wantSource, gotSource) + }) + } +} + +// TestHasActionsOIDCEnv verifies the gate runAgent uses to decide whether a +// file-sourced mint_url can be attempted: both OIDC request env vars must +// be present, matching mintclient.fetchOIDCJWT's own requirement. +func TestHasActionsOIDCEnv(t *testing.T) { + tests := []struct { + name string + requestURL string + requestToken string + want bool + }{ + {"both set", "https://actions.example.com", "tok", true}, + {"url missing", "", "tok", false}, + {"token missing", "https://actions.example.com", "", false}, + {"neither set", "", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + env := map[string]string{ + "ACTIONS_ID_TOKEN_REQUEST_URL": tt.requestURL, + "ACTIONS_ID_TOKEN_REQUEST_TOKEN": tt.requestToken, + } + got := hasActionsOIDCEnv(func(k string) string { return env[k] }) + assert.Equal(t, tt.want, got) + }) + } +} + func TestRunAgent_MintURLFileWinsOverEnv(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() @@ -7524,6 +7636,11 @@ func TestRunAgent_MintURLFileWinsOverEnv(t *testing.T) { t.Setenv("GH_TOKEN", "") t.Setenv("PUSH_TOKEN", "") t.Setenv("PUSH_TOKEN_SOURCE", "") + // A file-sourced mint_url only proceeds to mint when GitHub Actions + // OIDC is available; otherwise it is a warn-and-skip (#8400). Set + // both so this test exercises the "mint attempted" branch. + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://actions.example.com/oidc") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "fake-oidc-request-token") var buf bytes.Buffer rFlags := resolveFlags{maxDepth: 10, maxResources: 50} @@ -7581,6 +7698,11 @@ func TestRunAgent_MintURLFromBaseFileWinsOverEnv(t *testing.T) { t.Setenv("GH_TOKEN", "") t.Setenv("PUSH_TOKEN", "") t.Setenv("PUSH_TOKEN_SOURCE", "") + // A file-sourced mint_url only proceeds to mint when GitHub Actions + // OIDC is available; otherwise it is a warn-and-skip (#8400). Set + // both so this test exercises the "mint attempted" branch. + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://actions.example.com/oidc") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "fake-oidc-request-token") var buf bytes.Buffer rFlags := resolveFlags{maxDepth: 10, maxResources: 50} @@ -7644,6 +7766,105 @@ func TestRunAgent_MintURLFlagWinsOverFile(t *testing.T) { assert.True(t, mintCalled, "should have minted using the --mint-url flag") } +func TestRunAgent_MintURLFromFileSkipsWithoutOIDC(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + // No --mint-url flag, no FULLSEND_MINT_URL, and critically no + // ACTIONS_ID_TOKEN_REQUEST_URL/_TOKEN — this is the local-run case from + // docs/guides/user/running-agents-locally.md: the ambient GH_TOKEN is + // used directly and minting is skipped, exactly as it was before + // config.yaml's mint_url was consulted at all. + t.Setenv("FULLSEND_MINT_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "fake-gh-token") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.NotContains(t, err.Error(), "agent token minting failed", "a file-sourced mint_url without OIDC must not hard-fail the run") + assert.Contains(t, err.Error(), "openshell", "run should proceed past the skipped mint to the shell stage") + assert.Contains(t, buf.String(), "GitHub Actions OIDC is unavailable", "should warn that the file-sourced mint_url was skipped") + // mintAgentTokenAtLevel only calls os.Setenv("GH_TOKEN", ...) after a + // successful mint; skipping the mint attempt means that call never + // happens, so GH_TOKEN must still hold the ambient value set above, + // not a minted one. The fake openshell stub exits before reading any + // env vars, so this is the only way this test can observe that the + // ambient credential was left for the (unexercised) shell to use. + assert.Equal(t, "fake-gh-token", os.Getenv("GH_TOKEN"), "GH_TOKEN must remain the ambient token; minting must not have touched it") +} + +// TestRunAgent_MintURLFlagFailsClosedWithoutOIDC confirms the other half of +// the #8400 follow-up fix: unlike a file-sourced mint_url, an explicit +// --mint-url flag (or FULLSEND_MINT_URL) is a deliberate signal from the +// operator and stays fail-closed — it must still hard-fail when GitHub +// Actions OIDC is unavailable, rather than silently degrading. +func TestRunAgent_MintURLFlagFailsClosedWithoutOIDC(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "fake-gh-token") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + sOpts := statusOpts{mintURL: "https://mint-from-flag.example.com"} + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, sOpts, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "agent token minting failed", "an explicit --mint-url must stay fail-closed even without OIDC") +} + func TestRunAgent_MintsRuntimePrivilegeLevel(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() From 87b1064d4c048dac45ea1b79781a31827c82c3f0 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Tue, 20 Oct 2026 12:15:50 +0200 Subject: [PATCH 4/8] docs(#8192): clarify mint_url OIDC downgrade only applies to run's agent mint reconcile-status and the status-comment mint drop resolveMintURL's source and still fail on a file-sourced mint_url with no GitHub Actions OIDC; only runAgent's agent-token mint warns and skips. The config-source-inventory.md row previously implied all three paths downgrade the same way. Signed-off-by: fmuntean Co-authored-by: Cursor --- docs/contributing/config-source-inventory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 15c652eb9a..1dd98d1e1b 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -110,7 +110,7 @@ The Go accessor layers these. The bash steps in `.github/workflows/reusable-disp | `runtime`, and per-agent `agents[].runtime` | Which runtime runs (`claude`, `pi`, `codex`, `dummy`) | `--runtime`, `FULLSEND_RUNTIME` (repository variable copied by `setup-agent-env.sh`), agent entry, repo `runtime:`, compiled `claude` | Flag, then `FULLSEND_RUNTIME`, then the agent entry, then repo `runtime:`, then `claude` (`docs/cli/run.md`) | `fullsend run` | File should win. Flag stays first. `FULLSEND_RUNTIME` stays as the fallback | Yes, for the fleet default. | | `agents[].model` | Model for one agent | `--model`, `FULLSEND_MODEL`, then `FULLSEND_PI_MODEL` or `FULLSEND_CODEX_MODEL` when that runtime is selected, agent entry, harness, frontmatter | Flag, then `FULLSEND_MODEL`, then the runtime-scoped alias, then the agent entry | `fullsend run` | File should win. Same fallback rule | The shared default can live on the base-file agent entry. | | `agents[].effort` | Effort for one agent | `--effort`, `FULLSEND_EFFORT`, agent entry, harness | Flag, then `FULLSEND_EFFORT`, then the agent entry | `fullsend run` | File should win. Same fallback rule | Same as model. | -| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | `fullsend run` and `reconcile-status --fullsend-dir`: flag, then layered `mint_url`, then `FULLSEND_MINT_URL` (`resolveMintURL`, #8400). A file-sourced value warns and skips minting, rather than failing, when GitHub Actions OIDC is unavailable; flag/env stay fail-closed. `mint token` has no `--fullsend-dir`, so it stays flag then env | `fullsend run`, `reconcile-status`, `mint token`. GitLab never mints | File should win: done for `run` and `reconcile-status`. Workflows still pass `mint-url` every stage, so the flag wins until the `route` job computes it from the file itself. `mint token` stays flag-then-env; it has no directory to layer from | Yes. | +| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | `fullsend run` and `reconcile-status --fullsend-dir`: flag, then layered `mint_url`, then `FULLSEND_MINT_URL` (`resolveMintURL`, #8400). Only `runAgent`'s agent-token mint downgrades a file-sourced value to warn-and-skip (ambient `GH_TOKEN`) when GitHub Actions OIDC is unavailable; `reconcile-status` and the status-comment mint still attempt it and fail — fail-closed for `reconcile-status`, a per-call warning for status comments. `mint token` has no `--fullsend-dir`, so it stays flag then env | `fullsend run`, `reconcile-status`, `mint token`. GitLab never mints | File should win: done for `run` and `reconcile-status`. Workflows still pass `mint-url` every stage, so the flag wins until the `route` job computes it from the file itself. `mint token` stays flag-then-env; it has no directory to layer from. The OIDC downgrade should extend to `reconcile-status` and status comments for consistency — tracked, not yet done | Yes. | | `inference.region` | GCP region for inference | Layered `inference.region`, compiled `global`. Workflows pass `vars.FULLSEND_GCP_REGION` as `gcp_region`, which becomes `CLOUD_ML_REGION`. GitLab `run-agent-job.sh` exports `CLOUD_ML_REGION` from `FULLSEND_GCP_REGION` | The job environment, not the file. Setup writes the file's effective region into `FULLSEND_GCP_REGION` at install time. A later edit to the file does not change the variable | Vertex client via `CLOUD_ML_REGION`. The accessor is used at install and converge | File should win for the binary. Keep `FULLSEND_GCP_REGION` as the fallback and as the value old workflows still pass | Yes. | | `inference.project` | GCP project for inference | Layered `inference.project` (no compiled default), secret `FULLSEND_GCP_PROJECT_ID` | The secret. Workflows export it as `ANTHROPIC_VERTEX_PROJECT_ID`. `setup-gcp` uses the same secret to authenticate before the binary runs | Google auth action and the Vertex client | Leave the secret for the auth action. The file should be what the binary reads, with the secret as fallback. Do not put the secret value only in git if the auth action still needs it | Yes for the project id the binary uses. The secret remains for the auth action. | | `inference.wif_provider` | Workload Identity provider resource name | Layered `inference.wif_provider` (no compiled default), secret `FULLSEND_GCP_WIF_PROVIDER` | The secret. `setup-gcp` reads it | Google auth action | Leave the secret for the auth action. The file should describe the provider the binary needs. Same split as the project id | Yes for the non-secret resource name. The credential material stays a secret. | From bd18203789135beaf16192792c3e65fa368413eb Mon Sep 17 00:00:00 2001 From: fmuntean Date: Tue, 20 Oct 2026 13:56:44 +0200 Subject: [PATCH 5/8] fix(#8192): narrow mint_url OIDC downgrade to genuine local runs The file-sourced mint_url downgrade in runAgent was too broad: - It ignored a separately-set FULLSEND_MINT_URL (shadowed by the file's higher precedence but still a real signal to mint), so it silently skipped minting instead of staying fail-closed. - It didn't check GITHUB_ACTIONS, so a workflow missing id-token: write would silently fall back to the ambient GH_TOKEN instead of failing loudly. The downgrade now requires FULLSEND_MINT_URL to be unset and GITHUB_ACTIONS to not be "true", restricting it to a genuine local run with no competing signal. Also fixes a doc-comment typo and two stale mint_url descriptions in the local-run guides. Signed-off-by: fmuntean Co-authored-by: Cursor --- docs/guides/user/bring-your-own-agent.md | 8 +- docs/guides/user/running-agents-locally.md | 2 +- internal/cli/run.go | 19 ++++- internal/cli/run_test.go | 96 ++++++++++++++++++++++ internal/config/interfaces_test.go | 4 +- 5 files changed, 120 insertions(+), 9 deletions(-) diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index bf8911831b..9deae0b8c6 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -180,9 +180,11 @@ sequenceDiagram The dispatch workflow matches the comment against the `trigger:` of every registered harness and starts `fullsend run` for each match. `fullsend run` gets a short-lived GitHub token for the harness's `role:` from the mint (a -local run without `--mint-url` or `FULLSEND_MINT_URL` skips this and uses -your `GH_TOKEN`), sets up the providers on the OpenShell gateway, and starts -the sandbox. For GitHub and OpenAI the agent never holds a real credential: +local run with no mint URL from `--mint-url`, `config.yaml`/`config.base.yaml`, +or `FULLSEND_MINT_URL` — or where GitHub Actions OIDC isn't available — +skips this and uses your `GH_TOKEN`), sets up the providers on the OpenShell +gateway, and starts the sandbox. For GitHub and OpenAI the agent never holds +a real credential: the gateway gives it a placeholder and swaps in the real value on each request a declared provider covers. On the Vertex route the GCP credentials file is copied into the sandbox, and the model calls use it directly. After diff --git a/docs/guides/user/running-agents-locally.md b/docs/guides/user/running-agents-locally.md index 7c41803b53..0f106caa0c 100644 --- a/docs/guides/user/running-agents-locally.md +++ b/docs/guides/user/running-agents-locally.md @@ -397,7 +397,7 @@ target issue/PR. These flags mirror what the CI workflows pass automatically: | `--run-url` | URL of the CI/CD run shown in the status comment | | `--status-repo` | Repository (`owner/repo`) to post status comments on | | `--status-number` | Issue or PR number for status comments | -| `--mint-url` | Mint service URL for on-demand status comment tokens (default: `$FULLSEND_MINT_URL`) | +| `--mint-url` | Mint service URL for on-demand status comment tokens (default: layered `mint_url` from `--fullsend-dir`, then `$FULLSEND_MINT_URL`) | | `--forge` | Forge platform (`github` or `gitlab`); when omitted, resolved from `forge:` in the `config.yaml` at the root of `--fullsend-dir`, then `GITHUB_ACTIONS`/`GITLAB_CI` | Example: diff --git a/internal/cli/run.go b/internal/cli/run.go index 2f6516e6b8..c9605bd5cb 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -896,10 +896,23 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // run into a hard failure by attempting a GitHub Actions OIDC exchange // that isn't available outside Actions. A flag or FULLSEND_MINT_URL is // an explicit signal from the operator, so those stay fail-closed below - // (#8400). + // (#8400). Two conditions narrow the downgrade to a genuine local run, + // not just "OIDC env happens to be empty" (review feedback on #8400): + // - FULLSEND_MINT_URL must also be unset. The file wins the endpoint + // precedence either way, but an operator who separately set the + // env var still signalled real intent to mint, even though that + // value is shadowed, so a mint failure must stay loud. + // - GITHUB_ACTIONS must not be "true". Downgrading solely on missing + // OIDC env would also silently fall back to the ambient (often + // broader) GH_TOKEN inside Actions when a workflow is missing + // id-token: write — a misconfiguration that should fail loudly, + // not swap in unscoped credentials. mintSkipWarning := "" - if mintSource == mintURLSourceFile && !hasActionsOIDCEnv(os.Getenv) { - mintSkipWarning = "config.yaml/config.base.yaml sets mint_url, but GitHub Actions OIDC is unavailable (not running in Actions, or missing id-token: write); skipping token minting for role " + h.Role + if mintSource == mintURLSourceFile && + os.Getenv("FULLSEND_MINT_URL") == "" && + os.Getenv("GITHUB_ACTIONS") != "true" && + !hasActionsOIDCEnv(os.Getenv) { + mintSkipWarning = "config.yaml/config.base.yaml sets mint_url for a local run with no FULLSEND_MINT_URL, but GitHub Actions OIDC is unavailable; skipping token minting for role " + h.Role mintURL = "" } runtimeLevel := h.PrivilegeLevelForStage(harness.PrivilegeStageRuntime) diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index f3e4ffb560..e94f7ed78e 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -8257,6 +8257,7 @@ func TestRunAgent_MintURLFromFileSkipsWithoutOIDC(t *testing.T) { t.Setenv("FULLSEND_MINT_URL", "") t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("GITHUB_ACTIONS", "") t.Setenv("REPO_FULL_NAME", "org/my-repo") t.Setenv("GH_TOKEN", "fake-gh-token") t.Setenv("PUSH_TOKEN", "") @@ -8286,6 +8287,101 @@ func TestRunAgent_MintURLFromFileSkipsWithoutOIDC(t *testing.T) { // --mint-url flag (or FULLSEND_MINT_URL) is a deliberate signal from the // operator and stays fail-closed — it must still hard-fail when GitHub // Actions OIDC is unavailable, rather than silently degrading. +// TestRunAgent_MintURLFromFileFailsClosedWhenEnvAlsoSet is a regression test +// for review feedback on #8400: the file wins the mint_url endpoint +// precedence, so resolveMintURL reports mintURLSourceFile even when +// FULLSEND_MINT_URL is also set — but an operator who set the env var still +// signalled real intent to mint, even though that value is shadowed. The +// downgrade must not fire in that case; a missing OIDC environment must +// still hard-fail the run. +func TestRunAgent_MintURLFromFileFailsClosedWhenEnvAlsoSet(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("GITHUB_ACTIONS", "") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "fake-gh-token") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "agent token minting failed", "a competing FULLSEND_MINT_URL must stay fail-closed even though the file wins the endpoint") +} + +// TestRunAgent_MintURLFromFileFailsClosedInGitHubActions is a regression +// test for review feedback on #8400: downgrading solely on missing OIDC env +// would also silently fall back to the ambient GH_TOKEN inside GitHub +// Actions when a workflow is missing id-token: write — a misconfiguration +// that must fail loudly, not swap in unscoped credentials. The downgrade +// must only apply to a genuine local (non-Actions) run. +func TestRunAgent_MintURLFromFileFailsClosedInGitHubActions(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + // Simulates a workflow missing id-token: write permission: genuinely + // inside GitHub Actions, but the OIDC request env vars never showed up. + t.Setenv("FULLSEND_MINT_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("GITHUB_ACTIONS", "true") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "fake-gh-token") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "agent token minting failed", "a missing id-token: write permission inside Actions must fail loudly, not fall back to the ambient GH_TOKEN") +} + func TestRunAgent_MintURLFlagFailsClosedWithoutOIDC(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() diff --git a/internal/config/interfaces_test.go b/internal/config/interfaces_test.go index 2b52af3c2b..9c8729ee2c 100644 --- a/internal/config/interfaces_test.go +++ b/internal/config/interfaces_test.go @@ -353,8 +353,8 @@ func TestPerRepoConfig_MintURL_Fallback(t *testing.T) { }) } -// TestPerRepoConfig_MintURLFromFile_Fallback -// checks thatConfigMintURLFromFile stops at "" instead of reaching the compiled +// TestPerRepoConfig_MintURLFromFile_Fallback checks that +// ConfigMintURLFromFile stops at "" instead of reaching the compiled // default — it never asks the perRepoDefaults layer for a value. func TestPerRepoConfig_MintURLFromFile_Fallback(t *testing.T) { t.Run("empty falls through to parent", func(t *testing.T) { From 9b3d06c84085ca3a65d7d7f5893a6af4a234aaee Mon Sep 17 00:00:00 2001 From: fmuntean Date: Wed, 21 Oct 2026 14:31:04 +0200 Subject: [PATCH 6/8] docs(#8400): correct mint_url row for the prioritize live-dispatch effect Review on #8400 (discussion_r4325809765) found that the PR's "no live effect on dispatch" claim is false for the prioritize paths: reusable-prioritize.yml and the inlined prioritize job in reusable-dispatch.yml have no upfront mint-token step gating on FULLSEND_MINT_URL, and action.yml's MINT_FLAGS omits --mint-url entirely when the composite action's input is empty rather than passing an empty value. So when that repository variable is unset but mint_url is set in config.yaml/config.base.yaml, fullsend run and the status notifier already mint from the file's endpoint inside real GitHub Actions runs with working OIDC - a live effect today, not only a future one, on that one path. Correct the mint_url row's Decision cell to describe this accurately. Signed-off-by: fmuntean Co-authored-by: Cursor --- docs/contributing/config-source-inventory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 1dd98d1e1b..41c61db793 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -110,7 +110,7 @@ The Go accessor layers these. The bash steps in `.github/workflows/reusable-disp | `runtime`, and per-agent `agents[].runtime` | Which runtime runs (`claude`, `pi`, `codex`, `dummy`) | `--runtime`, `FULLSEND_RUNTIME` (repository variable copied by `setup-agent-env.sh`), agent entry, repo `runtime:`, compiled `claude` | Flag, then `FULLSEND_RUNTIME`, then the agent entry, then repo `runtime:`, then `claude` (`docs/cli/run.md`) | `fullsend run` | File should win. Flag stays first. `FULLSEND_RUNTIME` stays as the fallback | Yes, for the fleet default. | | `agents[].model` | Model for one agent | `--model`, `FULLSEND_MODEL`, then `FULLSEND_PI_MODEL` or `FULLSEND_CODEX_MODEL` when that runtime is selected, agent entry, harness, frontmatter | Flag, then `FULLSEND_MODEL`, then the runtime-scoped alias, then the agent entry | `fullsend run` | File should win. Same fallback rule | The shared default can live on the base-file agent entry. | | `agents[].effort` | Effort for one agent | `--effort`, `FULLSEND_EFFORT`, agent entry, harness | Flag, then `FULLSEND_EFFORT`, then the agent entry | `fullsend run` | File should win. Same fallback rule | Same as model. | -| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | `fullsend run` and `reconcile-status --fullsend-dir`: flag, then layered `mint_url`, then `FULLSEND_MINT_URL` (`resolveMintURL`, #8400). Only `runAgent`'s agent-token mint downgrades a file-sourced value to warn-and-skip (ambient `GH_TOKEN`) when GitHub Actions OIDC is unavailable; `reconcile-status` and the status-comment mint still attempt it and fail — fail-closed for `reconcile-status`, a per-call warning for status comments. `mint token` has no `--fullsend-dir`, so it stays flag then env | `fullsend run`, `reconcile-status`, `mint token`. GitLab never mints | File should win: done for `run` and `reconcile-status`. Workflows still pass `mint-url` every stage, so the flag wins until the `route` job computes it from the file itself. `mint token` stays flag-then-env; it has no directory to layer from. The OIDC downgrade should extend to `reconcile-status` and status comments for consistency — tracked, not yet done | Yes. | +| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | `fullsend run` and `reconcile-status --fullsend-dir`: flag, then layered `mint_url`, then `FULLSEND_MINT_URL` (`resolveMintURL`, #8400). Only `runAgent`'s agent-token mint downgrades a file-sourced value to warn-and-skip (ambient `GH_TOKEN`) when GitHub Actions OIDC is unavailable; `reconcile-status` and the status-comment mint still attempt it and fail — fail-closed for `reconcile-status`, a per-call warning for status comments. `mint token` has no `--fullsend-dir`, so it stays flag then env | `fullsend run`, `reconcile-status`, `mint token`. GitLab never mints | File should win: done for `run` and `reconcile-status`. This has a live effect today, not only a future one: `action.yml` (`MINT_FLAGS`) omits `--mint-url` entirely when the composite action's `mint_url` input is empty, rather than passing an empty value, and the `prioritize` paths (`reusable-prioritize.yml` and the inlined `prioritize` job in `reusable-dispatch.yml`) have no upfront mint-token step gating on `FULLSEND_MINT_URL` the way triage/code/review/fix/retro/harness-run do. So when that repository variable is unset, those two paths (and any other composite-action caller that leaves `mint-url` empty) already mint — and notify — from a file-only `mint_url` inside real GitHub Actions runs with working OIDC. Every other dispatched stage still passes `mint-url` built from the possibly-stale variable, so the flag wins there until the `route` job computes the value from the file itself. `mint token` stays flag-then-env; it has no directory to layer from. The OIDC downgrade should extend to `reconcile-status` and status comments for consistency — tracked, not yet done. Confirming the mint endpoint serves the `prioritize` role wherever `mint_url` is file-only is tracked, not yet done (#8400 review) | Yes. | | `inference.region` | GCP region for inference | Layered `inference.region`, compiled `global`. Workflows pass `vars.FULLSEND_GCP_REGION` as `gcp_region`, which becomes `CLOUD_ML_REGION`. GitLab `run-agent-job.sh` exports `CLOUD_ML_REGION` from `FULLSEND_GCP_REGION` | The job environment, not the file. Setup writes the file's effective region into `FULLSEND_GCP_REGION` at install time. A later edit to the file does not change the variable | Vertex client via `CLOUD_ML_REGION`. The accessor is used at install and converge | File should win for the binary. Keep `FULLSEND_GCP_REGION` as the fallback and as the value old workflows still pass | Yes. | | `inference.project` | GCP project for inference | Layered `inference.project` (no compiled default), secret `FULLSEND_GCP_PROJECT_ID` | The secret. Workflows export it as `ANTHROPIC_VERTEX_PROJECT_ID`. `setup-gcp` uses the same secret to authenticate before the binary runs | Google auth action and the Vertex client | Leave the secret for the auth action. The file should be what the binary reads, with the secret as fallback. Do not put the secret value only in git if the auth action still needs it | Yes for the project id the binary uses. The secret remains for the auth action. | | `inference.wif_provider` | Workload Identity provider resource name | Layered `inference.wif_provider` (no compiled default), secret `FULLSEND_GCP_WIF_PROVIDER` | The secret. `setup-gcp` reads it | Google auth action | Leave the secret for the auth action. The file should describe the provider the binary needs. Same split as the project id | Yes for the non-secret resource name. The credential material stays a secret. | From 29713b072ee30d153654dec13dbaa3067a7db480 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Mon, 26 Oct 2026 20:47:27 +0100 Subject: [PATCH 7/8] fix(#8192): restore statusForgeClient arg dropped by merge conflict A merge from main left resolveBuiltInGitHubReviewCancellationGuidance's call missing its statusForgeClient argument (stray blank lines and a bare comma instead), breaking the build. Restores the argument. Signed-off-by: fmuntean Co-authored-by: Cursor --- internal/cli/reconcilestatus.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/internal/cli/reconcilestatus.go b/internal/cli/reconcilestatus.go index 31f0777c62..2318003d75 100644 --- a/internal/cli/reconcilestatus.go +++ b/internal/cli/reconcilestatus.go @@ -173,12 +173,7 @@ finalized, this is a no-op.`, if reviewRun && termReason == statuscomment.ReasonCancelled { var guidanceErr error guidance, guidanceErr = resolveBuiltInGitHubReviewCancellationGuidance( - cmd.Context(), - - - - , "review", forgePlatform, trackerSource, - project, number, sha, + cmd.Context(), statusForgeClient, "review", forgePlatform, trackerSource, project, number, sha, ) if guidanceErr != nil { fmt.Fprintf(os.Stderr, "WARNING: could not determine whether cancelled review was superseded; omitting retry guidance: %v\n", guidanceErr) From 55e3e7580b5dc072543aae1be4e91fdd257ad19a Mon Sep 17 00:00:00 2001 From: fmuntean Date: Wed, 28 Oct 2026 15:04:06 +0100 Subject: [PATCH 8/8] fix(cli): resolve mint_url via layered precedence in cancellation finalizer The built-in GitHub review cancellation finalizer minted its own status token via newStatusGitHubForgeClient(dCtx, sOpts.mintURL, ...), bypassing resolveMintURL's flag > layered config file > env precedence. A file-only mint_url minted against "" here even though the start comment correctly used config.yaml's value, and a file value competing with a different FULLSEND_MINT_URL would mint against the env endpoint instead of the file-selected one. Also update the --mint-url flag help text, which only described status-token minting and the env fallback, to cover agent-token minting and the layered config file source too. Adds regression tests for both scenarios (file-only mint_url, and file value winning over a competing env var) in the cancellation finalizer path. Refs #8192, #8400 Signed-off-by: fmuntean Co-authored-by: Cursor --- docs/guides/dev/cli-internals.md | 2 +- internal/cli/run.go | 12 ++- internal/cli/run_test.go | 155 +++++++++++++++++++++++++++++++ 3 files changed, 166 insertions(+), 3 deletions(-) diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index fd7b3ac8d9..34442d1fc3 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -134,7 +134,7 @@ fullsend │ ├── --run-url # CI/CD run URL for status comments │ ├── --status-repo # Repository for status comments │ ├── --status-number # Issue/PR number for status comments -│ └── --mint-url # Mint service URL for on-demand status tokens +│ └── --mint-url # Mint service URL for agent and status tokens (default: layered mint_url, then $FULLSEND_MINT_URL) ├── fetch-skill # Fetch a skill at runtime (in-sandbox) ├── scan # Run security scanner on input/output │ ├── input # Scan event payload for prompt injection diff --git a/internal/cli/run.go b/internal/cli/run.go index e25daebb4e..a008382dae 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -471,7 +471,7 @@ func newRunCmd() *cobra.Command { cmd.Flags().StringVar(&sOpts.statusRepo, "status-repo", "", "repository (owner/repo) for status comments") cmd.Flags().IntVar(&sOpts.statusNum, "status-number", 0, "issue/PR number for status comments") cmd.Flags().IntVar(&sOpts.statusComment, "status-comment-id", 0, "ID of the triggering comment, for comment-scoped reactions on slash-command runs (optional)") - cmd.Flags().StringVar(&sOpts.mintURL, "mint-url", "", "mint service URL for on-demand status tokens (default: $FULLSEND_MINT_URL)") + cmd.Flags().StringVar(&sOpts.mintURL, "mint-url", "", "mint service URL for agent and status tokens (default: layered mint_url from --fullsend-dir, then $FULLSEND_MINT_URL)") cmd.Flags().StringVar(&oFlags.runtime, "runtime", "", "override the agent runtime from config.yaml for this run (claude, pi, codex, opencode, dummy or dummy-playback; also $FULLSEND_RUNTIME)") cmd.Flags().StringVar(&oFlags.model, "model", "", "override the harness/agent model for this run (alias such as opus/sonnet/haiku, a model id, or provider/id on pi, codex, and opencode — codex takes OpenAI ids and gateway/ only; also $FULLSEND_MODEL)") cmd.Flags().StringVar(&oFlags.effort, "effort", "", "override the harness effort level for this run (low, medium, high, xhigh, max; also $FULLSEND_EFFORT)") @@ -1406,7 +1406,15 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep defer dCancel() if status == "cancelled" && builtInGitHubReview(agentName, forgePlatform, sOpts.trackerSource) { parts := strings.SplitN(sOpts.statusRepo, "/", 2) - client, err := newStatusGitHubForgeClient(dCtx, sOpts.mintURL, h.Role, parts[1]) + // Resolve through the same flag > layered config file > + // env precedence as setupStatusNotifierGitHub, not just + // flag > env: otherwise a file-only mint_url mints + // against "" here (even though the start comment above + // minted correctly), and a file value competing with a + // different FULLSEND_MINT_URL would mint against the + // env endpoint instead of the file-selected one (#8400). + cancelMintURL, _ := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) + client, err := newStatusGitHubForgeClient(dCtx, cancelMintURL, h.Role, parts[1]) if err == nil { // Reuse this freshly minted write client for completion so // cancellation cleanup does not spend time on a second mint. diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index a356080f89..15140fc9e6 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -8990,6 +8990,161 @@ func TestRunAgent_CancelledReviewUsesCurrentHeadGuidance(t *testing.T) { assert.NotContains(t, body, "/fs-review") } +// TestRunAgent_CancelledReviewMintsFromFileOnlyMintURL guards against a +// regression where the cancellation finalizer's own mint call (distinct +// from the start-comment mint set up by setupStatusNotifierGitHub) passed +// the raw --mint-url flag value straight to newStatusGitHubForgeClient +// instead of resolving it through the same flag > layered config file > +// FULLSEND_MINT_URL precedence as everywhere else. With no flag and no env +// var, that bug minted against "" for the finalizer even though the start +// comment (and the agent-token mint) correctly used config.yaml's mint_url +// (#8400). +func TestRunAgent_CancelledReviewMintsFromFileOnlyMintURL(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "review.md"), + []byte("You are a review agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "review.yaml"), + []byte("agent: agents/review.md\nrole: review\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/review.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + origNewClient := statusNewForgeClientFn + t.Cleanup(func() { + statusMintToken = origMint + statusNewForgeClientFn = origNewClient + }) + var mintCalls int + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalls++ + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, + "call #%d (role=%s, level=%s) must use config.yaml's mint_url, not \"\"", mintCalls, req.Role, req.Level) + return &mintclient.MintResult{Token: "ghs_test_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cancel() + fc := forge.NewFakeClient() + fc.PullRequestHeadSHA = "new-head" + statusNewForgeClientFn = func(token string) forge.Client { + assert.Equal(t, "ghs_test_token", token) + return fc + } + + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("PR_HEAD_SHA", "cancelled-head") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + t.Setenv("FULLSEND_MINT_URL", "") + + var buf bytes.Buffer + // No --mint-url flag: statusOpts.mintURL is left empty so the only + // source of a mint URL is config.yaml's layered mint_url. + err := runAgent(ctx, "review", dir, "", t.TempDir(), "", nil, false, "", "github", "", resolveFlags{maxDepth: 10, maxResources: 50}, statusOpts{ + statusRepo: "org/my-repo", + statusNum: 42, + trackerSource: "github", + }, ui.New(&buf), false, runOverrideFlags{}) + require.Error(t, err) + comments := fc.IssueComments["org/my-repo/42"] + require.NotEmpty(t, comments, "output: %s; all comments: %#v", buf.String(), fc.IssueComments) + body := comments[len(comments)-1].Body + assert.Contains(t, body, "superseded by a newer commit") + // At least the start-comment mint and the finalizer mint must both + // have happened for this regression to be meaningfully covered. + assert.GreaterOrEqual(t, mintCalls, 2, "expected both the start-comment mint and the cancellation-finalizer mint to occur") +} + +// TestRunAgent_CancelledReviewFileMintURLWinsOverEnv guards against the +// same cancellation-finalizer bug as above, but for the case where a +// competing FULLSEND_MINT_URL is also set: the finalizer must mint against +// config.yaml's mint_url (matching the start comment), not silently fall +// back to the env var (#8400). +func TestRunAgent_CancelledReviewFileMintURLWinsOverEnv(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "review.md"), + []byte("You are a review agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "review.yaml"), + []byte("agent: agents/review.md\nrole: review\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/review.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + origNewClient := statusNewForgeClientFn + t.Cleanup(func() { + statusMintToken = origMint + statusNewForgeClientFn = origNewClient + }) + var mintCalls int + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalls++ + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, + "call #%d (role=%s, level=%s) must use config.yaml's mint_url, not the competing FULLSEND_MINT_URL", mintCalls, req.Role, req.Level) + return &mintclient.MintResult{Token: "ghs_test_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cancel() + fc := forge.NewFakeClient() + fc.PullRequestHeadSHA = "new-head" + statusNewForgeClientFn = func(token string) forge.Client { + assert.Equal(t, "ghs_test_token", token) + return fc + } + + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("PR_HEAD_SHA", "cancelled-head") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + // A stale/different value in the environment — simulating a + // repository variable set at install time that the file has since + // overridden without anyone updating the variable. + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + + var buf bytes.Buffer + err := runAgent(ctx, "review", dir, "", t.TempDir(), "", nil, false, "", "github", "", resolveFlags{maxDepth: 10, maxResources: 50}, statusOpts{ + statusRepo: "org/my-repo", + statusNum: 42, + trackerSource: "github", + }, ui.New(&buf), false, runOverrideFlags{}) + require.Error(t, err) + comments := fc.IssueComments["org/my-repo/42"] + require.NotEmpty(t, comments, "output: %s; all comments: %#v", buf.String(), fc.IssueComments) + body := comments[len(comments)-1].Body + assert.Contains(t, body, "superseded by a newer commit") + assert.GreaterOrEqual(t, mintCalls, 2, "expected both the start-comment mint and the cancellation-finalizer mint to occur") +} + type runStatusEventWriter func(string) func (w runStatusEventWriter) Write(p []byte) (int, error) {