diff --git a/changelog.d/added-contributor-first-kicks.md b/changelog.d/added-contributor-first-kicks.md new file mode 100644 index 0000000000..78f7941ff3 --- /dev/null +++ b/changelog.d/added-contributor-first-kicks.md @@ -0,0 +1 @@ +- Contributor-first lanes: `agents..contributor_first: true` makes a connected contributor relay acting as that agent's role the lane's primary worker. While such a relay is connected (and not stale or failure-paused) the governor withholds the resident agent's kicks, so the hive's own inference budget is not spent on work a contributor is already covering; the resident agent resumes on its normal cadence once no relay has covered the role for `contributor_first_grace` (default 10m). The Governor section shows which lanes are covered and by whom (`covered_lanes` on `/api/status`). Budget pause and standby dispatch are unchanged: a covered lane is never reported as paused for budget. diff --git a/dashboard/test/contributor-first-tile.test.js b/dashboard/test/contributor-first-tile.test.js new file mode 100644 index 0000000000..fdb45e1352 --- /dev/null +++ b/dashboard/test/contributor-first-tile.test.js @@ -0,0 +1,81 @@ +'use strict'; + +// The contributor-first tile (agents..contributor_first): the governor +// is withholding a resident agent's kicks because a contributor relay is +// acting as the role. The tile must name the lane and who covers it, say when +// the resident agent resumes during the grace, render nothing when no lane is +// covered, and escape everything it prints. + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +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}`); +} + +function loadTile() { + const context = { exports: {} }; + const source = [ + "function esc(s) { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/\"/g, '"'); }", + extractFunction('contributorFirstFactsHtml'), + 'exports.contributorFirstFactsHtml = contributorFirstFactsHtml;', + ].join('\n'); + vm.runInNewContext(source, context); + return context.exports.contributorFirstFactsHtml; +} + +test('contributor-first tile renders nothing when no lane is covered', () => { + const tile = loadTile(); + assert.equal(tile(undefined, 'stat'), ''); + assert.equal(tile({}, 'stat'), ''); + assert.equal(tile({ covered_lanes: {} }), ''); + assert.equal(tile({ covered_lanes: null }), ''); +}); + +test('contributor-first tile names the lane and who covers it, in both variants', () => { + const tile = loadTile(); + const gov = { covered_lanes: { quality: { contributors: ['alice', 'bob'], since: '2026-11-03T12:00:00Z' } } }; + const stat = tile(gov, 'stat'); + assert.match(stat, /id="gov-contributor-first-tile"/); + assert.match(stat, /class="label">contributor-firstcontributor-first { + const tile = loadTile(); + const graceUntil = new Date(Date.now() + 5 * 60 * 1000).toISOString(); + const html = tile({ covered_lanes: { quality: { contributors: [], grace_until: graceUntil } } }, 'stat'); + assert.match(html, /quality cover ended, resident kicks resume in ~5 min unless a relay returns/); + const noGrace = tile({ covered_lanes: { quality: {} } }, 'stat'); + assert.match(noGrace, /resident kicks resume after grace/); +}); + +test('contributor-first tile lists lanes in a stable order and escapes what it prints', () => { + const tile = loadTile(); + const html = tile({ covered_lanes: { + scanner: { contributors: ['dave'] }, + quality: { contributors: [''] }, + } }, 'stat'); + assert.ok(html.indexOf('quality covered by') < html.indexOf('scanner covered by'), 'lanes are sorted'); + assert.doesNotMatch(html, //); + assert.match(html, /<img src=x>/); +}); diff --git a/src/cmd/hive/contributor_first.go b/src/cmd/hive/contributor_first.go new file mode 100644 index 0000000000..352c8a92a5 --- /dev/null +++ b/src/cmd/hive/contributor_first.go @@ -0,0 +1,22 @@ +package main + +import ( + "time" + + "github.com/hivecommons/hive/pkg/dashboard" + "github.com/hivecommons/hive/pkg/governor" +) + +// contributorRoleCoverage is the eval cycle's feed for contributor-first lanes +// (`agents..contributor_first`): which agent roles a connected +// contributor relay is acting as right now. The governor withholds those +// agents' kicks so the hive's own budget is not spent on work a contributor +// is already covering. Nil — no dashboard, no contribute hub, nobody +// connected — means nobody is covering anything, which the governor treats +// as "kick as usual". +func contributorRoleCoverage(dashSrv *dashboard.Server, now time.Time) map[string]governor.ContributorCoverage { + if dashSrv == nil { + return nil + } + return dashSrv.ContributorRoleCoverage(now) +} diff --git a/src/cmd/hive/contributor_first_test.go b/src/cmd/hive/contributor_first_test.go new file mode 100644 index 0000000000..af6b73c1f4 --- /dev/null +++ b/src/cmd/hive/contributor_first_test.go @@ -0,0 +1,14 @@ +package main + +import ( + "testing" + "time" +) + +// A hive running without the dashboard reports no coverage, which the +// governor reads as "kick as usual" — the feed must never panic on nil. +func TestContributorRoleCoverage_NilDashboardIsNoCoverage(t *testing.T) { + if got := contributorRoleCoverage(nil, time.Now()); got != nil { + t.Fatalf("contributorRoleCoverage(nil) = %+v, want nil", got) + } +} diff --git a/src/cmd/hive/eval_cycle_seams.go b/src/cmd/hive/eval_cycle_seams.go index 528b63b364..9d5a403ce2 100644 --- a/src/cmd/hive/eval_cycle_seams.go +++ b/src/cmd/hive/eval_cycle_seams.go @@ -154,6 +154,8 @@ func mergeResumeKicks(agentsDue, restartedAgents []string, allow func(string) (b logger.Warn("restarted agent NOT resume-kicked (cadence/budget gate); it idles until its next scheduled slot", "agent", a, "reason", string(reason)) case governor.ResumeRefusalBudgetExhausted: logger.Warn("restarted agent NOT resume-kicked (cadence/budget gate); budget exhausted, kicks suspended", "agent", a, "reason", string(reason)) + case governor.ResumeRefusalContributorCovering: + logger.Info("restarted agent NOT resume-kicked; a contributor relay is covering its role (contributor_first)", "agent", a, "reason", string(reason)) default: logger.Info("restarted agent NOT resume-kicked (cadence/budget gate); idle by configuration", "agent", a, "reason", string(reason)) } diff --git a/src/cmd/hive/main_eval_cycle.go b/src/cmd/hive/main_eval_cycle.go index 2d79a30793..791caef793 100644 --- a/src/cmd/hive/main_eval_cycle.go +++ b/src/cmd/hive/main_eval_cycle.go @@ -863,6 +863,12 @@ func runEvalCycle( // round-trip; self-clears the moment a cadence is set or any kick lands. applyNoCadenceAlert(gov, dashSrv) + // Contributor-first lanes (agents..contributor_first): tell the + // governor which roles a connected contributor relay is covering right + // now, so it withholds those agents' kicks and the hive's own budget is + // not spent on work a contributor is already doing. + gov.SetContributorCoverage(contributorRoleCoverage(dashSrv, time.Now())) + agentsDue := gov.EvaluateWithRepoDepths( actionable.Issues.Count, actionable.PRs.Count, diff --git a/src/crux/config/agent_config.go b/src/crux/config/agent_config.go index 842b482bdd..79a4481491 100644 --- a/src/crux/config/agent_config.go +++ b/src/crux/config/agent_config.go @@ -442,6 +442,26 @@ type AgentConfig struct { // src/docs/design/standby-contributors.md. Standby *StandbyConfig `yaml:"standby,omitempty" json:"standby,omitempty"` + // ContributorFirst makes a connected contributor relay acting as this + // agent's role the lane's PRIMARY worker. While such a relay is connected + // (fresh heartbeat, not failure-paused) the governor withholds this + // agent's kicks — at the same gates that withhold them for an exhausted + // budget — so the hive's own inference budget is not spent on work a + // contributor is already covering. Standby (the block above) is the + // opposite order: it offers paused budget work to volunteers. Off is the + // zero value, and an absent key leaves every existing roster unchanged. + // + // The role must be one contributors may act as + // (hub.contribute_delegatable_roles, or the default scanner / quality / + // outreach), or the load fails: a contributor-first lane nobody may claim + // would sit inert forever. + ContributorFirst bool `yaml:"contributor_first,omitempty" json:"contributor_first,omitempty"` + // ContributorFirstGrace is how long kicks stay withheld after the last + // covering relay disappears, so a routine relay reconnect does not flap + // the resident agent. Absent means DefaultContributorFirstGrace (10m); + // negative is rejected at load. + ContributorFirstGrace time.Duration `yaml:"contributor_first_grace,omitempty" json:"contributor_first_grace,omitempty"` + // Channels declares how this agent gets triggered. "kick" is the governor // runtime; "mention" is valid only alongside "kick". When nil/empty, the // agent uses governor timer kicks by default (implicit kick channel). diff --git a/src/crux/config/contributor_first.go b/src/crux/config/contributor_first.go new file mode 100644 index 0000000000..1825cbd3dd --- /dev/null +++ b/src/crux/config/contributor_first.go @@ -0,0 +1,25 @@ +package config + +import "time" + +// DefaultContributorFirstGrace is how long the governor keeps withholding a +// contributor-first agent's kicks after the last covering relay disappears, +// when the agent sets no contributor_first_grace of its own. +// +// Ten minutes is long enough to ride out a relay reconnect — the hub keeps a +// dropped relay's task lease for thirty minutes precisely because reconnects +// are routine (#4260) — and short enough that a contributor who really has +// gone home does not leave the lane idle for long. +const DefaultContributorFirstGrace = 10 * time.Minute + +// ContributorFirstGraceOrDefault resolves contributor_first_grace: a zero +// (absent) value yields DefaultContributorFirstGrace, anything positive is +// returned as-is. Negative values are rejected at load, so this never sees +// one from a loaded config; a caller that assembled an AgentConfig by hand +// gets the default for a negative value rather than a grace in the past. +func (a AgentConfig) ContributorFirstGraceOrDefault() time.Duration { + if a.ContributorFirstGrace <= 0 { + return DefaultContributorFirstGrace + } + return a.ContributorFirstGrace +} diff --git a/src/crux/config/contributor_first_test.go b/src/crux/config/contributor_first_test.go new file mode 100644 index 0000000000..1c753ea8b7 --- /dev/null +++ b/src/crux/config/contributor_first_test.go @@ -0,0 +1,28 @@ +package config + +import ( + "testing" + "time" +) + +func TestContributorFirstGraceOrDefault(t *testing.T) { + cases := []struct { + name string + grace time.Duration + want time.Duration + }{ + {name: "absent yields the default", grace: 0, want: DefaultContributorFirstGrace}, + {name: "positive is returned as-is", grace: 3 * time.Minute, want: 3 * time.Minute}, + {name: "negative (hand-built, never loaded) yields the default", grace: -time.Minute, want: DefaultContributorFirstGrace}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := (AgentConfig{ContributorFirstGrace: tc.grace}).ContributorFirstGraceOrDefault(); got != tc.want { + t.Fatalf("ContributorFirstGraceOrDefault() = %v, want %v", got, tc.want) + } + }) + } + if DefaultContributorFirstGrace != 10*time.Minute { + t.Fatalf("DefaultContributorFirstGrace = %v, want 10m (documented default)", DefaultContributorFirstGrace) + } +} diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index c068eab0ed..f157204bb4 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -1245,6 +1245,67 @@ T3 list** — for the same reason none proposes lowering a floor. That is deliberate, and it is the point of the whole feature. A lane that ran on a strong model for months and then quietly starts producing work from a weak one costs more reviewer trust than a paused lane saves queue depth. **"Nobody qualifies, the lane stays paused" is an acceptable answer.** Lowering a floor should be a decision you made, in a file, on purpose. +## Contributor-first lanes (`contributor_first`) + +A contributor relay can act as one of your agent roles ("Acting as" on the +contributor card, or `HIVE_AGENT_ROLE` on the relay; see +[Delegated ClankeR agent roles](contributor-trust-and-roles.md#delegated-clanker-agent-roles)). +It then does that role's work on the contributor's own machine, with the +contributor's own model. By default it does so **in parallel** with your +resident agent: the governor keeps kicking the resident agent on its cadence, +so your own inference budget is still spent on a lane a contributor is already +covering. Standby (above) is the opposite order on purpose — it offers paused +*budget* work to volunteers and never fires before the budget is gone. + +`contributor_first` inverts the order for one lane. While at least one +contributor relay is **acting as that role and connected** — fresh heartbeat, +not in a failure-streak pause — the governor **withholds the resident agent's +kicks**, at the same gates where it withholds them for an exhausted budget +(cadence kicks, continuous re-kicks, CEL event kicks and crash-recovery resume +kicks). The contributor is the lane's primary worker and spends their own +inference; the resident agent is the fallback. Once no relay has covered the +role for `contributor_first_grace`, the resident agent resumes on its normal +cadence. The grace exists because a relay reconnect is routine (the hub keeps +a dropped relay's lease for thirty minutes for the same reason); without it +the resident agent would flap on and off with every socket drop. + +```yaml +agents: + quality: + contributor_first: true # default false + contributor_first_grace: 10m # default 10m; how long to wait for a relay to return +``` + +| Field | Meaning | +|---|---| +| `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. | + +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. +`/api/status` carries the same facts under `governor.covered_lanes`. A +withheld agent is simply idle; it is not paused, not disabled, and nothing +about its cadence or mode changes. + +What does **not** change: + +- **Budget and standby.** A covered lane is never reported as paused for + budget: `suppressed_lanes` and `lane_pause_reasons` stay budget-only, so + standby dispatch keeps its meaning. If the budget *is* exhausted, the lane + reads as paused for budget exactly as before, and the contributor relay + keeps working because the contributor path has never been budget-gated. +- **Who may act as the role.** Trust tier, grants and the delegatable list are + decided by the contributor path as before; `contributor_first` only reads + the result. A relay that is busy on a task still counts as covering — it is + draining the lane, which is the point. +- **What a relay may take.** Contributors run on their own GitHub identity and + scoped token, so work the role does *outside* contributor task assignment + (for example pushes to adopted branches, or merges) is not done for the + resident agent while it is withheld. Set `contributor_first` on lanes whose + work is issue-shaped and delegatable, which is what the delegatable-role + gate already expresses. + ## Write-back containment (`writeback`) ACMM levels and label policy decide what *agents* may do. The `writeback` diff --git a/src/docs/api-reference.md b/src/docs/api-reference.md index 75e569a09d..3de5a23126 100644 --- a/src/docs/api-reference.md +++ b/src/docs/api-reference.md @@ -33,17 +33,17 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)); also `hub_build` (the hub's short SHA) and, once a stdio `hive-admin-mcp` client has called `/api/version`, `/api/status` or `/api/status/summary` with its `hive-admin-mcp/+` User-Agent, `last_seen_stdio_build` and `last_seen_stdio_at` (RFC3339) so the dashboard can flag build skew ([#12318](https://github.com/hivecommons/hive/issues/12318)) | `pkg/dashboard/api.go:45` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:73` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1759` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1760` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1761` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1767` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); every your-turn issue and PR row carries the critical path (#13646): `waits_on[]` (`{kind,ref}`, kind one of `pr`, `issue`, `external`, `base-check` (ref = the check red on the base branch), `approval`, `merge`; ref `#N` in the same repository or `owner/repo#N`), `unblocks` (transitive count of your-turn items waiting on it, cycle-guarded), `may_conflict_with[]` (PR numbers of the same repository sharing a closing issue or a known changed file; never an edge), `action` (`merge`, `release-hold`, `rebase`, `rerun` or `approve`), `action_ref`, `root_cause` and `blocker` (the root cause it collapses under); `repos[].yourTurn` has `issues`, `prs` (your turn, `CLOSE` excluded), `root_issues`, `root_prs`, `root_cause_count`, `order[]` (`{kind,repo,number}` by unblocks then age), `groups[]` (`{blocker,blocker_title,dependents[]}`) and `main_red` (`{check,since,fix,fix_your_turn}`); the top-level `yourTurn` sums the counts | `pkg/dashboard/server.go:1772` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers, with the hive-wide `yourTurn` root-cause counts the phone widget reads (#13646); honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1773` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1776` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1777` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1778` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1779` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1780` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1773` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1774` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1775` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1781` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); every your-turn issue and PR row carries the critical path (#13646): `waits_on[]` (`{kind,ref}`, kind one of `pr`, `issue`, `external`, `base-check` (ref = the check red on the base branch), `approval`, `merge`; ref `#N` in the same repository or `owner/repo#N`), `unblocks` (transitive count of your-turn items waiting on it, cycle-guarded), `may_conflict_with[]` (PR numbers of the same repository sharing a closing issue or a known changed file; never an edge), `action` (`merge`, `release-hold`, `rebase`, `rerun` or `approve`), `action_ref`, `root_cause` and `blocker` (the root cause it collapses under); `repos[].yourTurn` has `issues`, `prs` (your turn, `CLOSE` excluded), `root_issues`, `root_prs`, `root_cause_count`, `order[]` (`{kind,repo,number}` by unblocks then age), `groups[]` (`{blocker,blocker_title,dependents[]}`) and `main_red` (`{check,since,fix,fix_your_turn}`); the top-level `yourTurn` sums the counts | `pkg/dashboard/server.go:1786` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers, with the hive-wide `yourTurn` root-cause counts the phone widget reads (#13646); honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1787` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1790` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1791` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1792` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1793` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1794` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | @@ -86,7 +86,7 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1841` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](branding.md)) | `pkg/dashboard/server.go:1855` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:87` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:88` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:89` | @@ -114,9 +114,9 @@ History point limits, timestamp cutoffs, incremental cost reads and ETag/304 beh | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1781` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1782` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1783` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1795` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1796` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1797` | ## Configuration @@ -652,7 +652,7 @@ always resolved server-side from the validated token. | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:327` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:328` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:329` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1788` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1802` | ## Hub SaaS 102 routes — see [api-reference/hub-saas.md](api-reference/hub-saas.md). diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index d104ed27ca..61805292dd 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,6 +24,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1781` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1782` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1783` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1795` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1796` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1797` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 90ba942090..dc2f43bebd 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -63,4 +63,4 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:327` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:328` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:329` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1788` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1802` | diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index e40b8317be..b1c8d1664c 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -8,17 +8,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)) | `pkg/dashboard/api.go:45` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:73` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1759` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1760` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1761` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1767` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1772` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1773` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1776` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1777` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1778` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1779` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1780` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1773` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1774` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1775` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1781` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1786` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1787` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1790` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1791` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1792` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1793` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1794` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 8c6132b6b2..30a3289de2 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1841` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1855` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:87` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:88` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:89` | diff --git a/src/docs/contributor-trust-and-roles.md b/src/docs/contributor-trust-and-roles.md index fb10254e9a..dd7579b435 100644 --- a/src/docs/contributor-trust-and-roles.md +++ b/src/docs/contributor-trust-and-roles.md @@ -125,3 +125,7 @@ hub: ``` If the list is empty, Hive uses the safe default: `scanner`, `quality`, and `outreach`. Privileged roles must be both listed here and granted on the contributor profile. The owner UI exposes these grants as chips/check boxes; assigning a privileged role auto-preserves the matching grant so reconnects keep working. + +### 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). diff --git a/src/hive.yaml.example b/src/hive.yaml.example index 2d8e085a32..0c1d0a0079 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -381,6 +381,18 @@ agents: # auto_dispatch: false # min_model_capability: T1 # daily_cap_per_contributor: 0 + # Contributor-first lane: make a connected contributor relay that is + # "Acting as" this role the lane's PRIMARY worker. While one is connected + # (fresh heartbeat, not failure-paused) the governor withholds this + # agent's kicks, so the hive's own inference budget is not spent on work a + # contributor is already covering — the opposite order from standby, which + # offers paused BUDGET work. Kicks resume on the normal cadence once no + # relay has covered the role for contributor_first_grace. The role must be + # delegatable (hub.contribute_delegatable_roles, or the default scanner / + # quality / outreach) or the hive fails to load. See + # src/docs/agent-configuration.md#contributor-first-lanes-contributor_first. + # contributor_first: false + # contributor_first_grace: 10m architect: enabled: false # Disabled by default — enable for design work backend: claude diff --git a/src/pkg/config/contributor_first.go b/src/pkg/config/contributor_first.go new file mode 100644 index 0000000000..3dd3e33a86 --- /dev/null +++ b/src/pkg/config/contributor_first.go @@ -0,0 +1,46 @@ +package config + +import ( + "fmt" + "strings" +) + +// validateContributorFirst checks the contributor-first lane keys +// (`agents..contributor_first` and `contributor_first_grace`). +// +// Like validateStandby it runs as its own pass rather than inside the agent +// loop, because the rule that matters is a relation between the agent and the +// hub block: a lane can only be covered by a role that contributors are +// allowed to act as. A contributor-first lane nobody may claim would sit +// inert forever while the operator believes contributors are taking the +// load, so — as standby does for an enabled lane with nobody approved — the +// 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) + } + } + return nil +} diff --git a/src/pkg/config/contributor_first_test.go b/src/pkg/config/contributor_first_test.go new file mode 100644 index 0000000000..a0b3548ba7 --- /dev/null +++ b/src/pkg/config/contributor_first_test.go @@ -0,0 +1,106 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func contributorFirstConfig(agents map[string]AgentConfig, delegatable ...string) *Config { + c := &Config{ + Project: ProjectConfig{Org: "my-org"}, + GitHub: GitHubConfig{Token: "t"}, + AgentRuntimeConfig: AgentRuntimeConfig{ + Agents: agents, + }, + } + c.Hub.ContributeDelegatableRoles = delegatable + return c +} + +func TestValidateContributorFirst(t *testing.T) { + cases := []struct { + name string + agents map[string]AgentConfig + delegatable []string + wantErr string + }{ + { + name: "default-delegatable role is accepted", + agents: map[string]AgentConfig{"quality": {Backend: "claude", ContributorFirst: true}}, + }, + { + name: "flag off needs no delegation", + agents: map[string]AgentConfig{"architect": {Backend: "claude"}}, + }, + { + name: "privileged role not in the delegatable list fails the load", + agents: map[string]AgentConfig{"architect": {Backend: "claude", ContributorFirst: true}}, + wantErr: "contribute_delegatable_roles", + }, + { + name: "privileged role listed as delegatable is accepted", + agents: map[string]AgentConfig{"architect": {Backend: "claude", ContributorFirst: true}}, + delegatable: []string{"architect"}, + }, + { + name: "mixed-case agent name could never be claimed", + agents: map[string]AgentConfig{"Quality": {Backend: "claude", ContributorFirst: true}}, + wantErr: "lower-case", + }, + { + name: "supervisor is never delegatable", + agents: map[string]AgentConfig{"supervisor": {Backend: "claude", ContributorFirst: true}}, + wantErr: "supervisor", + }, + { + name: "negative grace fails even with the flag off", + agents: map[string]AgentConfig{"quality": {Backend: "claude", ContributorFirstGrace: -time.Minute}}, + wantErr: "contributor_first_grace", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := contributorFirstConfig(tc.agents, tc.delegatable...) + err := c.validateContributorFirst() + if tc.wantErr == "" { + if err != nil { + t.Fatalf("validateContributorFirst() = %v, want nil", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("validateContributorFirst() = %v, want error containing %q", err, tc.wantErr) + } + }) + } +} + +// The validator is wired into the full validation pass: a bad flag fails +// Validate, not just the helper. +func TestValidate_RejectsUndelegatableContributorFirst(t *testing.T) { + c := contributorFirstConfig(map[string]AgentConfig{ + "scanner": {Backend: "claude"}, + "architect": {Backend: "claude", ContributorFirst: true}, + }) + err := c.validate() + if err == nil || !strings.Contains(err.Error(), "contributor_first") || !strings.Contains(err.Error(), "architect") { + t.Fatalf("validate() = %v, want contributor_first error naming architect", err) + } + c.Hub.ContributeDelegatableRoles = []string{"architect"} + if err := c.validate(); err != nil { + t.Fatalf("a delegatable architect should validate: %v", err) + } +} + +func TestContributorFirstGraceOrDefault(t *testing.T) { + if got := (AgentConfig{}).ContributorFirstGraceOrDefault(); got != DefaultContributorFirstGrace { + t.Errorf("unset grace = %v, want default %v", got, DefaultContributorFirstGrace) + } + if got := (AgentConfig{ContributorFirstGrace: 3 * time.Minute}).ContributorFirstGraceOrDefault(); got != 3*time.Minute { + t.Errorf("set grace = %v, want 3m", got) + } + if got := (AgentConfig{ContributorFirstGrace: -time.Minute}).ContributorFirstGraceOrDefault(); got != DefaultContributorFirstGrace { + t.Errorf("negative grace (never loaded, hand-built) = %v, want default %v", got, DefaultContributorFirstGrace) + } +} diff --git a/src/pkg/config/crux_aliases.go b/src/pkg/config/crux_aliases.go index 8c10bab080..bdc0ae5910 100644 --- a/src/pkg/config/crux_aliases.go +++ b/src/pkg/config/crux_aliases.go @@ -230,15 +230,16 @@ type ( ) const ( - ChannelTypeMention = cruxconfig.ChannelTypeMention - DefaultExperimentEngine = cruxconfig.DefaultExperimentEngine - ExperimentEngineNous = cruxconfig.ExperimentEngineNous - RoleExperimenter = cruxconfig.RoleExperimenter - StandbyDefaultFloor = cruxconfig.StandbyDefaultFloor - StandbyTierT1 = cruxconfig.StandbyTierT1 - StandbyTierT2 = cruxconfig.StandbyTierT2 - StandbyTierT3 = cruxconfig.StandbyTierT3 - StandbyTierUnknown = cruxconfig.StandbyTierUnknown + ChannelTypeMention = cruxconfig.ChannelTypeMention + DefaultContributorFirstGrace = cruxconfig.DefaultContributorFirstGrace + DefaultExperimentEngine = cruxconfig.DefaultExperimentEngine + ExperimentEngineNous = cruxconfig.ExperimentEngineNous + RoleExperimenter = cruxconfig.RoleExperimenter + StandbyDefaultFloor = cruxconfig.StandbyDefaultFloor + StandbyTierT1 = cruxconfig.StandbyTierT1 + StandbyTierT2 = cruxconfig.StandbyTierT2 + StandbyTierT3 = cruxconfig.StandbyTierT3 + StandbyTierUnknown = cruxconfig.StandbyTierUnknown ) var NormalizeStandbyTier = cruxconfig.NormalizeStandbyTier diff --git a/src/pkg/config/validate.go b/src/pkg/config/validate.go index 4223d05c51..76a967a80f 100644 --- a/src/pkg/config/validate.go +++ b/src/pkg/config/validate.go @@ -536,6 +536,11 @@ func (c *Config) ValidateWithOptions(opts ValidateOptions) error { if err := c.validateStandby(); err != nil { return err } + // Contributor-first lanes: the role must be one contributors may act as, + // or the flag can never do anything (contributor_first.go). + if err := c.validateContributorFirst(); err != nil { + return err + } return nil } diff --git a/src/pkg/dashboard/contribute_coverage.go b/src/pkg/dashboard/contribute_coverage.go new file mode 100644 index 0000000000..bf7331b4de --- /dev/null +++ b/src/pkg/dashboard/contribute_coverage.go @@ -0,0 +1,130 @@ +package dashboard + +import ( + "sort" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/governor" +) + +// RoleCoverage reports which connected contributor relays are acting as which +// agent role right now, keyed by role, for the governor's contributor-first +// gate (`agents..contributor_first`; see pkg/governor/contributor_first.go). +// +// A relay counts as covering a role when: +// +// - its EFFECTIVE role is that role — the owner's "Acting as" assignment +// after it has overridden whatever the relay requested, which is what +// c.role already holds once the hub admitted the claim; +// - its heartbeat is fresh, by the same wsHeartbeatTimeout rule +// FleetSnapshot uses to mark a relay stale, so a relay whose socket died +// silently cannot keep the resident agent idle; +// - it is not in a failure-streak pause: a relay whose runtime keeps dying +// is connected but is not doing the lane's work; +// - the operator has not suspended contributions (hub.contribute_suspended). +// The suspend switch refuses work to every relay while their sockets stay +// up, so a connected relay is then covering nothing; reporting it as +// coverage would turn "pause contributors" into "pause the lane". +// +// A relay that is busy on a task still counts — it is draining the lane, +// which is the point. Whether the relay is ALLOWED the role (trust tier, +// grants, the delegatable list) was settled when the hub set c.role; nothing +// is re-derived here. +func (h *ContributeWSHub) RoleCoverage(now time.Time) map[string]governor.ContributorCoverage { + if h == nil || h.contributionsSuspended() { + return nil + } + type candidate struct { + role, login, identity string + } + var candidates []candidate + h.mu.RLock() + for _, c := range h.connections { + if c == nil { + continue + } + c.mu.Lock() + role := normalizeAgentRole(c.role) + fresh := now.Sub(c.lastPong) <= wsHeartbeatTimeout + login := "" + if c.profile != nil { + login = strings.TrimSpace(c.profile.GitHubUsername) + } + c.mu.Unlock() + if role == "" || !fresh || login == "" { + continue + } + candidates = append(candidates, candidate{role: role, login: login, identity: identityOf(c)}) + } + h.mu.RUnlock() + + // The failure-streak ledger has its own lock; consult it with h.mu + // released so the two are never nested. + byRole := make(map[string]map[string]struct{}) + for _, cand := range candidates { + if paused, _, _ := h.contributorFailureStreakActive(cand.identity, now); paused { + continue + } + if byRole[cand.role] == nil { + byRole[cand.role] = make(map[string]struct{}) + } + byRole[cand.role][cand.login] = struct{}{} + } + if len(byRole) == 0 { + return nil + } + out := make(map[string]governor.ContributorCoverage, len(byRole)) + for role, logins := range byRole { + list := make([]string, 0, len(logins)) + for login := range logins { + list = append(list, login) + } + sort.Strings(list) + out[role] = governor.ContributorCoverage{Contributors: list} + } + return out +} + +// contributionsSuspended mirrors the task-selection gate in +// contribute_select.go: with hub.contribute_suspended set, no relay is handed +// work, whatever role it holds. +func (h *ContributeWSHub) contributionsSuspended() bool { + return h != nil && h.server != nil && h.server.deps != nil && h.server.deps.Config != nil && + h.server.deps.Config.Hub.ContributeSuspended +} + +// ContributorRoleCoverage is the eval cycle's entry point to RoleCoverage. It +// is nil-safe on both the server and the hub: a hive without the contribute +// hub reports no coverage, and the governor treats nil as "nobody is covering +// anything". +func (s *Server) ContributorRoleCoverage(now time.Time) map[string]governor.ContributorCoverage { + if s == nil || s.contributeHub == nil { + return nil + } + return s.contributeHub.RoleCoverage(now) +} + +// frontendLaneCoverage renders the governor's covered-lane map for the status +// payload, timestamps as RFC 3339 strings like the other FrontendGovernor +// times. +func frontendLaneCoverage(in map[string]governor.LaneCoverage) map[string]FrontendLaneCoverage { + if len(in) == 0 { + return nil + } + out := make(map[string]FrontendLaneCoverage, len(in)) + for lane, cov := range in { + fc := FrontendLaneCoverage{Contributors: append([]string(nil), cov.Contributors...)} + if !cov.Since.IsZero() { + fc.Since = cov.Since.UTC().Format(time.RFC3339) + } + if !cov.LastSeen.IsZero() { + fc.LastSeen = cov.LastSeen.UTC().Format(time.RFC3339) + } + if !cov.GraceUntil.IsZero() { + fc.GraceUntil = cov.GraceUntil.UTC().Format(time.RFC3339) + } + out[lane] = fc + } + return out +} diff --git a/src/pkg/dashboard/contribute_coverage_test.go b/src/pkg/dashboard/contribute_coverage_test.go new file mode 100644 index 0000000000..551d3140ef --- /dev/null +++ b/src/pkg/dashboard/contribute_coverage_test.go @@ -0,0 +1,115 @@ +package dashboard + +import ( + "log/slog" + "reflect" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/governor" +) + +func coverageConn(login, role string, pong time.Time) *ContributorConnection { + return &ContributorConnection{ + profile: &ContributorProfile{GitHubUsername: login, ContributorID: "c-" + login, TrustTier: "contributor"}, + role: role, + assignedRole: role, + lastPong: pong, + } +} + +func TestRoleCoverage_ConnectedRoleRelaysOnly(t *testing.T) { + hub := NewContributeWSHub(slog.Default(), nil) + t.Cleanup(hub.Close) + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + + frank := coverageConn("frank", "quality", now) + hub.mu.Lock() + hub.connections["alice"] = coverageConn("alice", "quality", now) + hub.connections["bob"] = coverageConn("bob", "quality", now.Add(-wsHeartbeatTimeout-time.Second)) // stale heartbeat + hub.connections["carol"] = coverageConn("carol", "", now) // general work, no role + hub.connections["dave"] = coverageConn("dave", "scanner", now) + hub.connections["erin"] = coverageConn("erin", "Quality", now) // role is normalised + hub.connections["frank"] = frank // failure-streak paused below + hub.connections["ghost"] = &ContributorConnection{role: "quality", lastPong: now} + hub.mu.Unlock() + + hub.failureStreakMu.Lock() + if hub.contributorFailureStreaks == nil { + hub.contributorFailureStreaks = make(map[string]contributorFailureStreak) + } + hub.contributorFailureStreaks[identityOf(frank)] = contributorFailureStreak{Count: contributorFailureStreakThreshold, LastAt: now} + hub.failureStreakMu.Unlock() + + got := hub.RoleCoverage(now) + want := map[string]governor.ContributorCoverage{ + "quality": {Contributors: []string{"alice", "erin"}}, + "scanner": {Contributors: []string{"dave"}}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("RoleCoverage = %+v, want %+v", got, want) + } +} + +func TestRoleCoverage_NobodyConnectedIsNil(t *testing.T) { + hub := NewContributeWSHub(slog.Default(), nil) + t.Cleanup(hub.Close) + if got := hub.RoleCoverage(time.Now()); got != nil { + t.Fatalf("empty hub: RoleCoverage = %+v, want nil", got) + } + var none *ContributeWSHub + if got := none.RoleCoverage(time.Now()); got != nil { + t.Fatalf("nil hub: RoleCoverage = %+v, want nil", got) + } + var noServer *Server + if got := noServer.ContributorRoleCoverage(time.Now()); got != nil { + t.Fatalf("nil server: ContributorRoleCoverage = %+v, want nil", got) + } + if got := (&Server{}).ContributorRoleCoverage(time.Now()); got != nil { + t.Fatalf("server without a hub: ContributorRoleCoverage = %+v, want nil", got) + } +} + +func TestFrontendLaneCoverage(t *testing.T) { + if got := frontendLaneCoverage(nil); got != nil { + t.Fatalf("empty input must render nil, got %+v", got) + } + since := time.Date(2026, 11, 3, 11, 0, 0, 0, time.UTC) + got := frontendLaneCoverage(map[string]governor.LaneCoverage{ + "quality": {Contributors: []string{"alice"}, Since: since, LastSeen: since.Add(time.Minute)}, + "scanner": {Since: since, LastSeen: since, GraceUntil: since.Add(10 * time.Minute)}, + }) + want := map[string]FrontendLaneCoverage{ + "quality": {Contributors: []string{"alice"}, Since: "2026-11-03T11:00:00Z", LastSeen: "2026-11-03T11:01:00Z"}, + "scanner": {Since: "2026-11-03T11:00:00Z", LastSeen: "2026-11-03T11:00:00Z", GraceUntil: "2026-11-03T11:10:00Z"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("frontendLaneCoverage = %+v, want %+v", got, want) + } +} + +// The operator's "Suspend contributions" switch refuses work to every relay +// while their sockets stay up. A connected relay is then covering nothing, so +// no coverage may be reported — otherwise pausing contributors would also +// pause the resident agent and the lane would have no worker at all. +func TestRoleCoverage_SuspendedContributionsCoverNothing(t *testing.T) { + hub, s := covK2Hub(t) + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + hub.mu.Lock() + hub.connections["alice"] = coverageConn("alice", "quality", now) + hub.mu.Unlock() + + s.deps.Config.Hub.ContributeSuspended = true + if got := hub.RoleCoverage(now); got != nil { + t.Fatalf("suspended contributions: RoleCoverage = %+v, want nil", got) + } + if got := s.ContributorRoleCoverage(now); got != nil { + t.Fatalf("suspended contributions: ContributorRoleCoverage = %+v, want nil", got) + } + + s.deps.Config.Hub.ContributeSuspended = false + got := hub.RoleCoverage(now) + if len(got["quality"].Contributors) != 1 || got["quality"].Contributors[0] != "alice" { + t.Fatalf("contributions resumed: RoleCoverage = %+v, want quality covered by alice", got) + } +} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index bd47069b85..cdd585dc14 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -1185,9 +1185,23 @@ type FrontendGovernor struct { LanePauseReasons map[string]string `json:"lane_pause_reasons,omitempty"` QualifiedStandbys map[string]int `json:"qualified_standbys,omitempty"` SuspendedStandbys map[string]int `json:"suspended_standbys,omitempty"` - NextKickAt string `json:"nextKickAt,omitempty"` - NextKickIn string `json:"nextKickIn,omitempty"` - NextAgents []string `json:"nextAgents,omitempty"` + // CoveredLanes are the contributor-first lanes (agents..contributor_first) + // whose resident kicks the governor is withholding because a connected + // contributor relay is acting as the role, keyed by agent name. + CoveredLanes map[string]FrontendLaneCoverage `json:"covered_lanes,omitempty"` + NextKickAt string `json:"nextKickAt,omitempty"` + NextKickIn string `json:"nextKickIn,omitempty"` + NextAgents []string `json:"nextAgents,omitempty"` +} + +// FrontendLaneCoverage is one contributor-first lane the governor is +// withholding kicks for: who covers it, since when, and — while no relay +// covers it — when the resident agent resumes. Times are RFC 3339. +type FrontendLaneCoverage struct { + Contributors []string `json:"contributors,omitempty"` + Since string `json:"since,omitempty"` + LastSeen string `json:"last_seen,omitempty"` + GraceUntil string `json:"grace_until,omitempty"` } type FrontendThresholds struct { diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 9d96b5d3b3..d5933cb365 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -554,6 +554,8 @@ 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/agent-detail.js b/src/pkg/dashboard/static-src/js/agent-detail.js index 4922727700..dbb9a10649 100644 --- a/src/pkg/dashboard/static-src/js/agent-detail.js +++ b/src/pkg/dashboard/static-src/js/agent-detail.js @@ -766,6 +766,7 @@ ${fleetRunStripHtml()}
on hold${window._lastStatus?.hold?.total || 0}
${standbyPauseFactsHtml(gov)} + ${contributorFirstFactsHtml(gov)} ${(() => { const plan = window._lastStatus?.planning || {}; // Planning only runs at ACMM >= 5 (architect scheduled); hide the tile diff --git a/src/pkg/dashboard/static-src/js/governor-view.js b/src/pkg/dashboard/static-src/js/governor-view.js index 20ae08364d..2201e4d468 100644 --- a/src/pkg/dashboard/static-src/js/governor-view.js +++ b/src/pkg/dashboard/static-src/js/governor-view.js @@ -719,6 +719,7 @@ ${fleetRunStatHtml()}
on hold
${holdTotal}${holdSpark}
${standbyPauseFactsHtml(gov, 'stat')} + ${contributorFirstFactsHtml(gov, 'stat')}
blocked on human
${(Array.isArray(data.runs) ? data.runs : []).filter(r => r && r.waiting_on === 'human').length}
${(() => { // Merge hotspots tile (GET /api/hotspots): files concurrent PRs diff --git a/src/pkg/dashboard/static-src/js/sidebar.js b/src/pkg/dashboard/static-src/js/sidebar.js index 757313cd1e..88171a01ef 100644 --- a/src/pkg/dashboard/static-src/js/sidebar.js +++ b/src/pkg/dashboard/static-src/js/sidebar.js @@ -134,6 +134,28 @@ return `
standby${parts.join('; ')}
`; } + // Contributor-first lanes (agents..contributor_first): the governor + // is withholding the resident agent's kicks because a connected + // contributor relay is acting as that role, so no hive budget is spent on + // a lane a contributor already covers. Renders nothing when no lane is + // covered; sits next to the standby tile in both governor views. + function contributorFirstFactsHtml(gov, variant) { + const covered = gov && gov.covered_lanes && typeof gov.covered_lanes === 'object' ? gov.covered_lanes : {}; + const lanes = Object.keys(covered).sort(); + if (lanes.length === 0) return ''; + const parts = lanes.map(lane => { + const cov = covered[lane] || {}; + const who = Array.isArray(cov.contributors) ? cov.contributors.filter(Boolean) : []; + if (who.length > 0) return `${lane} covered by ${who.join(', ')}, resident kicks withheld`; + const until = cov.grace_until ? Date.parse(cov.grace_until) : NaN; + const mins = Number.isFinite(until) ? Math.max(0, Math.round((until - Date.now()) / 60000)) : null; + return `${lane} cover ended, resident kicks resume ${mins === null ? 'after grace' : 'in ~' + mins + ' min'} unless a relay returns`; + }); + const title = 'CONTRIBUTOR-FIRST — a contributor relay is the primary worker of these lanes.\n\nWHAT: agents..contributor_first is set and a connected contributor relay is acting as the role, so the governor withholds the resident agent\'s kicks and spends no hive budget on the lane.\n\nHOW: kicks resume on the normal cadence once no relay has covered the role for contributor_first_grace (default 10m). Budget pause and standby are unaffected.'; + if (variant === 'stat') return `
contributor-first
${esc(parts.join('; '))}
`; + return `
contributor-first${esc(parts.join('; '))}
`; + } + async function standbyDispatch(btn) { const lane = btn?.dataset?.standbyLane || ''; const key = btn?.dataset?.standbyKey || ''; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index aaaf2e2a11..7267c32959 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -11788,6 +11788,7 @@

Where to get help

${fleetRunStripHtml()}
on hold${window._lastStatus?.hold?.total || 0}
${standbyPauseFactsHtml(gov)} + ${contributorFirstFactsHtml(gov)} ${(() => { const plan = window._lastStatus?.planning || {}; // Planning only runs at ACMM >= 5 (architect scheduled); hide the tile @@ -12097,6 +12098,28 @@

Where to get help

return `
standby${parts.join('; ')}
`; } + // Contributor-first lanes (agents..contributor_first): the governor + // is withholding the resident agent's kicks because a connected + // contributor relay is acting as that role, so no hive budget is spent on + // a lane a contributor already covers. Renders nothing when no lane is + // covered; sits next to the standby tile in both governor views. + function contributorFirstFactsHtml(gov, variant) { + const covered = gov && gov.covered_lanes && typeof gov.covered_lanes === 'object' ? gov.covered_lanes : {}; + const lanes = Object.keys(covered).sort(); + if (lanes.length === 0) return ''; + const parts = lanes.map(lane => { + const cov = covered[lane] || {}; + const who = Array.isArray(cov.contributors) ? cov.contributors.filter(Boolean) : []; + if (who.length > 0) return `${lane} covered by ${who.join(', ')}, resident kicks withheld`; + const until = cov.grace_until ? Date.parse(cov.grace_until) : NaN; + const mins = Number.isFinite(until) ? Math.max(0, Math.round((until - Date.now()) / 60000)) : null; + return `${lane} cover ended, resident kicks resume ${mins === null ? 'after grace' : 'in ~' + mins + ' min'} unless a relay returns`; + }); + const title = 'CONTRIBUTOR-FIRST — a contributor relay is the primary worker of these lanes.\n\nWHAT: agents..contributor_first is set and a connected contributor relay is acting as the role, so the governor withholds the resident agent\'s kicks and spends no hive budget on the lane.\n\nHOW: kicks resume on the normal cadence once no relay has covered the role for contributor_first_grace (default 10m). Budget pause and standby are unaffected.'; + if (variant === 'stat') return `
contributor-first
${esc(parts.join('; '))}
`; + return `
contributor-first${esc(parts.join('; '))}
`; + } + async function standbyDispatch(btn) { const lane = btn?.dataset?.standbyLane || ''; const key = btn?.dataset?.standbyKey || ''; @@ -26921,6 +26944,7 @@

Approval and audit records

${approval}`; ${fleetRunStatHtml()}
on hold
${holdTotal}${holdSpark}
${standbyPauseFactsHtml(gov, 'stat')} + ${contributorFirstFactsHtml(gov, 'stat')}
blocked on human
${(Array.isArray(data.runs) ? data.runs : []).filter(r => r && r.waiting_on === 'human').length}
${(() => { // Merge hotspots tile (GET /api/hotspots): files concurrent PRs diff --git a/src/pkg/dashboard/status_builder.go b/src/pkg/dashboard/status_builder.go index 12b451f2a6..b4895b1978 100644 --- a/src/pkg/dashboard/status_builder.go +++ b/src/pkg/dashboard/status_builder.go @@ -2153,6 +2153,7 @@ func buildGovernorWithLaneDepths(state governor.State, cfg *config.Config, laneD SuppressedLanes: cloneStringSlice(state.SuppressedLanes), LaneQueueDepths: cloneStatusIntMap(laneDepths), LanePauseReasons: cloneStringStringMap(state.LanePauseReasons), + CoveredLanes: frontendLaneCoverage(state.CoveredLanes), NextKickAt: nextKickAt, NextKickIn: nextKickIn, NextAgents: append([]string(nil), state.PendingKicks...), diff --git a/src/pkg/governor/contributor_first.go b/src/pkg/governor/contributor_first.go new file mode 100644 index 0000000000..ae661b5623 --- /dev/null +++ b/src/pkg/governor/contributor_first.go @@ -0,0 +1,274 @@ +package governor + +import ( + "sort" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// Contributor-first lanes (`agents..contributor_first`). +// +// A contributor relay acting as an agent role — "Acting as" on the contributor +// card, or HIVE_AGENT_ROLE on the relay — does that role's work on the +// contributor's own machine, with the contributor's own model. Until now it +// did so IN PARALLEL with the hive's resident agent: the governor had no idea a +// relay was connected, kept kicking the resident agent on cadence, and so the +// hive's own inference budget was spent on work a contributor was already +// covering. Standby (RFC #7629) is the other way round on purpose: it offers +// paused BUDGET work to volunteers and never fires before the budget is gone. +// +// contributor_first inverts the order for one lane. While at least one +// connected, non-stale, non-failure-paused relay is acting as the role (and +// the operator has not suspended contributions), the +// governor WITHHOLDS the resident agent's kicks — at exactly the gates where it +// withholds them for an exhausted budget. The relay is the primary worker; the +// resident agent is the fallback, and it resumes on its normal cadence once no +// relay has covered the role for contributor_first_grace. The grace exists +// because a relay reconnect is routine (#4260 keeps a dropped relay's lease for +// thirty minutes); without it the resident agent would flap on and off with +// every socket drop. +// +// What this deliberately does NOT touch: the budget gate and SuppressedLanes +// (a covered lane is never reported as paused for budget, so standby cannot +// dispatch on it), the contributor path's own admission rules (trust tier, +// grants, allow-lists), and which issues a relay may take. + +// ContributorCoverage is the contribute hub's per-tick report that connected +// contributor relays are acting as an agent role right now. The hub owns the +// definition of "acting as": the connection's EFFECTIVE role, after an owner +// assignment has overridden whatever the relay requested. +type ContributorCoverage struct { + // Contributors are the GitHub logins of the covering relays. + Contributors []string +} + +// LaneCoverage is what the governor publishes for a contributor-first lane it +// is currently withholding kicks for. +type LaneCoverage struct { + // Contributors are the logins covering the lane right now. Empty while + // the grace period runs after the last relay disappeared. + Contributors []string `json:"contributors,omitempty"` + // Since is when coverage began. + Since time.Time `json:"since"` + // LastSeen is the last report in which a relay covered the lane. + LastSeen time.Time `json:"last_seen"` + // GraceUntil is when the resident agent resumes if no relay returns. Zero + // while a relay is covering the lane. + GraceUntil time.Time `json:"grace_until,omitempty"` +} + +// contributorCoveringPauseReason is the machine-readable reason a +// contributor-first lane is not being kicked. It is published through +// State.CoveredLanes and used as the continuous-mode blocker string. It is +// deliberately NOT written into SuppressedLanes or LanePauseReasons, which +// stay budget-only so that standby dispatch keeps its "paused for budget" +// meaning. +const contributorCoveringPauseReason = "contributor_covering" + +// ResumeRefusalContributorCovering: a contributor relay is covering the agent's +// role and contributor_first is set, so a crash-recovery resume kick is +// withheld exactly as a scheduled kick is. +const ResumeRefusalContributorCovering ResumeRefusal = "contributor_covering" + +// coverageRecord is the governor's memory of one role's coverage. +type coverageRecord struct { + contributors []string + since time.Time + lastSeen time.Time +} + +// SetContributorCoverage replaces the governor's view of which roles connected +// contributor relays are covering. The eval cycle calls it once per tick, +// before Evaluate, with the hub's current report; nil or empty means nobody is +// covering anything. A role missing from the report keeps its record until its +// grace has elapsed — that is what lets a relay reconnect without the resident +// agent being kicked in between. +// +// Coverage is remembered for every role the hub reports, whether or not the +// agent has contributor_first set, so switching the flag on takes effect on +// the next evaluation rather than after the next relay heartbeat. The gate +// itself (contributorCoveredLocked) is the only place the flag is read. +func (g *Governor) SetContributorCoverage(coverage map[string]ContributorCoverage) { + g.mu.Lock() + defer g.mu.Unlock() + now := g.now() + if g.coverage == nil { + g.coverage = make(map[string]coverageRecord) + } + + reported := make(map[string]struct{}, len(coverage)) + for role, cov := range coverage { + role = strings.ToLower(strings.TrimSpace(role)) + logins := normalizeContributorLogins(cov.Contributors) + if role == "" || len(logins) == 0 { + continue + } + reported[role] = struct{}{} + rec, known := g.coverage[role] + if !known { + rec = coverageRecord{since: now} + if g.contributorFirstLocked(role) && g.logger != nil { + g.logger.Info("contributor relay covering a contributor-first lane — withholding the resident agent's kicks", + "agent", role, "contributors", strings.Join(logins, ",")) + } + } else if len(rec.contributors) == 0 && g.contributorFirstLocked(role) && g.logger != nil { + // Back within the grace window: coverage never really ended. + g.logger.Info("contributor relay returned within grace — resident agent stays withheld", + "agent", role, "contributors", strings.Join(logins, ",")) + } + rec.contributors = logins + rec.lastSeen = now + g.coverage[role] = rec + } + + for role, rec := range g.coverage { + if _, ok := reported[role]; ok { + continue + } + flagged := g.contributorFirstLocked(role) + if len(rec.contributors) > 0 { + // The last relay just disappeared: start the grace. + rec.contributors = nil + g.coverage[role] = rec + if flagged && g.logger != nil { + g.logger.Info("contributor cover ended — resident agent resumes after grace unless a relay returns", + "agent", role, "grace", g.contributorFirstGraceLocked(role).String()) + } + continue + } + if !now.Before(rec.lastSeen.Add(g.contributorFirstGraceLocked(role))) { + delete(g.coverage, role) + if flagged && g.logger != nil { + g.logger.Info("contributor-first grace elapsed — resident agent kicks resume", "agent", role) + } + } + } +} + +// coverageLane is the key the hub reports coverage under for an agent: the +// base lane name, case-folded. A replica (quality-2) or a review head +// (quality-fast-1) carries ReplicaOf = base and a relay acts as the BASE role, +// so every derived agent of a contributor-first lane is withheld together +// with its base rather than only replica 1. +func coverageLane(agentName string, ac config.AgentConfig) string { + lane := agentName + if ac.ReplicaOf != "" { + lane = ac.ReplicaOf + } + return strings.ToLower(strings.TrimSpace(lane)) +} + +// baseAgentForLaneLocked finds the configuration that owns a coverage lane: +// the base agent whose case-folded name is the lane or, failing that, one of +// its derived agents, which carry the base's copied flag and grace. Agent +// names are matched case-insensitively so a lane's grace is honoured however +// the agent is spelled in hive.yaml. Callers must hold g.mu. +func (g *Governor) baseAgentForLaneLocked(lane string) (config.AgentConfig, bool) { + var derived config.AgentConfig + found := false + for name, ac := range g.agents { + if coverageLane(name, ac) != lane { + continue + } + if ac.ReplicaOf == "" { + return ac, true + } + if !found { + derived, found = ac, true + } + } + return derived, found +} + +// contributorCoveredLocked reports whether the named agent's kicks are +// withheld because a contributor relay is covering its lane: the agent has +// contributor_first set, and either a relay covers the lane right now or the +// last one disappeared less than contributor_first_grace ago. Callers must +// hold g.mu. +func (g *Governor) contributorCoveredLocked(agentName string) (LaneCoverage, bool) { + ac, ok := g.agents[agentName] + if !ok || !ac.ContributorFirst { + return LaneCoverage{}, false + } + rec, ok := g.coverage[coverageLane(agentName, ac)] + if !ok { + return LaneCoverage{}, false + } + if len(rec.contributors) > 0 { + return LaneCoverage{ + Contributors: append([]string(nil), rec.contributors...), + Since: rec.since, + LastSeen: rec.lastSeen, + }, true + } + until := rec.lastSeen.Add(ac.ContributorFirstGraceOrDefault()) + if g.now().Before(until) { + return LaneCoverage{Since: rec.since, LastSeen: rec.lastSeen, GraceUntil: until}, true + } + return LaneCoverage{}, false +} + +// coveredLanesLocked is the per-evaluation publication: every contributor-first +// lane whose kicks are currently withheld, keyed by the base lane name (one +// entry per lane, not per replica), with who is covering it. Callers must +// hold g.mu. +func (g *Governor) coveredLanesLocked() map[string]LaneCoverage { + var out map[string]LaneCoverage + for name, ac := range g.agents { + cov, ok := g.contributorCoveredLocked(name) + if !ok { + continue + } + if out == nil { + out = make(map[string]LaneCoverage) + } + out[coverageLane(name, ac)] = cov + } + return out +} + +func (g *Governor) contributorFirstLocked(lane string) bool { + ac, ok := g.baseAgentForLaneLocked(lane) + return ok && ac.ContributorFirst +} + +func (g *Governor) contributorFirstGraceLocked(lane string) time.Duration { + if ac, ok := g.baseAgentForLaneLocked(lane); ok { + return ac.ContributorFirstGraceOrDefault() + } + return config.DefaultContributorFirstGrace +} + +// normalizeContributorLogins trims, drops empties, de-duplicates and sorts, so +// the published list is stable across ticks and map iteration order. +func normalizeContributorLogins(in []string) []string { + seen := make(map[string]struct{}, len(in)) + out := make([]string, 0, len(in)) + for _, login := range in { + login = strings.TrimSpace(login) + if login == "" { + continue + } + if _, dup := seen[login]; dup { + continue + } + seen[login] = struct{}{} + out = append(out, login) + } + sort.Strings(out) + return out +} + +func cloneLaneCoverage(in map[string]LaneCoverage) map[string]LaneCoverage { + if len(in) == 0 { + return nil + } + out := make(map[string]LaneCoverage, len(in)) + for lane, cov := range in { + cov.Contributors = append([]string(nil), cov.Contributors...) + out[lane] = cov + } + return out +} diff --git a/src/pkg/governor/contributor_first_test.go b/src/pkg/governor/contributor_first_test.go new file mode 100644 index 0000000000..216a1bb3f0 --- /dev/null +++ b/src/pkg/governor/contributor_first_test.go @@ -0,0 +1,336 @@ +package governor + +import ( + "log/slog" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// contributorFirstGovernor builds a governor with "quality" marked +// contributor-first (grace = grace) and "scanner" ordinary, on a fixed clock +// the test advances through *now. +func contributorFirstGovernor(t *testing.T, grace time.Duration) (*Governor, *time.Time) { + t.Helper() + cfg, agents := standardConfig("quality", "scanner") + q := agents["quality"] + q.ContributorFirst = true + q.ContributorFirstGrace = grace + agents["quality"] = q + g := New(cfg, agents, testLogger()) + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + g.now = func() time.Time { return now } + return g, &now +} + +func coverage(logins ...string) map[string]ContributorCoverage { + return map[string]ContributorCoverage{"quality": {Contributors: logins}} +} + +func TestContributorFirst_CoveredLaneWithholdsKicks(t *testing.T) { + g, _ := contributorFirstGovernor(t, 5*time.Minute) + g.SetContributorCoverage(coverage("alice")) + + due := dueSet(g) + if due["quality"] { + t.Error("quality is covered by a contributor relay and must not be due") + } + if !due["scanner"] { + t.Error("scanner has no contributor_first and must still be due") + } + + state := g.GetState() + cov, ok := state.CoveredLanes["quality"] + if !ok || len(cov.Contributors) != 1 || cov.Contributors[0] != "alice" { + t.Fatalf("CoveredLanes = %+v, want quality covered by alice", state.CoveredLanes) + } + if cov.Since.IsZero() || !cov.GraceUntil.IsZero() { + t.Errorf("covered lane must carry Since and no GraceUntil, got %+v", cov) + } + // The budget vocabulary stays budget-only: standby dispatch keys on it. + if len(state.SuppressedLanes) != 0 { + t.Errorf("a covered lane must not be reported as budget-suppressed, got %v", state.SuppressedLanes) + } + if _, reasoned := state.LanePauseReasons["quality"]; reasoned { + t.Errorf("a covered lane must not carry a lane pause reason, got %v", state.LanePauseReasons) + } + history := g.EvalHistory() + if len(history) == 0 || history[len(history)-1].CoveredLanes["quality"].Contributors[0] != "alice" { + t.Fatalf("eval history did not publish the covered lane: %+v", history) + } +} + +func TestContributorFirst_FlagOffIgnoresCoverage(t *testing.T) { + cfg, agents := standardConfig("quality", "scanner") + g := New(cfg, agents, testLogger()) + g.SetContributorCoverage(coverage("alice")) + + due := dueSet(g) + if !due["quality"] { + t.Error("without contributor_first a covered role must still be kicked") + } + if len(g.GetState().CoveredLanes) != 0 { + t.Errorf("CoveredLanes must be empty without the flag, got %+v", g.GetState().CoveredLanes) + } +} + +func TestContributorFirst_GraceThenResume(t *testing.T) { + g, now := contributorFirstGovernor(t, 5*time.Minute) + start := *now + g.SetContributorCoverage(coverage("alice")) + if dueSet(g)["quality"] { + t.Fatal("covered: quality must not be due") + } + + // The relay disappears: the grace starts from the last sighting. + *now = start.Add(time.Minute) + g.SetContributorCoverage(nil) + if dueSet(g)["quality"] { + t.Error("within grace: quality must still be withheld") + } + cov := g.GetState().CoveredLanes["quality"] + if len(cov.Contributors) != 0 { + t.Errorf("in grace the lane has no contributors, got %v", cov.Contributors) + } + if want := start.Add(5 * time.Minute); !cov.GraceUntil.Equal(want) { + t.Errorf("GraceUntil = %v, want %v (last sighting + grace)", cov.GraceUntil, want) + } + + // The relay comes back inside the grace: coverage never ended, so Since + // is the original start. + *now = start.Add(3 * time.Minute) + g.SetContributorCoverage(coverage("alice")) + if dueSet(g)["quality"] { + t.Error("relay returned within grace: quality must still be withheld") + } + if got := g.GetState().CoveredLanes["quality"].Since; !got.Equal(start) { + t.Errorf("Since = %v, want the original start %v", got, start) + } + + // Gone again, and this time the grace elapses. + *now = start.Add(4 * time.Minute) + g.SetContributorCoverage(nil) + *now = start.Add(4*time.Minute + 5*time.Minute + time.Second) + g.SetContributorCoverage(nil) + if !dueSet(g)["quality"] { + t.Error("after the grace elapsed quality must resume its cadence") + } + if len(g.GetState().CoveredLanes) != 0 { + t.Errorf("CoveredLanes must be empty after the grace, got %+v", g.GetState().CoveredLanes) + } +} + +func TestContributorFirst_DefaultGraceWhenUnset(t *testing.T) { + g, now := contributorFirstGovernor(t, 0) + start := *now + g.SetContributorCoverage(coverage("alice")) + dueSet(g) + *now = start.Add(time.Second) + g.SetContributorCoverage(nil) + if dueSet(g)["quality"] { + t.Fatal("within the default grace quality must still be withheld") + } + cov := g.GetState().CoveredLanes["quality"] + if want := start.Add(config.DefaultContributorFirstGrace); !cov.GraceUntil.Equal(want) { + t.Errorf("GraceUntil = %v, want %v (default grace)", cov.GraceUntil, want) + } +} + +func TestContributorFirst_BudgetGateStillWins(t *testing.T) { + g, _ := contributorFirstGovernor(t, 5*time.Minute) + g.SetContributorCoverage(coverage("alice")) + g.SetBudgetLimit(1000) + g.SeedBudget(1000, nil, nil, time.Now()) + + due := dueSet(g) + if due["quality"] || due["scanner"] { + t.Errorf("exhausted budget suppresses everything, got due=%v", due) + } + state := g.GetState() + // A lane that is BOTH out of budget and covered still reads as paused for + // budget — that is what standby dispatch keys on, and nothing here may + // change its meaning. + if state.LanePauseReasons["quality"] != budgetExhaustedPauseReason { + t.Errorf("quality pause reason = %q, want %q", state.LanePauseReasons["quality"], budgetExhaustedPauseReason) + } + found := false + for _, lane := range state.SuppressedLanes { + if lane == "quality" { + found = true + } + } + if !found { + t.Errorf("quality must still be budget-suppressed, got %v", state.SuppressedLanes) + } +} + +func TestContributorFirst_GatesEventAndResumeKicks(t *testing.T) { + g, now := contributorFirstGovernor(t, 5*time.Minute) + g.SetContributorCoverage(coverage("alice")) + dueSet(g) + + if g.AgentEligibleForCELKick("quality") { + t.Error("a CEL event kick must not bypass a covered lane") + } + if !g.AgentEligibleForCELKick("scanner") { + t.Error("scanner is not covered and must stay CEL-eligible") + } + if ok, reason := g.AllowResumeKickReason("quality"); ok || reason != ResumeRefusalContributorCovering { + t.Errorf("resume kick: ok=%v reason=%q, want refused with %q", ok, reason, ResumeRefusalContributorCovering) + } + + // Once the grace has elapsed both gates open again. + *now = now.Add(time.Hour) + g.SetContributorCoverage(nil) + *now = now.Add(time.Hour) + g.SetContributorCoverage(nil) + if !g.AgentEligibleForCELKick("quality") { + t.Error("after the grace a CEL kick must be allowed again") + } + if _, reason := g.AllowResumeKickReason("quality"); reason == ResumeRefusalContributorCovering { + t.Error("after the grace the resume gate must not cite contributor coverage") + } +} + +func TestContributorFirst_BlocksContinuousRekick(t *testing.T) { + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + g := New(config.GovernorConfig{Modes: map[string]config.ModeConfig{ + "idle": {Cadences: map[string]config.Cadence{"quality": "continuous"}}, + }}, map[string]config.AgentConfig{ + "quality": {Backend: "copilot", Enabled: true, ContributorFirst: true}, + }, slog.Default()) + g.now = func() time.Time { return now } + g.Evaluate(0, 0, 0, 0) + + g.SetContributorCoverage(coverage("alice")) + g.mu.Lock() + _, _, blocked := g.continuousBlockerLocked("quality") + g.mu.Unlock() + if blocked != contributorCoveringPauseReason { + t.Fatalf("continuous blocker = %q, want %q", blocked, contributorCoveringPauseReason) + } + + now = now.Add(time.Hour) + g.SetContributorCoverage(nil) + now = now.Add(time.Hour) + g.SetContributorCoverage(nil) + g.mu.Lock() + _, _, blocked = g.continuousBlockerLocked("quality") + g.mu.Unlock() + if blocked == contributorCoveringPauseReason { + t.Fatal("after the grace the continuous blocker must not cite contributor coverage") + } +} + +func TestContributorFirst_NormalisesReport(t *testing.T) { + g, _ := contributorFirstGovernor(t, 5*time.Minute) + g.SetContributorCoverage(map[string]ContributorCoverage{ + " Quality ": {Contributors: []string{" bob", "alice", "alice", ""}}, + "": {Contributors: []string{"nobody"}}, + "unknown": {Contributors: []string{"zed"}}, + "emptyLogin": {Contributors: []string{"", " "}}, + }) + dueSet(g) + cov := g.GetState().CoveredLanes["quality"] + if len(cov.Contributors) != 2 || cov.Contributors[0] != "alice" || cov.Contributors[1] != "bob" { + t.Fatalf("contributors = %v, want [alice bob] (trimmed, de-duplicated, sorted)", cov.Contributors) + } + if len(g.GetState().CoveredLanes) != 1 { + t.Errorf("only quality is a contributor-first agent, got %+v", g.GetState().CoveredLanes) + } +} + +func TestContributorFirst_GetStateIsACopy(t *testing.T) { + g, _ := contributorFirstGovernor(t, 5*time.Minute) + g.SetContributorCoverage(coverage("alice")) + dueSet(g) + first := g.GetState().CoveredLanes["quality"] + first.Contributors[0] = "mallory" + if got := g.GetState().CoveredLanes["quality"].Contributors[0]; got != "alice" { + t.Fatalf("GetState must return a copy; mutation leaked: %q", got) + } +} + +// Replicas (quality-2) and review heads (quality-fast-1) copy the base +// agent's config and carry ReplicaOf = base, while the hub reports coverage +// under the BASE role a relay acts as. Every derived agent of a covered lane +// must be withheld, and the lane must be published once, not per replica. +func TestContributorFirst_ReplicasAndReviewHeadsFollowTheBaseLane(t *testing.T) { + cfg, agents := standardConfig("quality", "quality-2", "quality-fast-1", "scanner") + base := agents["quality"] + base.ContributorFirst = true + base.ContributorFirstGrace = 5 * time.Minute + agents["quality"] = base + replica := base + replica.ReplicaOf = "quality" + replica.ReplicaIndex = 2 + agents["quality-2"] = replica + head := base + head.ReplicaOf = "quality" + head.ReviewHead = "quality-fast" + agents["quality-fast-1"] = head + g := New(cfg, agents, testLogger()) + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + g.now = func() time.Time { return now } + + g.SetContributorCoverage(coverage("alice")) + due := dueSet(g) + for _, name := range []string{"quality", "quality-2", "quality-fast-1"} { + if due[name] { + t.Errorf("%s belongs to the covered quality lane and must not be due", name) + } + } + if !due["scanner"] { + t.Error("scanner is not covered and must be due") + } + lanes := g.GetState().CoveredLanes + if len(lanes) != 1 || len(lanes["quality"].Contributors) != 1 { + t.Fatalf("CoveredLanes = %+v, want exactly one entry for the quality lane", lanes) + } + if g.AgentEligibleForCELKick("quality-2") { + t.Error("a replica of a covered lane must not be CEL-kickable either") + } + + // The grace is the lane's, for replicas too. + now = now.Add(time.Minute) + g.SetContributorCoverage(nil) + if d := dueSet(g); d["quality-2"] || d["quality-fast-1"] { + t.Errorf("within grace the derived agents must still be withheld, got %v", d) + } + now = now.Add(10 * time.Minute) + g.SetContributorCoverage(nil) + if d := dueSet(g); !d["quality"] || !d["quality-2"] || !d["quality-fast-1"] { + t.Errorf("after the grace every agent of the lane must resume, got %v", d) + } +} + +// Agent lookups are case-insensitive, so a lane's own grace is honoured +// however the agent is spelled in hive.yaml (the loader rejects mixed-case +// contributor-first names, but the governor must not depend on that). +func TestContributorFirst_MixedCaseAgentNameKeepsItsGrace(t *testing.T) { + cfg, agents := standardConfig("Quality") + q := agents["Quality"] + q.ContributorFirst = true + q.ContributorFirstGrace = 30 * time.Minute + agents["Quality"] = q + g := New(cfg, agents, testLogger()) + now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC) + g.now = func() time.Time { return now } + + g.SetContributorCoverage(coverage("alice")) + if dueSet(g)["Quality"] { + t.Fatal("covered: Quality must not be due") + } + now = now.Add(time.Minute) + g.SetContributorCoverage(nil) + // Past the 10m default but inside the agent's own 30m grace. + now = now.Add(15 * time.Minute) + g.SetContributorCoverage(nil) + if dueSet(g)["Quality"] { + t.Fatal("inside the agent's 30m grace Quality must still be withheld; the default grace must not have expired the record") + } + if want := time.Date(2026, 11, 3, 12, 30, 0, 0, time.UTC); !g.GetState().CoveredLanes["quality"].GraceUntil.Equal(want) { + t.Fatalf("GraceUntil = %v, want %v", g.GetState().CoveredLanes["quality"].GraceUntil, want) + } +} diff --git a/src/pkg/governor/governor.go b/src/pkg/governor/governor.go index 4837961164..1f5d1c4253 100644 --- a/src/pkg/governor/governor.go +++ b/src/pkg/governor/governor.go @@ -58,6 +58,7 @@ type EvalSnapshot struct { SuppressedLanes []string `json:"suppressed_lanes,omitempty"` LaneQueueDepths map[string]int `json:"lane_queue_depths,omitempty"` LanePauseReasons map[string]string `json:"lane_pause_reasons,omitempty"` + CoveredLanes map[string]LaneCoverage `json:"covered_lanes,omitempty"` } type RepoSnapshot struct { @@ -199,6 +200,11 @@ type State struct { BudgetExhaustedUnit string `json:"budget_exhausted_unit,omitempty"` SuppressedLanes []string `json:"suppressed_lanes,omitempty"` LanePauseReasons map[string]string `json:"lane_pause_reasons,omitempty"` + // CoveredLanes are the contributor-first lanes whose kicks are withheld + // because a contributor relay covers the role (contributor_first.go). + // Kept separate from SuppressedLanes on purpose: that list means "paused + // for budget" to standby dispatch. + CoveredLanes map[string]LaneCoverage `json:"covered_lanes,omitempty"` } // ContinuousState is the governor's in-memory schedule/backoff for one agent @@ -295,6 +301,11 @@ type Governor struct { // window rolls so each window alerts at most once per threshold. budgetWarned bool budgetExhaustedAlerted bool + + // coverage is the governor's memory of which agent roles connected + // contributor relays are covering (contributor_first.go). Fed by + // SetContributorCoverage once per eval tick; lazily allocated. + coverage map[string]coverageRecord } func New(cfg config.GovernorConfig, agents map[string]config.AgentConfig, logger *slog.Logger) *Governor { @@ -497,6 +508,7 @@ func (g *Governor) EvaluateWithRepoDepths(queueIssues, queuePRs, queueHold, slaV g.state.PendingKicks = agentNamesFromKickKeys(due) g.state.SuppressedLanes = kickReport.suppressedLanes g.state.LanePauseReasons = kickReport.pauseReasons + g.state.CoveredLanes = kickReport.coveredLanes snap := EvalSnapshot{ Timestamp: time.Now().UnixMilli(), @@ -512,6 +524,7 @@ func (g *Governor) EvaluateWithRepoDepths(queueIssues, queuePRs, queueHold, slaV OpenPRs: queuePRs, SuppressedLanes: cloneStrings(kickReport.suppressedLanes), LanePauseReasons: cloneStringMap(kickReport.pauseReasons), + CoveredLanes: cloneLaneCoverage(kickReport.coveredLanes), } g.appendEvalHistory(snap) @@ -902,6 +915,7 @@ type kickReport struct { due []string suppressedLanes []string pauseReasons map[string]string + coveredLanes map[string]LaneCoverage } const budgetExhaustedPauseReason = "budget_exhausted" @@ -1002,6 +1016,14 @@ func (g *Governor) agentsDueForKickReport() kickReport { suppressedSet[agentName] = struct{}{} continue } + // Contributor-first: a connected contributor relay is acting as this + // role, so the resident agent's kick is withheld (contributor_first.go). + // Checked AFTER the budget gate so a lane that is both out of budget + // and covered still reads as paused for budget, which is what standby + // dispatch keys on. + if _, covered := g.contributorCoveredLocked(agentName); covered { + continue + } lastKick := g.state.LastKick[cadenceKey] due := false @@ -1063,7 +1085,7 @@ func (g *Governor) agentsDueForKickReport() kickReport { } sort.Strings(suppressedLanes) - return kickReport{due: due, suppressedLanes: suppressedLanes, pauseReasons: pauseReasons} + return kickReport{due: due, suppressedLanes: suppressedLanes, pauseReasons: pauseReasons, coveredLanes: g.coveredLanesLocked()} } // armContinuousIfIdleLocked seeds the first continuous re-kick when continuous @@ -1181,6 +1203,9 @@ func (g *Governor) continuousBlockerLocked(agentName string) (string, AgentCaden if g.continuousBudgetBlockedLocked(ac) { return cadenceKey, cadence, "budget" } + if _, covered := g.contributorCoveredLocked(agentName); covered { + return cadenceKey, cadence, contributorCoveringPauseReason + } return cadenceKey, cadence, "" } @@ -1252,6 +1277,12 @@ func (g *Governor) AgentEligibleForCELKick(agentName string) bool { return false } + // Contributor-first gate: identical to agentsDueForKick, so an event + // kick cannot bypass a lane a contributor relay is covering. + if _, covered := g.contributorCoveredLocked(agentName); covered { + return false + } + return true } @@ -1376,6 +1407,9 @@ func (g *Governor) resumeKickVerdictLocked(agentName string) (string, time.Durat if g.budgetExhausted() && !g.budgetExempt(agentName) { return cadenceKey, interval, ResumeRefusalBudgetExhausted } + if _, covered := g.contributorCoveredLocked(agentName); covered { + return cadenceKey, interval, ResumeRefusalContributorCovering + } if cadence.Schedule.Mode() != config.CadenceModeInterval { return cadenceKey, interval, ResumeRefusalNotInterval } @@ -1550,6 +1584,7 @@ func (g *Governor) GetState() State { BudgetExhaustedUnit: g.state.BudgetExhaustedUnit, SuppressedLanes: cloneStrings(g.state.SuppressedLanes), LanePauseReasons: cloneStringMap(g.state.LanePauseReasons), + CoveredLanes: cloneLaneCoverage(g.state.CoveredLanes), } }