diff --git a/changelog.d/added-contributor-first-settings.md b/changelog.d/added-contributor-first-settings.md new file mode 100644 index 0000000000..c9b2902b95 --- /dev/null +++ b/changelog.d/added-contributor-first-settings.md @@ -0,0 +1 @@ +- Settings: the agent's General tab now has **Contributor-first** and **Contributor-first grace** controls for `agents..contributor_first` and `contributor_first_grace`, so a hive owner (including on a hub-hosted spoke) can switch a lane to contributor-first without editing `hive.yaml`. The toggle is disabled, with the fix named, for a role contributors may not act as; a save is refused with the same message the load would give, and takes effect on the next governor evaluation without a restart. diff --git a/dashboard/test/contributor-first-general.test.js b/dashboard/test/contributor-first-general.test.js new file mode 100644 index 0000000000..7d0340b78f --- /dev/null +++ b/dashboard/test/contributor-first-general.test.js @@ -0,0 +1,145 @@ +'use strict'; + +// The agent's General tab controls for the contributor-first lane keys +// (agents..contributor_first and contributor_first_grace, #16518). The +// toggle must show the stored state, carry its help mark, and be disabled with +// the fix named when the role is not one contributors may act as. The grace +// field shows the stored value and saves seconds, blank clearing to 10m. + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const indexHtml = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'pkg', 'dashboard', 'static', 'index.html'), 'utf8'); + +function extractFunction(name) { + const start = indexHtml.indexOf('function ' + name + '('); + assert.notEqual(start, -1, `${name} function exists`); + const brace = indexHtml.indexOf('{', start); + let depth = 0; + for (let i = brace; i < indexHtml.length; i++) { + const ch = indexHtml[i]; + if (ch === '{') depth++; + if (ch === '}') depth--; + if (depth === 0) return indexHtml.slice(start, i + 1); + } + throw new Error(`unterminated ${name}`); +} + +// Everything renderAgentGeneral touches that this test does not exercise +// resolves to a black hole: callable, any property is another black hole, and +// it prints as ''. The functions under test are the real ones from index.html. +const blackHole = new Proxy(function () {}, { + get: (_t, key) => (key === Symbol.toPrimitive ? () => '' : blackHole), + apply: () => blackHole, +}); + +const realSrc = ['renderAgentGeneral', 'agentContributorFirstControlsHtml', 'settingHelpMark', 'yamlHint', 'esc', 'cadenceToHuman'] + .map(extractFunction).join('\n'); + +function renderGeneral(g, agent) { + const own = { + _configState: { agent, isCreate: false }, + window: { _lastAgents: [], _lastStatus: {} }, + settingHelpSeq: 0, + dashboardDocsHref: (page, anchor) => '/docs/' + page + '#' + anchor, + setTimeout: () => {}, + SECONDS_PER_MIN: 60, + SECONDS_PER_HOUR: 3600, + SECONDS_PER_DAY: 86400, + }; + const passthrough = new Set(['String', 'Number', 'Boolean', 'Array', 'Object', 'JSON', 'Math', 'parseInt', 'parseFloat', 'isNaN', 'undefined', 'Symbol', 'Date', 'RegExp', 'Error', 'encodeURIComponent']); + const scope = new Proxy(own, { + has: (target, key) => !passthrough.has(key), + get: (target, key) => (key === Symbol.unscopables ? undefined : key in target ? target[key] : blackHole), + set: (target, key, value) => { target[key] = value; return true; }, + }); + // eslint-disable-next-line no-new-func + const render = new Function('scope', 'with (scope) { ' + realSrc + '\n return renderAgentGeneral; }')(scope); + return render(g); +} + +function toggle(html) { + const m = html.match(/
]*>/); + assert.ok(m, 'contributor-first toggle rendered'); + return m[0]; +} + +function helpMarks(html, label) { + return html.match(new RegExp(']*aria-label="Help: ' + label + '"', 'g')) || []; +} + +test('toggle on for a delegatable role, with help marks on both controls', () => { + const html = renderGeneral({ contributorFirst: true, contributorFirstGrace: 900, contributorFirstDelegatable: true }, 'scanner'); + const t = toggle(html); + assert.match(t, /config-toggle-switch on /); + assert.doesNotMatch(t, /class="[^"]*\bdisabled\b/); + assert.match(t, /data-action="toggleConfigSwitch"/); + assert.match(t, /data-key="contributorFirst"/); + assert.equal(helpMarks(html, 'Contributor-first').length, 1, 'toggle help mark'); + assert.equal(helpMarks(html, 'Contributor-first grace').length, 1, 'grace help mark'); + for (const phrase of ["primary worker and the resident agent's kicks are withheld", 'Kicks resume on the normal cadence', 'Budget pause and standby are unaffected', 'a manual Kick still works']) { + assert.ok(html.includes(phrase), `toggle help says: ${phrase}`); + } + assert.match(html, /id="cfg-contributor-first-grace" value="15m" placeholder="10m" data-change-action="contributorFirstGraceChanged"/); + assert.doesNotMatch(html, /id="cfg-contributor-first-disabled"/); + assert.match(html, /agents\.<key>\.contributor_first<\/code>/); +}); + +test('toggle off for a delegatable role; unset grace shows the placeholder', () => { + const html = renderGeneral({ contributorFirst: false, contributorFirstGrace: 0, contributorFirstDelegatable: true }, 'quality'); + const t = toggle(html); + assert.doesNotMatch(t, /config-toggle-switch on /); + assert.match(t, /data-action="toggleConfigSwitch"/); + assert.match(t, /data-disabled="false"/); + assert.match(html, /id="cfg-contributor-first-grace" value="" placeholder="10m"/); + assert.doesNotMatch(html, /id="cfg-contributor-first-disabled"/); +}); + +test('non-delegatable role: toggle disabled and the fix named', () => { + const html = renderGeneral({ contributorFirst: false, contributorFirstDelegatable: false }, 'architect'); + const t = toggle(html); + assert.match(t, /class="[^"]*\bdisabled\b/); + assert.match(t, /data-action=""/); + assert.match(t, /data-disabled="true"/); + const reason = html.match(/
]*>([\s\S]*?)<\/div>/); + assert.ok(reason, 'disabled reason rendered'); + assert.match(reason[1], /add architect<\/code> to hub\.contribute_delegatable_roles<\/code>/); + assert.equal(helpMarks(html, 'Contributor-first').length, 1, 'help mark still rendered when disabled'); +}); + +test('supervisor names why it can never be delegated', () => { + const html = renderGeneral({ contributorFirstDelegatable: false }, 'supervisor'); + assert.match(html, /id="cfg-contributor-first-disabled"[^>]*>The supervisor role is never delegatable to contributors\. { + const own = { _configState: { agent: '', isCreate: true } }; + const passthrough = new Set(['String', 'Number', 'Boolean', 'Array', 'Object', 'JSON', 'Math', 'parseInt', 'parseFloat', 'isNaN', 'undefined', 'Symbol']); + const base = { window: { _lastAgents: [] }, settingHelpSeq: 0, dashboardDocsHref: () => '#', setTimeout: () => {}, SECONDS_PER_MIN: 60, SECONDS_PER_HOUR: 3600, SECONDS_PER_DAY: 86400 }; + const target = Object.assign(base, own); + const scope = new Proxy(target, { + has: (t, key) => !passthrough.has(key), + get: (t, key) => (key === Symbol.unscopables ? undefined : key in t ? t[key] : blackHole), + set: (t, key, value) => { t[key] = value; return true; }, + }); + const render = new Function('scope', 'with (scope) { ' + realSrc + '\n return renderAgentGeneral; }')(scope); + assert.doesNotMatch(render({}), /cfg-contributor-first/); +}); + +test('grace field saves seconds; blank or unparseable clears to the default', () => { + const line = indexHtml.split('\n').find(l => l.includes('contributorFirstGraceChanged: function')); + assert.ok(line, 'grace change handler exists'); + const body = line.trim().replace(/,$/, ''); + const cadenceFromHuman = new Function('SECONDS_PER_MIN', 'SECONDS_PER_HOUR', 'SECONDS_PER_DAY', extractFunction('cadenceFromHuman') + '; return cadenceFromHuman;')(60, 3600, 86400); + const cadenceToHuman = new Function('SECONDS_PER_MIN', 'SECONDS_PER_HOUR', 'SECONDS_PER_DAY', extractFunction('cadenceToHuman') + '; return cadenceToHuman;')(60, 3600, 86400); + for (const [input, secs, shown] of [['15m', 900, '15m'], ['90s', 90, '90s'], ['1h', 3600, '1h'], ['', 0, ''], ['-5m', 0, ''], ['soon', 0, '']]) { + const dirty = []; + const handlers = new Function('markDirty', 'cadenceFromHuman', 'cadenceToHuman', 'return {' + body + '};')((section, key, value) => dirty.push([section, key, value]), cadenceFromHuman, cadenceToHuman); + const el = { value: input }; + handlers.contributorFirstGraceChanged.call(el, {}, []); + assert.deepEqual(dirty, [['general', 'contributorFirstGrace', secs]], `input ${JSON.stringify(input)}`); + assert.equal(el.value, shown, `input ${JSON.stringify(input)} is shown back as ${JSON.stringify(shown)}`); + } +}); diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index fbecbcc892..97f84f585e 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -1302,6 +1302,8 @@ agents: | `contributor_first` | Make a connected contributor relay acting as this role the lane's primary worker, and withhold the resident agent's kicks while one is connected. Default off; an absent key changes nothing. **The role must be one contributors may act as** — in `hub.contribute_delegatable_roles`, or one of the default `scanner`, `quality`, `outreach` — or the load fails: a contributor-first lane nobody may claim would sit inert while you believe contributors are taking the load. `supervisor` is never delegatable and is rejected. | | `contributor_first_grace` | How long kicks stay withheld after the last covering relay disappears. Default **10m**; negative fails the load. | +Both keys are also on the agent's **General** tab in Settings (**Contributor-first** and **Contributor-first grace**), so a hive owner can switch a lane without editing `hive.yaml`; the save refuses exactly what the load refuses, with the same message, and takes effect on the next governor evaluation without a restart. + What you see: the Governor section gains a **contributor-first** tile naming each covered lane and who covers it ("quality covered by alice, resident kicks withheld"), and during the grace it says when the resident agent resumes. diff --git a/src/docs/contributor-trust-and-roles.md b/src/docs/contributor-trust-and-roles.md index dd7579b435..ca8a8e5e6e 100644 --- a/src/docs/contributor-trust-and-roles.md +++ b/src/docs/contributor-trust-and-roles.md @@ -128,4 +128,4 @@ If the list is empty, Hive uses the safe default: `scanner`, `quality`, and `out ### Making the contributor the primary worker (`contributor_first`) -A delegated role runs **in parallel** with the hive's resident agent by default: the relay takes issues from the role's lane while the governor keeps kicking the resident agent, so the hive's own inference budget is still spent on that lane. To let contributors take the load *first*, set `contributor_first: true` on the agent. While at least one connected, healthy relay is acting as that role, the governor withholds the resident agent's kicks; once no relay has covered the role for `contributor_first_grace` (default 10m) the resident agent resumes on its normal cadence. The role must be delegatable (listed in `hub.contribute_delegatable_roles`, or one of the defaults), or the hive refuses to load. Budget pause and standby are unchanged — a covered lane is never reported as paused for budget. Details and the exact rules are in [Contributor-first lanes](agent-configuration.md#contributor-first-lanes-contributor_first). +A delegated role runs **in parallel** with the hive's resident agent by default: the relay takes issues from the role's lane while the governor keeps kicking the resident agent, so the hive's own inference budget is still spent on that lane. To let contributors take the load *first*, set `contributor_first: true` on the agent. While at least one connected, healthy relay is acting as that role, the governor withholds the resident agent's kicks; once no relay has covered the role for `contributor_first_grace` (default 10m) the resident agent resumes on its normal cadence. The role must be delegatable (listed in `hub.contribute_delegatable_roles`, or one of the defaults), or the hive refuses to load. Budget pause and standby are unchanged — a covered lane is never reported as paused for budget. The agent's **General** tab in Settings exposes both `contributor_first` and `contributor_first_grace`, so this needs no `hive.yaml` edit. Details and the exact rules are in [Contributor-first lanes](agent-configuration.md#contributor-first-lanes-contributor_first). diff --git a/src/pkg/config/contributor_first.go b/src/pkg/config/contributor_first.go index 3dd3e33a86..46998271db 100644 --- a/src/pkg/config/contributor_first.go +++ b/src/pkg/config/contributor_first.go @@ -17,30 +17,47 @@ import ( // load fails and names the fix. func (c *Config) validateContributorFirst() error { for _, name := range sortedAgentNames(c.Agents) { - agent := c.Agents[name] - label := agentSourceLabel(name, agent.SourceFile()) - if agent.ContributorFirstGrace < 0 { - return fmt.Errorf("agent %s: contributor_first_grace must not be negative (got %s; omit it for the default %s)", - label, agent.ContributorFirstGrace, DefaultContributorFirstGrace) - } - if !agent.ContributorFirst { - continue - } - role := strings.ToLower(strings.TrimSpace(name)) - // Relays request roles in lower case and the hub looks the agent up by - // that spelling (contribute_agent_roles.go), so a contributor-first - // agent with a mixed-case name could never be covered. Reject it for - // the same reason as an undelegatable role: the flag would be inert. - if role != name { - return fmt.Errorf("agent %s: contributor_first is true but the agent name is not lower-case — relays claim roles in lower case, so %q could never be covered", label, name) - } - if role == "supervisor" { - return fmt.Errorf("agent %s: contributor_first is true but the supervisor role is never delegatable to contributors", label) - } - if !c.Hub.IsContributeRoleDelegatable(role) { - return fmt.Errorf("agent %s: contributor_first is true but %q is not a role contributors may act as — add it to hub.contribute_delegatable_roles (the default list is scanner, quality and outreach)", - label, role) + if err := ValidateContributorFirstAgent(name, c.Agents[name], c.Hub); err != nil { + return err } } return nil } + +// ValidateContributorFirstAgent checks one agent's contributor-first keys +// against the hub block. It is the per-agent body of validateContributorFirst, +// exported so the dashboard's General-tab save refuses exactly what a load +// would, with the same message. +func ValidateContributorFirstAgent(name string, agent AgentConfig, hub HubConfig) error { + label := agentSourceLabel(name, agent.SourceFile()) + if agent.ContributorFirstGrace < 0 { + return fmt.Errorf("agent %s: contributor_first_grace must not be negative (got %s; omit it for the default %s)", + label, agent.ContributorFirstGrace, DefaultContributorFirstGrace) + } + if !agent.ContributorFirst { + return nil + } + role := strings.ToLower(strings.TrimSpace(name)) + // Relays request roles in lower case and the hub looks the agent up by + // that spelling (contribute_agent_roles.go), so a contributor-first + // agent with a mixed-case name could never be covered. Reject it for + // the same reason as an undelegatable role: the flag would be inert. + if role != name { + return fmt.Errorf("agent %s: contributor_first is true but the agent name is not lower-case — relays claim roles in lower case, so %q could never be covered", label, name) + } + if role == "supervisor" { + return fmt.Errorf("agent %s: contributor_first is true but the supervisor role is never delegatable to contributors", label) + } + if !hub.IsContributeRoleDelegatable(role) { + return fmt.Errorf("agent %s: contributor_first is true but %q is not a role contributors may act as — add it to hub.contribute_delegatable_roles (the default list is scanner, quality and outreach)", + label, role) + } + return nil +} + +// ContributorFirstDelegatable reports whether contributor_first could be +// turned on for the agent named name: the same name and role rules +// ValidateContributorFirstAgent applies, without the grace check. +func ContributorFirstDelegatable(name string, hub HubConfig) bool { + return ValidateContributorFirstAgent(name, AgentConfig{ContributorFirst: true}, hub) == nil +} diff --git a/src/pkg/config/contributor_first_test.go b/src/pkg/config/contributor_first_test.go index a0b3548ba7..baaacb0eab 100644 --- a/src/pkg/config/contributor_first_test.go +++ b/src/pkg/config/contributor_first_test.go @@ -104,3 +104,49 @@ func TestContributorFirstGraceOrDefault(t *testing.T) { t.Errorf("negative grace (never loaded, hand-built) = %v, want default %v", got, DefaultContributorFirstGrace) } } + +// The dashboard's General-tab save calls ValidateContributorFirstAgent; a +// refusal there must read exactly like the load error, so the operator sees +// one message whichever way the key was set. +func TestValidateContributorFirstAgent_MatchesLoadError(t *testing.T) { + cases := map[string]AgentConfig{ + "architect": {Backend: "claude", ContributorFirst: true}, + "supervisor": {Backend: "claude", ContributorFirst: true}, + "Scanner": {Backend: "claude", ContributorFirst: true}, + "quality": {Backend: "claude", ContributorFirstGrace: -time.Minute}, + } + for name, agent := range cases { + t.Run(name, func(t *testing.T) { + c := contributorFirstConfig(map[string]AgentConfig{name: agent}) + loadErr := c.validateContributorFirst() + apiErr := ValidateContributorFirstAgent(name, agent, c.Hub) + if loadErr == nil || apiErr == nil { + t.Fatalf("want both to fail, got load=%v api=%v", loadErr, apiErr) + } + if loadErr.Error() != apiErr.Error() { + t.Fatalf("messages differ:\nload: %s\napi: %s", loadErr, apiErr) + } + }) + } + if err := ValidateContributorFirstAgent("scanner", AgentConfig{ContributorFirst: true, ContributorFirstGrace: 0}, HubConfig{}); err != nil { + t.Fatalf("default-delegatable scanner with zero grace: %v", err) + } +} + +func TestContributorFirstDelegatable(t *testing.T) { + hub := HubConfig{ContributeDelegatableRoles: []string{"ci-maintainer", "supervisor"}} + for name, want := range map[string]bool{ + "scanner": true, // the defaults always apply; the list adds to them + "ci-maintainer": true, + "architect": false, + "supervisor": false, // never delegatable, even when listed + "Scanner": false, + } { + if got := ContributorFirstDelegatable(name, hub); got != want { + t.Errorf("ContributorFirstDelegatable(%q) = %v, want %v", name, got, want) + } + } + if !ContributorFirstDelegatable("outreach", HubConfig{}) { + t.Error("outreach is in the default delegatable list") + } +} diff --git a/src/pkg/dashboard/agent_config_contributor_first_test.go b/src/pkg/dashboard/agent_config_contributor_first_test.go new file mode 100644 index 0000000000..d092c405e7 --- /dev/null +++ b/src/pkg/dashboard/agent_config_contributor_first_test.go @@ -0,0 +1,197 @@ +package dashboard + +import ( + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/governor" +) + +// The contributor-first lane keys (agents..contributor_first and +// contributor_first_grace, #16518) were hive.yaml-only, so on a hub-hosted +// spoke only the hub operator could switch a lane over. The agent's General +// tab now reads and writes both, refusing exactly what a load would refuse. + +func generalSection(t *testing.T, s *Server, agent string) map[string]interface{} { + t.Helper() + rec := doGet(s, "/api/config/agent/"+agent) + if rec.Code != http.StatusOK { + t.Fatalf("GET status = %d, want 200: %s", rec.Code, rec.Body.String()) + } + general, ok := decodeJSON(t, rec)["general"].(map[string]interface{}) + if !ok { + t.Fatal("response has no general section") + } + return general +} + +func TestAgentConfigGet_ExposesContributorFirst(t *testing.T) { + s, deps := apiServer(t) + cfg := deps.Config.Agents["scanner"] + cfg.ContributorFirst = true + cfg.ContributorFirstGrace = 15 * time.Minute + deps.Config.Agents["scanner"] = cfg + deps.Config.Agents["architect"] = config.AgentConfig{Backend: "claude", Enabled: true} + + g := generalSection(t, s, "scanner") + if g["contributorFirst"] != true { + t.Errorf("contributorFirst = %v, want true", g["contributorFirst"]) + } + if g["contributorFirstGrace"] != float64(900) { + t.Errorf("contributorFirstGrace = %v, want 900 seconds", g["contributorFirstGrace"]) + } + if g["contributorFirstDelegatable"] != true { + t.Errorf("scanner is a default delegatable role; contributorFirstDelegatable = %v", g["contributorFirstDelegatable"]) + } + + // Presence matters for the unset case too: the panel renders 0 as the + // default placeholder and needs the delegatable flag to disable the toggle. + g = generalSection(t, s, "architect") + for key, want := range map[string]interface{}{"contributorFirst": false, "contributorFirstGrace": float64(0), "contributorFirstDelegatable": false} { + v, present := g[key] + if !present || v != want { + t.Errorf("architect general.%s = %v (present %v), want %v", key, v, present, want) + } + } +} + +func TestAgentConfigGeneral_SetsContributorFirstAndGrace(t *testing.T) { + s, deps := apiServer(t) + deps.Config.Data.AgentsDir = t.TempDir() + + rec := doPut(s, "/api/config/agent/scanner/general", map[string]any{"contributorFirst": true, "contributorFirstGrace": 300}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String()) + } + got := deps.Config.Agents["scanner"] + if !got.ContributorFirst || got.ContributorFirstGrace != 5*time.Minute { + t.Fatalf("stored contributor_first=%v grace=%s, want true and 5m", got.ContributorFirst, got.ContributorFirstGrace) + } + overlay, err := os.ReadFile(filepath.Join(deps.Config.Data.AgentsDir, "scanner.yaml")) + if err != nil { + t.Fatalf("agent overlay not written: %v", err) + } + if !strings.Contains(string(overlay), "contributor_first: true") || !strings.Contains(string(overlay), "contributor_first_grace: 5m0s") { + t.Errorf("agent overlay does not carry both keys:\n%s", overlay) + } + + // GET round-trips what was saved. + g := generalSection(t, s, "scanner") + if g["contributorFirst"] != true || g["contributorFirstGrace"] != float64(300) { + t.Errorf("GET after save: contributorFirst=%v grace=%v", g["contributorFirst"], g["contributorFirstGrace"]) + } + + // 0 clears the stored grace, so the governor falls back to the default. + rec = doPut(s, "/api/config/agent/scanner/general", map[string]any{"contributorFirstGrace": 0}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String()) + } + got = deps.Config.Agents["scanner"] + if got.ContributorFirstGrace != 0 || got.ContributorFirstGraceOrDefault() != config.DefaultContributorFirstGrace { + t.Errorf("grace 0 must clear to the default, got stored %s effective %s", got.ContributorFirstGrace, got.ContributorFirstGraceOrDefault()) + } + if !got.ContributorFirst { + t.Error("a save that only clears the grace must keep contributor_first") + } +} + +// The save updates the governor in place (UpdateAgents), so a lane switched +// on from the panel is withheld on the next evaluation once a relay covers +// the role — no restart. +func TestAgentConfigGeneral_ContributorFirstReachesGovernor(t *testing.T) { + s, deps := apiServer(t) + deps.Governor.SetContributorCoverage(map[string]governor.ContributorCoverage{"scanner": {Contributors: []string{"alice"}}}) + deps.Governor.Evaluate(0, 0, 0, 0) + if len(deps.Governor.GetState().CoveredLanes) != 0 { + t.Fatal("without the flag a covered role must not be reported as a covered lane") + } + + rec := doPut(s, "/api/config/agent/scanner/general", map[string]any{"contributorFirst": true}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String()) + } + deps.Governor.SetContributorCoverage(map[string]governor.ContributorCoverage{"scanner": {Contributors: []string{"alice"}}}) + deps.Governor.Evaluate(0, 0, 0, 0) + cov, ok := deps.Governor.GetState().CoveredLanes["scanner"] + if !ok || len(cov.Contributors) != 1 || cov.Contributors[0] != "alice" { + t.Fatalf("CoveredLanes = %+v, want scanner covered by alice after the save", deps.Governor.GetState().CoveredLanes) + } +} + +// A refusal answers 400 with the load's own message and changes nothing, in +// memory or on disk. +func TestAgentConfigGeneral_RefusesWhatTheLoadRefuses(t *testing.T) { + cases := []struct { + name string + agent string + body map[string]any + }{ + {"role not delegatable", "architect", map[string]any{"contributorFirst": true}}, + {"supervisor", "supervisor", map[string]any{"contributorFirst": true}}, + {"negative grace", "scanner", map[string]any{"contributorFirstGrace": -60}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s, deps := apiServer(t) + deps.Config.Data.AgentsDir = t.TempDir() + if _, ok := deps.Config.Agents[tc.agent]; !ok { + deps.Config.Agents[tc.agent] = config.AgentConfig{Backend: "claude", Enabled: true} + } + before := deps.Config.Agents[tc.agent] + + body := map[string]any{"displayName": "Renamed"} + for k, v := range tc.body { + body[k] = v + } + rec := doPut(s, "/api/config/agent/"+tc.agent+"/general", body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", rec.Code, rec.Body.String()) + } + + attempted := before + if v, ok := tc.body["contributorFirst"].(bool); ok { + attempted.ContributorFirst = v + } + if v, ok := tc.body["contributorFirstGrace"].(int); ok { + attempted.ContributorFirstGrace = time.Duration(v) * time.Second + } + want := config.ValidateContributorFirstAgent(tc.agent, attempted, deps.Config.Hub) + if want == nil { + t.Fatal("test case must be one the load refuses") + } + if msg := decodeJSON(t, rec)["error"]; msg != want.Error() { + t.Errorf("error = %q, want the load's message %q", msg, want.Error()) + } + + after := deps.Config.Agents[tc.agent] + if after.ContributorFirst != before.ContributorFirst || after.ContributorFirstGrace != before.ContributorFirstGrace || after.DisplayName != before.DisplayName { + t.Errorf("a refused save changed the agent: before %+v after %+v", before, after) + } + if entries, _ := os.ReadDir(deps.Config.Data.AgentsDir); len(entries) != 0 { + t.Errorf("a refused save wrote %d file(s) to the agents dir", len(entries)) + } + }) + } +} + +func TestAgentConfigGeneral_OmittedContributorFirstIsPreserved(t *testing.T) { + s, deps := apiServer(t) + cfg := deps.Config.Agents["scanner"] + cfg.ContributorFirst = true + cfg.ContributorFirstGrace = 20 * time.Minute + deps.Config.Agents["scanner"] = cfg + + rec := doPut(s, "/api/config/agent/scanner/general", map[string]any{"displayName": "Scanner"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String()) + } + got := deps.Config.Agents["scanner"] + if !got.ContributorFirst || got.ContributorFirstGrace != 20*time.Minute { + t.Errorf("a save that omits both keys must keep them, got contributor_first=%v grace=%s", got.ContributorFirst, got.ContributorFirstGrace) + } +} diff --git a/src/pkg/dashboard/api_agent_config.go b/src/pkg/dashboard/api_agent_config.go index d6df524d01..a0e47d9c67 100644 --- a/src/pkg/dashboard/api_agent_config.go +++ b/src/pkg/dashboard/api_agent_config.go @@ -162,6 +162,13 @@ func (s *Server) handleAgentConfigGet(w http.ResponseWriter, r *http.Request) { "definitionSource": agentCfg.DefinitionSource, "mode": agentCfg.Mode, "includeRepos": includeRepos, + // Contributor-first lane keys (#16518). The grace is seconds, 0 when + // unset (the governor then uses DefaultContributorFirstGrace); + // contributorFirstDelegatable says whether the toggle can be turned + // on at all, so the panel can disable it and name the fix. + "contributorFirst": agentCfg.ContributorFirst, + "contributorFirstGrace": int64(agentCfg.ContributorFirstGrace.Seconds()), + "contributorFirstDelegatable": config.ContributorFirstDelegatable(name, s.deps.Config.Hub), // The agent's repository scope (#6204), plus the hive's own repo // list so the dialog can offer real choices instead of a free-text // field the operator has to spell from memory. @@ -423,6 +430,29 @@ func (s *Server) handleAgentConfigGeneral(w http.ResponseWriter, r *http.Request agentCfg.OnDemandOwner = config.FieldOwnerOperator } } + // Contributor-first lane keys (#16518). Judged on this copy by the same + // rule the load applies, before anything below can persist a side effect, + // so a refusal answers 400 with the load's own message and saves nothing. + // 0 seconds clears the grace back to the default. A save that carries + // neither key is not judged on them. + _, cfSet := body["contributorFirst"] + _, cfGraceSet := body["contributorFirstGrace"] + if v, ok := body["contributorFirst"]; ok { + if b, ok := v.(bool); ok { + agentCfg.ContributorFirst = b + } + } + if v, ok := body["contributorFirstGrace"]; ok { + if f, ok := v.(float64); ok { + agentCfg.ContributorFirstGrace = time.Duration(int64(f)) * time.Second + } + } + if cfSet || cfGraceSet { + if err := config.ValidateContributorFirstAgent(name, agentCfg, s.deps.Config.Hub); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + } if v, ok := body["continuous"]; ok { if b, ok := v.(bool); ok { agentCfg.Continuous = b diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 9ddc121b22..6806193f97 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -578,8 +578,6 @@ agents..advisor.instructions # TODO #11854 agents..advisor.max_consecutive_blocks # TODO #11854 agents..advisor.model # TODO #11854 agents..advisor.timeout_s # TODO #11854 -agents..contributor_first # TODO #11854 -agents..contributor_first_grace # TODO #11854 agents..mode_owner # TODO #11854 agents..standby.auto_dispatch # TODO #11854 agents..standby.daily_cap_per_contributor # TODO #11854 diff --git a/src/pkg/dashboard/static-src/js/config-agent.js b/src/pkg/dashboard/static-src/js/config-agent.js index b1c1849f58..a60bb81207 100644 --- a/src/pkg/dashboard/static-src/js/config-agent.js +++ b/src/pkg/dashboard/static-src/js/config-agent.js @@ -1,4 +1,32 @@ // ── Agent Tab Renderers ── + // Contributor-first lane keys (agents..contributor_first and + // contributor_first_grace, #16518). The toggle can only be turned on for a + // role contributors may act as, the same rule the load enforces; the + // server says which (contributorFirstDelegatable), and a role that is not + // gets a disabled toggle and the one line that names the fix. + function agentContributorFirstControlsHtml(g, agentName) { + const delegatable = g.contributorFirstDelegatable === true; + const on = g.contributorFirst === true; + const name = String(agentName || ''); + let why = ''; + if (!delegatable) { + if (name === 'supervisor') why = 'The supervisor role is never delegatable to contributors.'; + else if (name !== name.toLowerCase()) why = 'Relays claim roles in lower case, so an agent whose name has capitals cannot be covered.'; + else why = `Not available: add ${esc(name)} to hub.contribute_delegatable_roles so contributors may act as this role.`; + } + const tip = `When on, a connected contributor relay acting as this role becomes the lane's primary worker and the resident agent's kicks are withheld. Kicks resume on the normal cadence once no relay has covered the role for the grace below. Budget pause and standby are unaffected, and a manual Kick still works. The role must be one contributors may act as (hub.contribute_delegatable_roles, or the default scanner, quality and outreach).`; + const graceTip = `How long the resident agent's kicks stay withheld after the last relay covering this role disconnects, so a relay can reconnect without the resident agent being kicked in between. Use s, m or h, e.g. 10m. Leave blank for the default, 10m.`; + const grace = Number(g.contributorFirstGrace) || 0; + return `
+
+ Contributor-first ${yamlHint('agents..contributor_first')} ${settingHelpMark('agent-configuration', 'contributor-first-lanes-contributor_first', 'Contributor-first', tip)} +
+ ${delegatable ? '' : `
${why}
`} +
+ + +
`; + } function renderAgentGeneral(g) { const agentName = _configState.agent || ''; const isCreate = _configState.isCreate === true; @@ -138,6 +166,7 @@
On Demand ${settingHelpMark('agent-configuration', 'anatomy-of-an-agent', 'On Demand', `When on, this agent is never started at boot and never kicked by the governor or by event (CEL) triggers — it only runs when something summons it explicitly. Turn it OFF to make the agent run on its cadence like a normal agent. Note: an agent also needs a cadence entry in the ACTIVE governor mode before it will actually be kicked. On-demand agents are also excluded from review fan-out, so a reviewer left on-demand cannot be dispatched.`)}${g.onDemand === true ? ' ' + statusBadgeHTML('on_demand', 'on demand', '', '') : ''}
+ ${isCreate ? '' : agentContributorFirstControlsHtml(g, agentName)}
Include Repos in Kicks ${settingHelpMark('agent-configuration', 'anatomy-of-an-agent', 'Include Repos in Kicks', `Append monitored repo information to the kick dialog. Disable for agents that don't need repo context (e.g. outreach).`)} diff --git a/src/pkg/dashboard/static-src/js/shimmy-handlers.js b/src/pkg/dashboard/static-src/js/shimmy-handlers.js index ebd8dbb5b7..105c38898c 100644 --- a/src/pkg/dashboard/static-src/js/shimmy-handlers.js +++ b/src/pkg/dashboard/static-src/js/shimmy-handlers.js @@ -275,6 +275,8 @@ gh33: function (event, A) { markDirty('general','sortOrder',parseInt(this.value,10)); }, gh34: function (event, A) { markDirty('general','replicas',Math.max(1,Math.min(MAX_AGENT_REPLICAS,parseInt(this.value,10)||1)));this.value=Math.max(1,Math.min(MAX_AGENT_REPLICAS,parseInt(this.value,10)||1)); }, gh35: function (event, A) { markDirty('general','staleTimeout',cadenceFromHuman(this.value));this.value=cadenceToHuman(cadenceFromHuman(this.value)); }, + // Contributor-first grace (#16518): blank or unparseable saves 0, which clears it to the 10m default. + contributorFirstGraceChanged: function (event, A) { const secs=cadenceFromHuman(this.value);markDirty('general','contributorFirstGrace',secs);this.value=secs>0?cadenceToHuman(secs):''; }, // Repo scope (#6204). An empty field is meaningful — it CLEARS the scope // and returns the agent to hive-wide — so it marks dirty with [] rather // than skipping, which is why it cannot just reuse gh36. diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index ca979f1c1a..b4283538cd 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -60199,6 +60199,34 @@

Hub settings

} // ── Agent Tab Renderers ── + // Contributor-first lane keys (agents..contributor_first and + // contributor_first_grace, #16518). The toggle can only be turned on for a + // role contributors may act as, the same rule the load enforces; the + // server says which (contributorFirstDelegatable), and a role that is not + // gets a disabled toggle and the one line that names the fix. + function agentContributorFirstControlsHtml(g, agentName) { + const delegatable = g.contributorFirstDelegatable === true; + const on = g.contributorFirst === true; + const name = String(agentName || ''); + let why = ''; + if (!delegatable) { + if (name === 'supervisor') why = 'The supervisor role is never delegatable to contributors.'; + else if (name !== name.toLowerCase()) why = 'Relays claim roles in lower case, so an agent whose name has capitals cannot be covered.'; + else why = `Not available: add ${esc(name)} to hub.contribute_delegatable_roles so contributors may act as this role.`; + } + const tip = `When on, a connected contributor relay acting as this role becomes the lane's primary worker and the resident agent's kicks are withheld. Kicks resume on the normal cadence once no relay has covered the role for the grace below. Budget pause and standby are unaffected, and a manual Kick still works. The role must be one contributors may act as (hub.contribute_delegatable_roles, or the default scanner, quality and outreach).`; + const graceTip = `How long the resident agent's kicks stay withheld after the last relay covering this role disconnects, so a relay can reconnect without the resident agent being kicked in between. Use s, m or h, e.g. 10m. Leave blank for the default, 10m.`; + const grace = Number(g.contributorFirstGrace) || 0; + return `
+
+ Contributor-first ${yamlHint('agents..contributor_first')} ${settingHelpMark('agent-configuration', 'contributor-first-lanes-contributor_first', 'Contributor-first', tip)} +
+ ${delegatable ? '' : `
${why}
`} +
+ + +
`; + } function renderAgentGeneral(g) { const agentName = _configState.agent || ''; const isCreate = _configState.isCreate === true; @@ -60338,6 +60366,7 @@

Hub settings

On Demand ${settingHelpMark('agent-configuration', 'anatomy-of-an-agent', 'On Demand', `When on, this agent is never started at boot and never kicked by the governor or by event (CEL) triggers — it only runs when something summons it explicitly. Turn it OFF to make the agent run on its cadence like a normal agent. Note: an agent also needs a cadence entry in the ACTIVE governor mode before it will actually be kicked. On-demand agents are also excluded from review fan-out, so a reviewer left on-demand cannot be dispatched.`)}${g.onDemand === true ? ' ' + statusBadgeHTML('on_demand', 'on demand', '', '') : ''}
+ ${isCreate ? '' : agentContributorFirstControlsHtml(g, agentName)}
Include Repos in Kicks ${settingHelpMark('agent-configuration', 'anatomy-of-an-agent', 'Include Repos in Kicks', `Append monitored repo information to the kick dialog. Disable for agents that don't need repo context (e.g. outreach).`)} @@ -73365,6 +73394,8 @@

${model.editIndex === null ? 'Add Event trigger' : 'Edit Event trigger'}

0?cadenceToHuman(secs):''; }, // Repo scope (#6204). An empty field is meaningful — it CLEARS the scope // and returns the agent to hive-wide — so it marks dirty with [] rather // than skipping, which is why it cannot just reuse gh36.