diff --git a/changelog.d/added-19070-parent-autoclose-settings.md b/changelog.d/added-19070-parent-autoclose-settings.md new file mode 100644 index 0000000000..3fb3636af2 --- /dev/null +++ b/changelog.d/added-19070-parent-autoclose-settings.md @@ -0,0 +1 @@ +- Settings, Repos tab now has a "Parent auto-close" card, so an owner can choose per repo how far the hive closes finished parent issues without editing YAML ([#19070](https://github.com/hivecommons/hive/issues/19070)). The three choices are "Close finished parents (default)", "Also close epics and holds" and "Never auto-close parents" (`repos..parent_autoclose`: `true`, `epics_too`, `false`). The card shows each monitored repo's effective value, saves through the new owner-only `GET`/`PUT /api/config/repos/parent-autoclose` routes, applies without a restart and is audited as `config_repo_parent_autoclose`. A parent a person reopened is still never re-closed, and issues marked as tracking issues are still never auto-closed. The settings parity allowlist entry for the field is removed. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index d3b8bb3b6f..f483a73b3c 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -8314,6 +8314,116 @@ } } }, + "/api/config/repos/parent-autoclose": { + "get": { + "tags": [ + "System" + ], + "summary": "Parent auto-close policy per repo", + "description": "Returns repos..parent_autoclose for every monitored repo (effective value and whether the repo carries its own), the default, and the three options the Settings editor offers. Owner only.", + "responses": { + "200": { + "description": "Current policy per monitored repo", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "default": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "object" + } + }, + "repos": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + } + } + }, + "put": { + "tags": [ + "System" + ], + "summary": "Set a repo's parent auto-close policy", + "description": "Sets repos..parent_autoclose for one monitored repo: true (close finished parents, the default and clears the override), epics_too (also close epic and hold parents) or false (never auto-close parents). Applies without a restart. Parents a person reopened and tracking issues are never auto-closed under any value. Audited as config_repo_parent_autoclose. Owner only.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "repo", + "value" + ], + "properties": { + "repo": { + "type": "string" + }, + "value": { + "type": "string", + "enum": [ + "true", + "epics_too", + "false" + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Current policy per monitored repo (same body as GET)", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "default": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "object" + } + }, + "repos": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + }, + "400": { + "description": "Missing repo or invalid value; nothing was stored" + }, + "404": { + "description": "The repo is not a monitored repo" + }, + "500": { + "description": "The config file could not be written; the previous value is restored" + } + } + } + }, "/api/config/reference-repos": { "get": { "tags": [ diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 86bcd20728..46b8b8c06b 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -27,7 +27,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1805` | | `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1806` | | `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1807` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:562` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:563` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:564` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:565` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:565` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:566` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:567` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:568` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 67169db1f3..8ed84abc01 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -103,9 +103,11 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:526` | | `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)), plus `credential_identity` (`bot`, `owner` or `token_file`) and `credential_note`, the one-line why ([#18516](https://github.com/hivecommons/hive/issues/18516)); always an array), `write_kinds`, `write_identity` (`project.remote_write_identity` with the default applied), `write_identities` and `bot_login` (the App bot login, when known) | `pkg/dashboard/api.go:556` | | `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:557` | -| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:559` | -| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:568` | -| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:569` | +| `PUT` | `/api/config/reference-repos/write-identity` | Owner only | Set `project.remote_write_identity` ([#18516](https://github.com/hivecommons/hive/issues/18516)): body `{"write_identity": "bot"}`, one of `bot`, `bot_only`, `owner`. 400 on an unknown value, or when a hand-written write entry would have no credential under the new value (the message boot exits 22 with); nothing is stored then. 500 when the file could not be written. On success the reference repos are re-resolved before the response, which is the same body as `GET /api/config/reference-repos`; audited as `config_remote_write_identity` with `previous` and `write_identity` | `pkg/dashboard/api.go:562` | +| `GET` | `/api/config/repos/parent-autoclose` | Owner only | `repos..parent_autoclose` for every monitored repo: the effective value (`true`, `epics_too` or `false`), whether the repo carries its own, the default and the three options the Settings editor offers ([#19070](https://github.com/hivecommons/hive/issues/19070)) | `pkg/dashboard/api.go:559` | +| `PUT` | `/api/config/repos/parent-autoclose` | Owner only | Set one monitored repo's parent auto-close policy: `{"repo": "owner/name", "value": "true" \| "epics_too" \| "false"}`. `true` is the default and clears the override. 400 for a missing repo or an invalid value, 404 for a repo that is not monitored, 500 when the file could not be written (previous value restored). Applies without a restart; audited as `config_repo_parent_autoclose`. Parents a person reopened and tracking issues are never auto-closed under any value | `pkg/dashboard/api.go:560` | +| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:571` | +| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:572` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:218` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:221` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:227` | diff --git a/src/docs/labels-and-control-signals/stage-labels.md b/src/docs/labels-and-control-signals/stage-labels.md index 8d179bc544..e8f8df3a3a 100644 --- a/src/docs/labels-and-control-signals/stage-labels.md +++ b/src/docs/labels-and-control-signals/stage-labels.md @@ -722,6 +722,13 @@ repos: parent_autoclose: false ``` +You can also set it without editing YAML: Settings, Repos tab, "Parent auto-close" +(owner only). Each monitored repo has a choice of "Close finished parents +(default)", "Also close epics and holds" and "Never auto-close parents"; saving +applies it without a restart and is recorded in the audit log. Issues marked as +tracking issues (`hive/tracking`, the `` marker, or "Keep +this issue open") are never auto-closed under any value. + The dashboard does not yet show a "kept open: reopened by " pill; the kept-open decision is logged (`decomposed parent kept open`). diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 05d98088dd..5bfd89d7f7 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -301,7 +301,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `governor.trajectory.enabled` | Defaults to enabled. | The lane no-ops until a reviewer endpoint and model resolve from `governor.trajectory` or `governor.litellm`. | | `governor.kick_limits.max_issues` / `max_prs` | `100` / `50` | Caps on every issue list and every PR list (actionable, stale drafts, merge-eligible, CI-failing) rendered into a kick prompt; a cut list ends with an explicit "… and N more" line. An absent key or a negative value means the default; an explicit `0` opts out of the cap entirely (`KickListUnlimited` — every item is listed), and anything above `500` is pinned to `500`. Editable without touching this file under **Settings → Repos → Kick prompt list caps**. Truncation drops the *newest, lowest-priority* items: issues are listed oldest first, and PRs in review-priority order (fixes, then refactors/docs, then tests, oldest first within each class), so lowering a cap never hides the most urgent work. Raise `max_prs` only if your agents actually work more than 50 PRs per turn; the tail of a long list costs tokens and delivery time on every kick without changing behaviour (#7368). | | `project.agents_md_max_bytes` | `32768` (or env `HIVE_AGENTS_MD_MAX_BYTES`); clamped to `2048`..`262144`. `repos..agents_md_max_bytes` overrides it per repo. | Caps the repo `AGENTS.md` block prepended to a kick. Whole sections (split at `#`/`##` headings; each resolved skill is its own unit) are kept or dropped, never clipped mid-rule; when any are dropped the kick carries a one-line `⚠️ AGENTS.md exceeded N bytes; … — read AGENTS.md …` warning naming them and the scheduler logs it. See [agents-md.md](../agents-md.md#size-cap-whole-sections-visible-warning). | -| `repos..parent_autoclose` | `true` (default), `epics_too` or `false` | Decomposed-parent auto-close policy for the repo: `true` closes a parent when every child is closed except `epic`/`hold`-labelled issues; `epics_too` also closes those; `false` never closes a parent. A parent a person reopened after a hive auto-close is never re-closed under any value. See [stage-labels.md](../labels-and-control-signals/stage-labels.md#decomposed-parents--closed-by-their-children-never-stalled). | +| `repos..parent_autoclose` | `true` (default), `epics_too` or `false` | Decomposed-parent auto-close policy for the repo: `true` closes a parent when every child is closed except `epic`/`hold`-labelled issues; `epics_too` also closes those; `false` never closes a parent. A parent a person reopened after a hive auto-close is never re-closed under any value. Editable in Settings, Repos tab, Parent auto-close (owner only; applies without a restart). See [stage-labels.md](../labels-and-control-signals/stage-labels.md#decomposed-parents--closed-by-their-children-never-stalled). | | `project.style` | unset (built-in text applies) | Hive-wide **house style**: a short how-to-change rule list prepended to every kick on every backend, directly under the header. A managed repo's root `HIVE_STYLE.md` (read from `project.checkouts_dir`) overrides it; precedence repo > hive > built-in. Inline text wins over `project.style_file`. See [house-style.md](../house-style.md). | | `project.style_file` | unset | Path on the hive host holding the hive-wide house style; used when `project.style` is empty. | | `project.style_max_bytes` | `4096`; values under `512` are raised to `512`. | Caps each house-style candidate. An oversize candidate is skipped whole (not clipped) and the next source applies; the skip is audited as `house_style_skip`. The repo file is also run through ioscan at the issue-body policy and refused whole on a block. | diff --git a/src/docs/settings.md b/src/docs/settings.md index af3e72437b..796f0c3264 100644 --- a/src/docs/settings.md +++ b/src/docs/settings.md @@ -44,6 +44,8 @@ Which labels hold, require, or route work, the label the merger queue applies to The repos the hive manages and the caps on how many issues and PRs are listed in one kick (`governor.kick_limits`). See the `governor.kick_limits` row of the [notable fields](operator-reference.md#notable-fields). +The same tab has a **Parent auto-close** card (owner only, `repos..parent_autoclose`): per monitored repo, choose "Close finished parents (default)", "Also close epics and holds" or "Never auto-close parents". It shows the effective value for each repo, applies on save without a restart, and is audited. A parent a person reopened is never re-closed, and issues marked as tracking issues are never auto-closed. See [stage-labels](labels-and-control-signals/stage-labels.md#decomposed-parents--closed-by-their-children-never-stalled). + ## Budget The token budget and its rolling period, optional dollar and coin caps, the percentage at which the governor enters budget-critical mode, per-agent exemptions, and the model lock that stops automatic model downgrades. See [Governor cadence and budget](operator-reference.md#governor-cadence-and-budget) and [Token collection and usage tracking](token-tracking.md). diff --git a/src/pkg/config/repo_settings.go b/src/pkg/config/repo_settings.go index eef445ab11..0a93b98b1f 100644 --- a/src/pkg/config/repo_settings.go +++ b/src/pkg/config/repo_settings.go @@ -1,6 +1,17 @@ package config -import "strings" +import ( + "errors" + "fmt" + "reflect" + "strings" + "sync" +) + +// repoSettingsMu guards Config.Repos. The dashboard edits a repo's settings +// while the scheduler and the issue-stage pass read them from other +// goroutines, so the map is never touched without it. +var repoSettingsMu sync.RWMutex // RepoSettings is one managed repository's per-repo knobs under the top-level // `repos:` map (hivecommons/hive#18495). It is additive: a repo with no entry @@ -54,17 +65,111 @@ func (c *Config) RepoSettingsFor(repo string) (RepoSettings, bool) { if c == nil || len(c.Repos) == 0 || strings.TrimSpace(repo) == "" { return RepoSettings{}, false } - org := c.Project.Org - want := repoPauseKey(org, strings.TrimSpace(repo)) - if rs, ok := c.Repos[repo]; ok { - return rs, true + repoSettingsMu.RLock() + defer repoSettingsMu.RUnlock() + if key, ok := c.repoSettingsKeyLocked(repo); ok { + return c.Repos[key], true } - for key, rs := range c.Repos { - if repoPauseKey(org, strings.TrimSpace(key)) == want { - return rs, true + return RepoSettings{}, false +} + +// repoSettingsKeyLocked is the key of repo's entry in the `repos:` map. The +// caller holds repoSettingsMu. +func (c *Config) repoSettingsKeyLocked(repo string) (string, bool) { + if _, ok := c.Repos[repo]; ok { + return repo, true + } + want := repoPauseKey(c.Project.Org, strings.TrimSpace(repo)) + for key := range c.Repos { + if repoPauseKey(c.Project.Org, strings.TrimSpace(key)) == want { + return key, true } } - return RepoSettings{}, false + return "", false +} + +// NormalizeParentAutoClose maps a dashboard or YAML value onto one of the +// three policy constants, and reports false for anything else (an empty value +// included: the dashboard always sends an explicit choice). +func NormalizeParentAutoClose(v string) (string, bool) { + switch n := strings.ToLower(strings.TrimSpace(v)); n { + case ParentAutoCloseOn, ParentAutoCloseOff, ParentAutoCloseEpicsToo: + return n, true + } + return "", false +} + +// ParentAutoCloseExplicit reports whether repo carries its own +// repos..parent_autoclose value, as opposed to inheriting the default. +func (c *Config) ParentAutoCloseExplicit(repo string) bool { + rs, ok := c.RepoSettingsFor(repo) + if !ok { + return false + } + _, valid := NormalizeParentAutoClose(rs.ParentAutoClose) + return valid +} + +// ErrRepoNotMonitored is returned by SetParentAutoClose for a repo that is not +// in project.repos: the policy only governs repos the hive manages. +var ErrRepoNotMonitored = errors.New("repo is not a monitored repo") + +// SetParentAutoClose sets repos..parent_autoclose for a monitored repo +// (hivecommons/hive#19070). value must be one of "true", "false" or +// "epics_too". Choosing the default ("true") clears the override, and an entry +// left with no other knob is dropped, so the config file only carries values +// that differ from the default. The change is visible to every reader at once: +// ParentAutoCloseFor reads the live map, so no restart is needed. +func (c *Config) SetParentAutoClose(repo, value string) error { + if c == nil { + return errors.New("config unavailable") + } + norm, ok := NormalizeParentAutoClose(value) + if !ok { + return fmt.Errorf("parent_autoclose must be %q, %q or %q", ParentAutoCloseOn, ParentAutoCloseEpicsToo, ParentAutoCloseOff) + } + name, ok := c.monitoredRepoName(repo) + if !ok { + return fmt.Errorf("%w: %s", ErrRepoNotMonitored, strings.TrimSpace(repo)) + } + repoSettingsMu.Lock() + defer repoSettingsMu.Unlock() + key, exists := c.repoSettingsKeyLocked(name) + if !exists { + key = name + } + rs := c.Repos[key] + if norm == ParentAutoCloseOn { + rs.ParentAutoClose = "" + } else { + rs.ParentAutoClose = norm + } + // RepoSettings holds slices (review_preflight), so it is not comparable + // with ==; IsZero reports an entry with no knob set. + if reflect.ValueOf(rs).IsZero() { + delete(c.Repos, key) + return nil + } + if c.Repos == nil { + c.Repos = map[string]RepoSettings{} + } + c.Repos[key] = rs + return nil +} + +// monitoredRepoName is the project.repos entry (as written) that repo names, +// compared org-qualified and case-folded. +func (c *Config) monitoredRepoName(repo string) (string, bool) { + want := repoPauseKey(c.Project.Org, strings.TrimSpace(repo)) + if want == "" { + return "", false + } + for _, r := range c.Project.Repos { + if repoPauseKey(c.Project.Org, strings.TrimSpace(r)) == want { + return strings.TrimSpace(r), true + } + } + return "", false } // AgentsMdMaxBytesFor is the configured AGENTS.md injection cap for repo: diff --git a/src/pkg/config/repo_settings_test.go b/src/pkg/config/repo_settings_test.go index 4efa7e3384..6a70274831 100644 --- a/src/pkg/config/repo_settings_test.go +++ b/src/pkg/config/repo_settings_test.go @@ -1,6 +1,7 @@ package config import ( + "errors" "testing" "gopkg.in/yaml.v3" @@ -66,3 +67,80 @@ func TestParentAutoCloseFor(t *testing.T) { } } } + +func TestSetParentAutoClose(t *testing.T) { + newCfg := func() *Config { + return &Config{Project: ProjectConfig{Org: "acme", Repos: []string{"widgets", "acme/gadgets"}}} + } + t.Run("sets and reads back live", func(t *testing.T) { + c := newCfg() + if err := c.SetParentAutoClose("acme/Widgets", " Epics_Too "); err != nil { + t.Fatal(err) + } + if got := c.ParentAutoCloseFor("widgets"); got != ParentAutoCloseEpicsToo { + t.Errorf("effective = %q, want epics_too", got) + } + if !c.ParentAutoCloseExplicit("widgets") { + t.Error("explicit = false after a set") + } + if _, ok := c.Repos["widgets"]; !ok { + t.Errorf("entry must be keyed as project.repos writes it, got %v", c.Repos) + } + }) + t.Run("default clears the override and drops an empty entry", func(t *testing.T) { + c := newCfg() + if err := c.SetParentAutoClose("gadgets", ParentAutoCloseOff); err != nil { + t.Fatal(err) + } + if got := c.ParentAutoCloseFor("gadgets"); got != ParentAutoCloseOff { + t.Errorf("effective = %q, want false", got) + } + if err := c.SetParentAutoClose("gadgets", ParentAutoCloseOn); err != nil { + t.Fatal(err) + } + if c.ParentAutoCloseExplicit("gadgets") || len(c.Repos) != 0 { + t.Errorf("default must leave no entry, got %v", c.Repos) + } + }) + t.Run("keeps other knobs when clearing", func(t *testing.T) { + c := newCfg() + c.Repos = map[string]RepoSettings{"widgets": {AgentsMdMaxBytes: 4096, ParentAutoClose: ParentAutoCloseOff}} + if err := c.SetParentAutoClose("widgets", ParentAutoCloseOn); err != nil { + t.Fatal(err) + } + if rs := c.Repos["widgets"]; rs.AgentsMdMaxBytes != 4096 || rs.ParentAutoClose != "" { + t.Errorf("entry = %+v", rs) + } + }) + t.Run("reuses an existing differently written key", func(t *testing.T) { + c := newCfg() + c.Repos = map[string]RepoSettings{"Acme/Widgets": {ParentAutoClose: ParentAutoCloseOff}} + if err := c.SetParentAutoClose("widgets", ParentAutoCloseEpicsToo); err != nil { + t.Fatal(err) + } + if len(c.Repos) != 1 || c.Repos["Acme/Widgets"].ParentAutoClose != ParentAutoCloseEpicsToo { + t.Errorf("repos = %v", c.Repos) + } + }) + t.Run("rejects bad value and unmonitored repo", func(t *testing.T) { + c := newCfg() + if err := c.SetParentAutoClose("widgets", "maybe"); err == nil { + t.Error("bad value accepted") + } + if err := c.SetParentAutoClose("widgets", ""); err == nil { + t.Error("empty value accepted") + } + if err := c.SetParentAutoClose("other/thing", ParentAutoCloseOff); !errors.Is(err, ErrRepoNotMonitored) { + t.Errorf("unmonitored repo err = %v", err) + } + if len(c.Repos) != 0 { + t.Errorf("a refused set stored %v", c.Repos) + } + }) + t.Run("nil config", func(t *testing.T) { + var c *Config + if err := c.SetParentAutoClose("widgets", ParentAutoCloseOff); err == nil { + t.Error("nil config accepted a set") + } + }) +} diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 73811c04cf..8ef64ce68b 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -555,6 +555,9 @@ func (s *Server) RegisterAPI(deps *Dependencies) { // project.reference_repos editor on the Repos tab (#18136, api_config_reference_repos.go). s.mux.HandleFunc("GET /api/config/reference-repos", s.handleReferenceReposGet) s.mux.HandleFunc("PUT /api/config/reference-repos", s.handleReferenceReposPut) + // repos..parent_autoclose editor on the Repos tab (#19070, api_config_parent_autoclose.go). + s.mux.HandleFunc("GET /api/config/repos/parent-autoclose", s.handleParentAutoCloseGet) + s.mux.HandleFunc("PUT /api/config/repos/parent-autoclose", s.handleParentAutoClosePut) // project.remote_write_identity on the same Settings section (#18516, api_config_remote_write_identity.go). s.mux.HandleFunc("PUT /api/config/reference-repos/write-identity", s.handleRemoteWriteIdentityPut) // The hive owner's GitHub identity for remote repos (#18197, diff --git a/src/pkg/dashboard/api_config_parent_autoclose.go b/src/pkg/dashboard/api_config_parent_autoclose.go new file mode 100644 index 0000000000..d17197d8c1 --- /dev/null +++ b/src/pkg/dashboard/api_config_parent_autoclose.go @@ -0,0 +1,171 @@ +package dashboard + +import ( + "errors" + "net/http" + "strings" + + "github.com/hivecommons/hive/pkg/config" +) + +// The per-repo parent auto-close policy (repos..parent_autoclose, +// hivecommons/hive#18869) editor on the Settings Repos tab +// (hivecommons/hive#19070). +// +// The policy decides whether the issue-stage pass closes a decomposed parent +// once every child is closed. Both endpoints are OWNER-ONLY: the value changes +// which issues the hive closes on its own. A PUT is validated before anything +// changes, applies without a restart (the stage pass reads the live config +// through ParentAutoCloseFor), is audited, and is rolled back when the config +// file cannot be written. +// +// Tracking issues (hive/tracking label, marker, "Keep +// this issue open") and parents a person reopened are never auto-closed under +// any value; the editor says so, and nothing here can change that. + +// parentAutoCloseOption is one choice the editor offers. +type parentAutoCloseOption struct { + Value string `json:"value"` + Label string `json:"label"` + Description string `json:"description"` +} + +// parentAutoCloseRepo is one monitored repo and its policy. +type parentAutoCloseRepo struct { + Repo string `json:"repo"` + // Value is the effective policy: "true", "false" or "epics_too". + Value string `json:"value"` + // Explicit is true when the repo carries its own value, false when it + // inherits the default. + Explicit bool `json:"explicit"` +} + +// parentAutoCloseResponse is the GET/PUT response body. +type parentAutoCloseResponse struct { + // Default is the policy a repo with no value gets. + Default string `json:"default"` + Options []parentAutoCloseOption `json:"options"` + // Repos lists every monitored repo (project.repos), in config order. + Repos []parentAutoCloseRepo `json:"repos"` +} + +// parentAutoCloseOptions is the vocabulary the editor offers, in display +// order. The wording is the contract the Settings card and the docs share. +var parentAutoCloseOptions = []parentAutoCloseOption{ + {config.ParentAutoCloseOn, "Close finished parents (default)", + "Close a split-up parent issue once all of its children are closed, except parents labelled epic or hold."}, + {config.ParentAutoCloseEpicsToo, "Also close epics and holds", + "As above, and also close parents labelled epic or hold when all of their children are closed."}, + {config.ParentAutoCloseOff, "Never auto-close parents", + "The hive never closes a parent issue itself; a person closes it."}, +} + +func parentAutoCloseResponseFor(cfg *config.Config) parentAutoCloseResponse { + out := parentAutoCloseResponse{ + Default: config.ParentAutoCloseOn, + Options: parentAutoCloseOptions, + Repos: make([]parentAutoCloseRepo, 0, len(cfg.Project.Repos)), + } + for _, repo := range cfg.Project.Repos { + repo = strings.TrimSpace(repo) + if repo == "" { + continue + } + out.Repos = append(out.Repos, parentAutoCloseRepo{ + Repo: repo, + Value: cfg.ParentAutoCloseFor(repo), + Explicit: cfg.ParentAutoCloseExplicit(repo), + }) + } + return out +} + +// handleParentAutoCloseGet returns the policy of every monitored repo. +func (s *Server) handleParentAutoCloseGet(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + if s.deps == nil || s.deps.Config == nil { + jsonError(w, "config unavailable", http.StatusServiceUnavailable) + return + } + jsonResponse(w, parentAutoCloseResponseFor(s.deps.Config)) +} + +// handleParentAutoClosePut sets one monitored repo's policy. Body: +// {"repo": "owner/name", "value": "true" | "epics_too" | "false"}. Choosing +// "true" (the default) clears the repo's override. +func (s *Server) handleParentAutoClosePut(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + if s.deps == nil || s.deps.Config == nil { + jsonError(w, "config unavailable", http.StatusServiceUnavailable) + return + } + var body struct { + Repo string `json:"repo"` + Value string `json:"value"` + } + if err := decodeBody(r, &body); err != nil { + jsonError(w, "invalid body", http.StatusBadRequest) + return + } + body.Repo = strings.TrimSpace(body.Repo) + if body.Repo == "" { + jsonError(w, "repo is required", http.StatusBadRequest) + return + } + cfg := s.deps.Config + + // --- validate before mutating anything --- + if _, ok := config.NormalizeParentAutoClose(body.Value); !ok { + jsonError(w, `value must be "true", "epics_too" or "false"`, http.StatusBadRequest) + return + } + previous := cfg.ParentAutoCloseFor(body.Repo) + prevEntry, hadEntry := cfg.RepoSettingsFor(body.Repo) + + // --- apply --- + if err := cfg.SetParentAutoClose(body.Repo, body.Value); err != nil { + if errors.Is(err, config.ErrRepoNotMonitored) { + jsonError(w, err.Error(), http.StatusNotFound) + return + } + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + if err := s.saveConfig(); err != nil { + // Memory must not diverge from the file: put the old value back. + restoreParentAutoClose(cfg, body.Repo, previous, prevEntry, hadEntry) + if s.logger != nil { + s.logger.Error("failed to persist config after parent auto-close update", "error", err) + } + jsonError(w, "failed to save config; parent auto-close unchanged", http.StatusInternalServerError) + return + } + effective := cfg.ParentAutoCloseFor(body.Repo) + s.auditFromRequest(r, "config_repo_parent_autoclose", auditDetail( + "section", "repos", + "repo", body.Repo, + "previous", previous, + "value", effective, + ), "") + if s.logger != nil { + s.logger.Info("parent auto-close updated via runtime settings", + "repo", body.Repo, "previous", previous, "value", effective) + } + jsonResponse(w, parentAutoCloseResponseFor(cfg)) +} + +// restoreParentAutoClose puts a repo's previous parent_autoclose value back +// after a failed save. A repo that had an explicit non-default value gets it +// back; one that inherited the default goes back to inheriting it. +func restoreParentAutoClose(cfg *config.Config, repo, previous string, prev config.RepoSettings, had bool) { + if had && prev.ParentAutoClose != "" { + if norm, ok := config.NormalizeParentAutoClose(prev.ParentAutoClose); ok { + previous = norm + } + } + _ = cfg.SetParentAutoClose(repo, previous) +} diff --git a/src/pkg/dashboard/api_config_parent_autoclose_test.go b/src/pkg/dashboard/api_config_parent_autoclose_test.go new file mode 100644 index 0000000000..d6dc932af2 --- /dev/null +++ b/src/pkg/dashboard/api_config_parent_autoclose_test.go @@ -0,0 +1,137 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// hivecommons/hive#19070: the owner-only repos..parent_autoclose editor. + +const parentAutoClosePath = "/api/config/repos/parent-autoclose" + +func decodeParentAutoClose(t *testing.T, body []byte) parentAutoCloseResponse { + t.Helper() + var got parentAutoCloseResponse + if err := json.Unmarshal(body, &got); err != nil { + t.Fatalf("decode: %v (%s)", err, body) + } + return got +} + +func TestParentAutoClose_OwnerOnly(t *testing.T) { + s := covApiServer(t) + if rec := doGetNoRole(s, parentAutoClosePath); rec.Code != http.StatusForbidden { + t.Fatalf("non-owner GET: expected 403, got %d", rec.Code) + } + if rec := doPutNoRole(s, parentAutoClosePath, `{"repo":"repo1","value":"false"}`); rec.Code != http.StatusForbidden { + t.Fatalf("non-owner PUT: expected 403, got %d", rec.Code) + } + if got := s.deps.Config.ParentAutoCloseFor("repo1"); got != config.ParentAutoCloseOn { + t.Fatalf("a refused PUT changed the policy to %q", got) + } +} + +func TestParentAutoClose_GetListsMonitoredReposAndOptions(t *testing.T) { + s := covApiServer(t) + s.deps.Config.Repos = map[string]config.RepoSettings{"repo1": {ParentAutoClose: config.ParentAutoCloseEpicsToo}} + s.deps.Config.Project.Repos = []string{"repo1", "repo2"} + rec := doOwnerGet(s, parentAutoClosePath) + if rec.Code != http.StatusOK { + t.Fatalf("GET: %d %s", rec.Code, rec.Body.String()) + } + got := decodeParentAutoClose(t, rec.Body.Bytes()) + if got.Default != config.ParentAutoCloseOn || len(got.Options) != 3 { + t.Fatalf("default=%q options=%v", got.Default, got.Options) + } + want := []parentAutoCloseRepo{ + {Repo: "repo1", Value: config.ParentAutoCloseEpicsToo, Explicit: true}, + {Repo: "repo2", Value: config.ParentAutoCloseOn, Explicit: false}, + } + if len(got.Repos) != len(want) { + t.Fatalf("repos = %v", got.Repos) + } + for i := range want { + if got.Repos[i] != want[i] { + t.Errorf("repos[%d] = %+v, want %+v", i, got.Repos[i], want[i]) + } + } +} + +func TestParentAutoClose_PutAppliesLiveAndAudits(t *testing.T) { + s := covApiServer(t) + cfg := s.deps.Config + rec := doPut(s, parentAutoClosePath, map[string]any{"repo": "myorg/repo1", "value": "epics_too"}) + if rec.Code != http.StatusOK { + t.Fatalf("PUT: %d %s", rec.Code, rec.Body.String()) + } + if got := cfg.ParentAutoCloseFor("repo1"); got != config.ParentAutoCloseEpicsToo { + t.Fatalf("live policy = %q, want epics_too", got) + } + if got := decodeParentAutoClose(t, rec.Body.Bytes()); len(got.Repos) != 1 || got.Repos[0].Value != config.ParentAutoCloseEpicsToo || !got.Repos[0].Explicit { + t.Fatalf("response repos = %+v", got.Repos) + } + if s.audit != nil { + found := false + for _, entry := range s.audit.Recent(50) { + if entry.Action == "config_repo_parent_autoclose" { + found = true + } + } + if !found { + t.Error("missing config_repo_parent_autoclose audit") + } + } + + // Choosing the default clears the override. + if rec := doPut(s, parentAutoClosePath, map[string]any{"repo": "repo1", "value": "true"}); rec.Code != http.StatusOK { + t.Fatalf("PUT default: %d %s", rec.Code, rec.Body.String()) + } + if cfg.ParentAutoCloseExplicit("repo1") || len(cfg.Repos) != 0 { + t.Fatalf("default must leave no override, got %v", cfg.Repos) + } +} + +func TestParentAutoClose_PutValidation(t *testing.T) { + s := covApiServer(t) + cases := []struct { + name string + body map[string]any + code int + }{ + {"bad value", map[string]any{"repo": "repo1", "value": "maybe"}, http.StatusBadRequest}, + {"empty value", map[string]any{"repo": "repo1", "value": ""}, http.StatusBadRequest}, + {"missing repo", map[string]any{"value": "false"}, http.StatusBadRequest}, + {"unmonitored repo", map[string]any{"repo": "other/thing", "value": "false"}, http.StatusNotFound}, + } + for _, tc := range cases { + if rec := doPut(s, parentAutoClosePath, tc.body); rec.Code != tc.code { + t.Errorf("%s: code %d, want %d (%s)", tc.name, rec.Code, tc.code, rec.Body.String()) + } + } + if len(s.deps.Config.Repos) != 0 { + t.Fatalf("a refused PUT stored %v", s.deps.Config.Repos) + } +} + +func TestRestoreParentAutoClose(t *testing.T) { + cfg := &config.Config{Project: config.ProjectConfig{Org: "acme", Repos: []string{"widgets"}}} + if err := cfg.SetParentAutoClose("widgets", config.ParentAutoCloseOff); err != nil { + t.Fatal(err) + } + prev, had := cfg.RepoSettingsFor("widgets") + if err := cfg.SetParentAutoClose("widgets", config.ParentAutoCloseEpicsToo); err != nil { + t.Fatal(err) + } + restoreParentAutoClose(cfg, "widgets", config.ParentAutoCloseOff, prev, had) + if got := cfg.ParentAutoCloseFor("widgets"); got != config.ParentAutoCloseOff { + t.Fatalf("restored = %q, want false", got) + } + // A repo that inherited the default goes back to inheriting it. + restoreParentAutoClose(cfg, "widgets", config.ParentAutoCloseOn, config.RepoSettings{}, false) + if cfg.ParentAutoCloseExplicit("widgets") { + t.Fatal("restore to default left an override") + } +} diff --git a/src/pkg/dashboard/audit.go b/src/pkg/dashboard/audit.go index 57b0a1ce24..d6942b6b36 100644 --- a/src/pkg/dashboard/audit.go +++ b/src/pkg/dashboard/audit.go @@ -106,6 +106,7 @@ var auditSensitiveActions = map[string]bool{ "config_governor_watchdog": true, "config_governor_work_source": true, "config_reference_repos": true, + "config_repo_parent_autoclose": true, "config_remote_write_identity": true, "config_review": true, "config_write_surface": true, diff --git a/src/pkg/dashboard/parent_autoclose_editor.test.js b/src/pkg/dashboard/parent_autoclose_editor.test.js new file mode 100644 index 0000000000..e6cf16cd7c --- /dev/null +++ b/src/pkg/dashboard/parent_autoclose_editor.test.js @@ -0,0 +1,129 @@ +// Settings -> Repos -> Parent auto-close editor (hivecommons/hive#19070): +// renderParentAutoClosePanel paints one row per monitored repo with a select of +// the three policies, shows the effective value, and Save PUTs only the rows +// that changed to /api/config/repos/parent-autoclose. A server refusal is shown +// verbatim and the edits are kept. +// Run: node --test src/pkg/dashboard/*.test.js +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); +const ASYNC_PREFIX = 'async '; +const fnSrc = name => { + let start = html.indexOf('function ' + name + '('); + assert.ok(start >= 0, name + ' not found'); + if (html.slice(start - ASYNC_PREFIX.length, start) === ASYNC_PREFIX) start -= ASYNC_PREFIX.length; + let depth = 0; + for (let i = html.indexOf('{', start); i < html.length; i++) { + if (html[i] === '{') depth++; + else if (html[i] === '}' && --depth === 0) return html.slice(start, i + 1); + } + throw new Error('unbalanced ' + name); +}; + +// Minimal fake DOM: elements with children, className, textContent (which +// clears children, as in the browser), attributes and listeners. +const makeDoc = () => { + const doc = {}; + const makeEl = tag => { + const el = { tag, children: [], listeners: {}, className: '', title: '', _text: '' }; + Object.defineProperty(el, 'textContent', { + get() { return el._text + el.children.map(c => c.textContent).join(''); }, + set(v) { el._text = String(v); el.children = []; }, + }); + el.appendChild = c => { el.children.push(c); return c; }; + el.addEventListener = (type, fn) => { (el.listeners[type] = el.listeners[type] || []).push(fn); }; + el.fire = (type, ev) => (el.listeners[type] || []).map(fn => fn(ev || {})); + el.find = pred => { + const out = []; + const walk = n => { if (pred(n)) out.push(n); (n.children || []).forEach(walk); }; + walk(el); + return out; + }; + return el; + }; + doc.createElement = makeEl; + doc.createTextNode = text => ({ tag: '#text', children: [], className: '', textContent: String(text) }); + doc.getElementById = () => null; + return doc; +}; + + +const OPTIONS = [ + { value: 'true', label: 'Close finished parents (default)', description: 'close finished parents' }, + { value: 'epics_too', label: 'Also close epics and holds', description: 'close epics too' }, + { value: 'false', label: 'Never auto-close parents', description: 'never close' }, +]; + +const setup = ({ repos, put }) => { + const doc = makeDoc(); + const toasts = []; + const calls = []; + const fetchStub = async (url, opts) => { + calls.push({ url, opts, body: JSON.parse(opts.body) }); + return put(calls[calls.length - 1]); + }; + const render = new Function('document', 'fetch', 'showToast', '_inceptionAuthHeaders', 'saveErrorMessage', + fnSrc('parentAutoCloseNode') + '\n' + fnSrc('renderParentAutoClosePanel') + '\nreturn renderParentAutoClosePanel;')( + doc, fetchStub, (m, k) => toasts.push([m, k]), () => ({}), async res => res.errorMessage); + const host = doc.createElement('div'); + render(host, { default: 'true', options: OPTIONS, repos }); + return { host, toasts, calls }; +}; + +const rows = host => host.find(n => String(n.className).startsWith('config-list-item config-repo-row')); +const selects = node => node.find(n => n.tag === 'select'); +const saveButton = host => host.find(n => n.tag === 'button' && n.textContent === 'Save parent auto-close')[0]; +const choose = (row, value) => { const sel = selects(row)[0]; sel.value = value; sel.fire('change'); }; + +test('one row per monitored repo with three options, the effective value and the yaml hint', () => { + const { host } = setup({ repos: [{ repo: 'acme/a', value: 'true', explicit: false }, { repo: 'acme/b', value: 'epics_too', explicit: true }], put: () => { throw new Error('no save'); } }); + const r = rows(host); + assert.strictEqual(r.length, 2); + assert.strictEqual(selects(r[0])[0].children.length, 3); + assert.deepStrictEqual(selects(r[1])[0].children.map(o => o.selected), [false, true, false]); + assert.match(r[0].find(n => n.className === 'rt-inherit')[0].textContent, /Close finished parents \(default\) \(inherited\)/); + assert.match(r[1].find(n => n.className === 'rt-inherit')[0].textContent, /^now: Also close epics and holds$/); + assert.ok(host.textContent.includes('repos..parent_autoclose')); + assert.match(host.textContent, /never closed again/); + assert.match(host.textContent, /never auto-closed/); +}); + +test('Save is disabled until a row changes, then PUTs only the changed rows', async () => { + const { host, calls, toasts } = setup({ + repos: [{ repo: 'acme/a', value: 'true', explicit: false }, { repo: 'acme/b', value: 'false', explicit: true }], + put: call => ({ ok: true, json: async () => ({ default: 'true', repos: [{ repo: call.body.repo, value: call.body.value, explicit: call.body.value !== 'true' }] }) }), + }); + assert.strictEqual(saveButton(host).disabled, true); + choose(rows(host)[0], 'epics_too'); + assert.strictEqual(saveButton(host).disabled, false); + await saveButton(host).fire('click')[0]; + assert.strictEqual(calls.length, 1); + assert.strictEqual(calls[0].url, '/api/config/repos/parent-autoclose'); + assert.strictEqual(calls[0].opts.method, 'PUT'); + assert.deepStrictEqual(calls[0].body, { repo: 'acme/a', value: 'epics_too' }); + assert.deepStrictEqual(toasts, [['Parent auto-close saved', 'success']]); + assert.match(rows(host)[0].find(n => n.className === 'rt-inherit')[0].textContent, /^now: Also close epics and holds$/); + assert.strictEqual(saveButton(host).disabled, true); +}); + +test('a refusal is shown as-is and the edit is kept', async () => { + const { host, calls, toasts } = setup({ + repos: [{ repo: 'acme/a', value: 'true', explicit: false }], + put: () => ({ ok: false, status: 400, errorMessage: 'value must be one of the three' }), + }); + choose(rows(host)[0], 'false'); + await saveButton(host).fire('click')[0]; + assert.strictEqual(calls.length, 1); + assert.deepStrictEqual(toasts, []); + assert.match(host.textContent, /acme\/a: value must be one of the three/); + assert.strictEqual(selects(rows(host)[0])[0].children.find(o => o.selected).value, 'false'); + assert.strictEqual(saveButton(host).disabled, false); +}); + +test('no monitored repos says so', () => { + const { host } = setup({ repos: [], put: () => { throw new Error('no save'); } }); + assert.match(host.textContent, /No monitored repos configured/); +}); diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index c99d035dd9..fac2e7641c 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -579,7 +579,6 @@ project.repos[] # TODO #11854 providers.status.enabled # TODO #11854 removed_agents[] # TODO #11854 repos..agents_md_max_bytes # TODO #18495 (per-repo AGENTS.md cap; Settings control pending) -repos..parent_autoclose # TODO #18869 (per-repo decomposed-parent auto-close policy; Settings control pending) repos..review_preflight.block_severity # TODO #19069 (review preflight; Settings control pending) repos..review_preflight.cache_ttl # TODO #19069 (review preflight; Settings control pending) repos..review_preflight.dependencies # TODO #19069 (review preflight; Settings control pending) diff --git a/src/pkg/dashboard/static-src/js/config-governor.js b/src/pkg/dashboard/static-src/js/config-governor.js index 345ecb3dd6..c3e147d6b2 100644 --- a/src/pkg/dashboard/static-src/js/config-governor.js +++ b/src/pkg/dashboard/static-src/js/config-governor.js @@ -1001,6 +1001,8 @@ /* Reference repos (#18136): painted asynchronously from their own owner-only endpoint, like the Security tab's write allowlist. */ loadReferenceRepos(); + /* Parent auto-close (#19070): per-repo policy, same async pattern. */ + loadParentAutoClose(); const primary = _configState.data.primaryRepo || ''; const selfAuthDefault = _configState.data.selfAuthorizationHold !== false; const selfAuthEnvLocked = !!_configState.data.selfAuthorizationHoldEnvLocked; @@ -1149,6 +1151,8 @@
Reference repos ${yamlHint('project.reference_repos[]')} ${settingHelpMark('settings', 'repos', 'Reference repos', 'Repositories outside this project that agents may clone and read but do not manage: no queue, no kicks, no work items. Read-only by default; a write opt-in allows opening issues and/or PRs there with a credential the hive verifies on save. Post on other projects as (project.remote_write_identity) picks whether those posts appear as the hive bot or as you. A repo is either monitored above or a reference repo, never both.')}
Loading…
+
Parent auto-close ${yamlHint('repos..parent_autoclose')} ${settingHelpMark('settings', 'repos', 'Parent auto-close', 'Per repo: whether the hive closes a split-up parent issue once all of its children are closed. Close finished parents (default) skips parents labelled epic or hold; Also close epics and holds includes them; Never auto-close parents leaves every parent to a person. A parent a person reopened is never closed again, and issues marked as tracking issues are never auto-closed.')}
+
Loading…
${anyLabelDriven ? `
diff --git a/src/pkg/dashboard/static-src/js/config-parent-autoclose.js b/src/pkg/dashboard/static-src/js/config-parent-autoclose.js new file mode 100644 index 0000000000..87d3b3fb5c --- /dev/null +++ b/src/pkg/dashboard/static-src/js/config-parent-autoclose.js @@ -0,0 +1,135 @@ + /* Parent auto-close editor (#19070): repos..parent_autoclose, one + choice per monitored repo, loaded from the owner-only + /api/config/repos/parent-autoclose endpoint and saved back to it. + Rendered with DOM nodes and textContent only, so a repo name or an + option string is never parsed as markup. The server validates the value + and applies it without a restart; its error message is shown as-is and + nothing is saved on an error. */ + const PARENT_AUTOCLOSE_HOST_ID = 'cfg-parent-autoclose-host'; + + function parentAutoCloseNode(tag, className, text) { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + } + + async function loadParentAutoClose() { + let host = null; + try { + const r = await fetch('/api/config/repos/parent-autoclose'); + host = document.getElementById(PARENT_AUTOCLOSE_HOST_ID); + if (!host) return; + if (r.status === 403) { + host.textContent = ''; + host.appendChild(parentAutoCloseNode('div', 'fs-sm text-muted', 'Only the hive owner can view and edit parent auto-close.')); + return; + } + if (!r.ok) throw new Error('HTTP ' + r.status); + renderParentAutoClosePanel(host, await r.json()); + } catch (e) { + host = host || document.getElementById(PARENT_AUTOCLOSE_HOST_ID); + if (!host) return; + host.textContent = ''; + host.appendChild(parentAutoCloseNode('div', 'fs-sm text-danger', 'Failed to load parent auto-close: ' + e.message)); + } + } + + /* renderParentAutoClosePanel paints one row per monitored repo: a select + with the three options, the effective value, and the one-line + explanation of the chosen option. Save sends only the rows that + changed. */ + function renderParentAutoClosePanel(host, data) { + if (!host) return; + data = data || {}; + const options = Array.isArray(data.options) ? data.options : []; + const repos = (Array.isArray(data.repos) ? data.repos : []).map(r => ({ + repo: r.repo || '', saved: r.value || data.default || 'true', value: r.value || data.default || 'true', explicit: !!r.explicit, + })); + const labelOf = v => { const o = options.find(x => x.value === v); return o ? o.label : v; }; + const textOf = v => { const o = options.find(x => x.value === v); return o ? o.description : ''; }; + host.textContent = ''; + host.appendChild(parentAutoCloseNode('p', 'config-help', + 'When every child of a split-up parent issue is closed, the hive can close the parent too. Choose, per repo, how far that goes. ' + + 'A parent that a person reopened after the hive closed it is never closed again, whatever you choose. ' + + 'Issues marked as tracking issues (the hive/tracking label, the hive:tracking marker or "Keep this issue open") are never auto-closed; only you closing them from the dashboard does that. ' + + 'Saving applies the change without a restart.')); + const list = parentAutoCloseNode('div', 'config-list'); + host.appendChild(list); + const statusEl = parentAutoCloseNode('div', 'fs-sm'); + const setStatus = (msg, cls) => { statusEl.textContent = msg; statusEl.className = 'fs-sm ' + (cls || 'text-muted'); }; + const saveBtn = parentAutoCloseNode('button', 'hv-btn btn-primary btn-sm', 'Save parent auto-close'); + + const dirty = () => repos.filter(r => r.value !== r.saved); + const syncSave = () => { saveBtn.disabled = dirty().length === 0; }; + + const paintRows = () => { + list.textContent = ''; + if (!repos.length) list.appendChild(parentAutoCloseNode('div', 'fs-sm text-muted mb-3', 'No monitored repos configured')); + repos.forEach(entry => { + const row = parentAutoCloseNode('div', 'config-list-item config-repo-row'); + row.appendChild(parentAutoCloseNode('span', 'config-repo-name', entry.repo)); + const select = document.createElement('select'); + select.title = 'Parent auto-close policy for ' + entry.repo; + options.forEach(o => { + const opt = document.createElement('option'); + opt.value = o.value; + opt.textContent = o.label; + opt.selected = o.value === entry.value; + select.appendChild(opt); + }); + const note = parentAutoCloseNode('span', 'text-muted fs-sm', textOf(entry.value)); + select.addEventListener('change', () => { + entry.value = select.value; + note.textContent = textOf(entry.value); + setStatus(''); + syncSave(); + }); + row.appendChild(select); + row.appendChild(parentAutoCloseNode('span', 'rt-inherit', 'now: ' + labelOf(entry.saved) + (entry.explicit ? '' : ' (inherited)'))); + row.appendChild(note); + list.appendChild(row); + }); + }; + + const hints = parentAutoCloseNode('div', 'config-help'); + const hint = parentAutoCloseNode('span', 'settings-yaml-hint', 'YAML '); + hint.appendChild(parentAutoCloseNode('code', '', 'repos..parent_autoclose')); + hints.appendChild(hint); + host.appendChild(hints); + + const actions = parentAutoCloseNode('div', 'config-list-add'); + actions.appendChild(saveBtn); + actions.appendChild(statusEl); + host.appendChild(actions); + paintRows(); + syncSave(); + + saveBtn.addEventListener('click', async () => { + const pending = dirty(); + if (!pending.length) return; + saveBtn.disabled = true; + setStatus('Saving…'); + try { + for (const entry of pending) { + const res = await fetch('/api/config/repos/parent-autoclose', { + method: 'PUT', + headers: _inceptionAuthHeaders(), + body: JSON.stringify({ repo: entry.repo, value: entry.value }), + }); + if (!res.ok) throw new Error(entry.repo + ': ' + await saveErrorMessage(res)); + const d = await res.json(); + const fresh = (d.repos || []).find(x => x.repo === entry.repo); + entry.saved = entry.value; + entry.explicit = fresh ? !!fresh.explicit : entry.value !== (d.default || 'true'); + } + paintRows(); + setStatus(''); + showToast('Parent auto-close saved', 'success'); + } catch (e) { + paintRows(); + setStatus(e.message, 'text-danger'); + } + syncSave(); + }); + } diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index c1bda2d851..4eb1c490a4 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -174,6 +174,7 @@ js/config-webhooks.js js/config-hub.js js/config-agent.js js/config-governor.js +js/config-parent-autoclose.js js/config-workflows.js js/config-workflows-handoff.js js/config-workflows-library.js diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 922b0b86aa..d837ad21ba 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -72189,6 +72189,8 @@

Clanker-requested PRs

/* Reference repos (#18136): painted asynchronously from their own owner-only endpoint, like the Security tab's write allowlist. */ loadReferenceRepos(); + /* Parent auto-close (#19070): per-repo policy, same async pattern. */ + loadParentAutoClose(); const primary = _configState.data.primaryRepo || ''; const selfAuthDefault = _configState.data.selfAuthorizationHold !== false; const selfAuthEnvLocked = !!_configState.data.selfAuthorizationHoldEnvLocked; @@ -72337,6 +72339,8 @@

Clanker-requested PRs

Reference repos ${yamlHint('project.reference_repos[]')} ${settingHelpMark('settings', 'repos', 'Reference repos', 'Repositories outside this project that agents may clone and read but do not manage: no queue, no kicks, no work items. Read-only by default; a write opt-in allows opening issues and/or PRs there with a credential the hive verifies on save. Post on other projects as (project.remote_write_identity) picks whether those posts appear as the hive bot or as you. A repo is either monitored above or a reference repo, never both.')}
Loading…
+
Parent auto-close ${yamlHint('repos..parent_autoclose')} ${settingHelpMark('settings', 'repos', 'Parent auto-close', 'Per repo: whether the hive closes a split-up parent issue once all of its children are closed. Close finished parents (default) skips parents labelled epic or hold; Also close epics and holds includes them; Never auto-close parents leaves every parent to a person. A parent a person reopened is never closed again, and issues marked as tracking issues are never auto-closed.')}
+
Loading…
${anyLabelDriven ? `
@@ -73434,6 +73438,141 @@

Agent Watchdog

— fixed progression; the last step is the cap.
`; } + /* Parent auto-close editor (#19070): repos..parent_autoclose, one + choice per monitored repo, loaded from the owner-only + /api/config/repos/parent-autoclose endpoint and saved back to it. + Rendered with DOM nodes and textContent only, so a repo name or an + option string is never parsed as markup. The server validates the value + and applies it without a restart; its error message is shown as-is and + nothing is saved on an error. */ + const PARENT_AUTOCLOSE_HOST_ID = 'cfg-parent-autoclose-host'; + + function parentAutoCloseNode(tag, className, text) { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + } + + async function loadParentAutoClose() { + let host = null; + try { + const r = await fetch('/api/config/repos/parent-autoclose'); + host = document.getElementById(PARENT_AUTOCLOSE_HOST_ID); + if (!host) return; + if (r.status === 403) { + host.textContent = ''; + host.appendChild(parentAutoCloseNode('div', 'fs-sm text-muted', 'Only the hive owner can view and edit parent auto-close.')); + return; + } + if (!r.ok) throw new Error('HTTP ' + r.status); + renderParentAutoClosePanel(host, await r.json()); + } catch (e) { + host = host || document.getElementById(PARENT_AUTOCLOSE_HOST_ID); + if (!host) return; + host.textContent = ''; + host.appendChild(parentAutoCloseNode('div', 'fs-sm text-danger', 'Failed to load parent auto-close: ' + e.message)); + } + } + + /* renderParentAutoClosePanel paints one row per monitored repo: a select + with the three options, the effective value, and the one-line + explanation of the chosen option. Save sends only the rows that + changed. */ + function renderParentAutoClosePanel(host, data) { + if (!host) return; + data = data || {}; + const options = Array.isArray(data.options) ? data.options : []; + const repos = (Array.isArray(data.repos) ? data.repos : []).map(r => ({ + repo: r.repo || '', saved: r.value || data.default || 'true', value: r.value || data.default || 'true', explicit: !!r.explicit, + })); + const labelOf = v => { const o = options.find(x => x.value === v); return o ? o.label : v; }; + const textOf = v => { const o = options.find(x => x.value === v); return o ? o.description : ''; }; + host.textContent = ''; + host.appendChild(parentAutoCloseNode('p', 'config-help', + 'When every child of a split-up parent issue is closed, the hive can close the parent too. Choose, per repo, how far that goes. ' + + 'A parent that a person reopened after the hive closed it is never closed again, whatever you choose. ' + + 'Issues marked as tracking issues (the hive/tracking label, the hive:tracking marker or "Keep this issue open") are never auto-closed; only you closing them from the dashboard does that. ' + + 'Saving applies the change without a restart.')); + const list = parentAutoCloseNode('div', 'config-list'); + host.appendChild(list); + const statusEl = parentAutoCloseNode('div', 'fs-sm'); + const setStatus = (msg, cls) => { statusEl.textContent = msg; statusEl.className = 'fs-sm ' + (cls || 'text-muted'); }; + const saveBtn = parentAutoCloseNode('button', 'hv-btn btn-primary btn-sm', 'Save parent auto-close'); + + const dirty = () => repos.filter(r => r.value !== r.saved); + const syncSave = () => { saveBtn.disabled = dirty().length === 0; }; + + const paintRows = () => { + list.textContent = ''; + if (!repos.length) list.appendChild(parentAutoCloseNode('div', 'fs-sm text-muted mb-3', 'No monitored repos configured')); + repos.forEach(entry => { + const row = parentAutoCloseNode('div', 'config-list-item config-repo-row'); + row.appendChild(parentAutoCloseNode('span', 'config-repo-name', entry.repo)); + const select = document.createElement('select'); + select.title = 'Parent auto-close policy for ' + entry.repo; + options.forEach(o => { + const opt = document.createElement('option'); + opt.value = o.value; + opt.textContent = o.label; + opt.selected = o.value === entry.value; + select.appendChild(opt); + }); + const note = parentAutoCloseNode('span', 'text-muted fs-sm', textOf(entry.value)); + select.addEventListener('change', () => { + entry.value = select.value; + note.textContent = textOf(entry.value); + setStatus(''); + syncSave(); + }); + row.appendChild(select); + row.appendChild(parentAutoCloseNode('span', 'rt-inherit', 'now: ' + labelOf(entry.saved) + (entry.explicit ? '' : ' (inherited)'))); + row.appendChild(note); + list.appendChild(row); + }); + }; + + const hints = parentAutoCloseNode('div', 'config-help'); + const hint = parentAutoCloseNode('span', 'settings-yaml-hint', 'YAML '); + hint.appendChild(parentAutoCloseNode('code', '', 'repos..parent_autoclose')); + hints.appendChild(hint); + host.appendChild(hints); + + const actions = parentAutoCloseNode('div', 'config-list-add'); + actions.appendChild(saveBtn); + actions.appendChild(statusEl); + host.appendChild(actions); + paintRows(); + syncSave(); + + saveBtn.addEventListener('click', async () => { + const pending = dirty(); + if (!pending.length) return; + saveBtn.disabled = true; + setStatus('Saving…'); + try { + for (const entry of pending) { + const res = await fetch('/api/config/repos/parent-autoclose', { + method: 'PUT', + headers: _inceptionAuthHeaders(), + body: JSON.stringify({ repo: entry.repo, value: entry.value }), + }); + if (!res.ok) throw new Error(entry.repo + ': ' + await saveErrorMessage(res)); + const d = await res.json(); + const fresh = (d.repos || []).find(x => x.repo === entry.repo); + entry.saved = entry.value; + entry.explicit = fresh ? !!fresh.explicit : entry.value !== (d.default || 'true'); + } + paintRows(); + setStatus(''); + showToast('Parent auto-close saved', 'success'); + } catch (e) { + paintRows(); + setStatus(e.message, 'text-danger'); + } + syncSave(); + }); + } // Workflow-model bindings (hivecommons/hive#17620, RFC phase 2). // // Each repo row on Settings → Repos carries a "Workflow" select: hive-default