Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-contributor-first-settings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Settings: the agent's General tab now has **Contributor-first** and **Contributor-first grace** controls for `agents.<name>.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.
145 changes: 145 additions & 0 deletions dashboard/test/contributor-first-general.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
'use strict';

// The agent's General tab controls for the contributor-first lane keys
// (agents.<name>.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(/<div class="config-toggle-switch[^"]*" id="cfg-contributor-first"[^>]*>/);
assert.ok(m, 'contributor-first toggle rendered');
return m[0];
}

function helpMarks(html, label) {
return html.match(new RegExp('<a class="config-info section-help-mark" href="/docs/agent-configuration#contributor-first-lanes-contributor_first"[^>]*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\.&lt;key&gt;\.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(/<div class="text-muted" id="cfg-contributor-first-disabled"[^>]*>([\s\S]*?)<\/div>/);
assert.ok(reason, 'disabled reason rendered');
assert.match(reason[1], /add <code>architect<\/code> to <code>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\.</);
});

test('agent creation shows no contributor-first controls', () => {
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)}`);
}
});
2 changes: 2 additions & 0 deletions src/docs/agent-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/docs/contributor-trust-and-roles.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
63 changes: 40 additions & 23 deletions src/pkg/config/contributor_first.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
46 changes: 46 additions & 0 deletions src/pkg/config/contributor_first_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Loading
Loading