diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index c856a73d7..4717364cf 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -91,7 +91,7 @@ {"_type":"issue","id":"archie-core-g7tm","title":"telegram: finalize the reply through a live context, matching the error branch","description":"The success path calls live.finalize(turnCtx, reply) with the raw cancellable turn context (telegram.go:582), while the error branch two lines above deliberately uses context.WithoutCancel(turnCtx). If /stop lands during finalize, the rich edit, the plain-text retry, and the split-send fallback all abort with context.Canceled (go-telegram/bot builds requests with NewRequestWithContext), so the authoritative reply is never delivered and the live message keeps the ▌ cursor forever. The reply is persisted to the ledger, so the loss is delivery-level — but the user sees a frozen half-answer.\n\nFailure: a long tool-using turn is /stop-ped as it completes; turnCtx is cancelled mid-finalize; every send fails on the dead context; the chat shows the last live frame with a blinking cursor and no final answer.\n\nFound by code-review of PR #476 (feat/467, merged 98e8dda).","design":"live.finalize(context.WithoutCancel(turnCtx), reply) — the one-liner the error branch already uses. Consider making finalize take a live context internally rather than trusting each caller to remember.","acceptance_criteria":"A /stop landing mid-finalize still delivers the authoritative reply and drops the cursor; a test covers the cancellable-context finalize path.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-14T14:43:08Z","created_by":"Sam Catlow","updated_at":"2026-08-14T15:07:36Z","started_at":"2026-08-14T14:53:28Z","closed_at":"2026-08-14T15:03:28Z","close_reason":"Fixed in internal/channels/telegram/live.go and telegram.go: finalize/abandon strip context cancellation before sending (mirroring each other), ToolCall escapes Markdown metacharacters via bot.EscapeMarkdown, splitLongMessage splits on rune boundaries. All new/changed tests verified red-then-green; task check clean; adversarial review pass found no blocking issues.","external_ref":"https://github.com/samcharles93/archie-core/issues/484","labels":["code-review","streaming","telegram"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-tb3a","title":"Fix streaming review blockers for inline tool calls","description":"Resolve the four evidence-gated findings in merged inline tool-call streaming: preserve the authoritative Telegram reply when final edits fail; keep Telegram network I/O off the model FullStream consumer and cancellable; correlate tool inputs with results and render a bounded redacted parameter summary; snapshot show_tool_calls per live reply to avoid reload races. Add regression tests for every path and run task check plus lint/race validation.","acceptance_criteria":"Regression tests fail on the merged implementation and pass after the fix. Final edit failure falls back to normal split delivery. Delta and ToolCall callbacks do not wait on Telegram HTTP and stop cancels in-flight rendering. Completed tool events include bounded redacted parameters correlated by tool-call ID. Reload cannot race an in-flight reply's show_tool_calls setting. task check passes, golangci-lint reports no new findings, and focused race tests pass.","notes":"Implemented in worktree /tmp/archie-core-tb3a on branch fix/archie-core-tb3a. Added cancellable async Telegram rendering, final edit failure fallback through normal split delivery, call-ID-correlated bounded conservative parameter summaries, atomic per-reply show_tool_calls snapshots, SSE/UI parameter rendering, rebuilt ui/dist, and regression tests. Validation: GOFLAGS=-buildvcs=false task check passed; golangci-lint --new-from-rev=HEAD ./... reported 0 issues; focused race suite passed; fresh adversarial reviewer reported PASS with zero findings. Plain task check is blocked in linked worktrees by Go VCS stamping exit 128, hence buildvcs override.\n2026-08-24 reconciliation: the close reason's 'worktree left uncommitted' is stale. The work did land on main via ba33527 (Merge pull request #477 from samcharles93/fix/archie-core-tb3a); verified on main: gateway/stream.go sensitiveParameterKey+redactToolParameters, telegram/live.go per-reply showToolCalls snapshot, webui/api_chat.go gating. The /tmp/archie-core-tb3a worktree and its branch are gone, as expected.\n","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T18:05:35Z","created_by":"Sam Catlow","updated_at":"2026-08-24T07:29:09Z","started_at":"2026-08-13T18:05:39Z","closed_at":"2026-08-13T18:35:26Z","close_reason":"Completed and independently reviewed; worktree left uncommitted per conservative repository policy.","external_ref":"https://github.com/samcharles93/archie-core/issues/485","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-dzx","title":"Remove duplicate archie-agent safe.directory setup","description":"## Problem\\ncmd/archie-agent/main.go configures git safe.directory inline and then calls markWorktreeSafe, so startup writes the same global git configuration twice.\\n\\n## Scope\\nKeep markWorktreeSafe as the single tested production path and remove the older inline exec.Command block/import. Add regression coverage proving startup wiring has exactly one authoritative safe-directory call.\\n\\n## Acceptance\\n- archie-agent startup invokes markWorktreeSafe exactly once\\n- no second inline safe.directory command remains in main.go\\n- cmd/archie-agent tests and repository quality gate pass","acceptance_criteria":"Single tested safe.directory setup path remains; duplicate inline command is removed; tests and task check pass","notes":"Red proof: TestMainConfiguresWorktreeSafetyOnce failed with 2 setup paths before implementation. Green proof: go test/vet/build ./cmd/archie-agent/... passed; golangci-lint --new-from-rev=HEAD reported 0 issues. Fresh adversarial review found no blockers. Full task check was not run because the working tree contains unrelated in-progress changes and task check rewrites files; scoped package gate used per repository protocol.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:09Z","created_by":"Sam Catlow","updated_at":"2026-08-13T16:13:48Z","started_at":"2026-08-13T16:10:24Z","closed_at":"2026-08-13T16:13:48Z","close_reason":"Removed duplicate inline safe.directory setup; markWorktreeSafe is now the single tested production path","external_ref":"https://github.com/samcharles93/archie-core/issues/470","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-b6ew.6","title":"Inline editing for per-repo config fields (allow_concurrent, max_retries, review_enabled)","description":"archie-core-b6ew.4 shipped visibility for AllowConcurrent, MaxRetries, and ReviewEnabled on the repositories card (read-only), which was the concrete discoverability gap Sam hit. Actual inline editing was scoped out of that issue because it hits a real backend limitation discovered while implementing it: the dashboard's PATCH /api/config path (installUpdateConfigHandler in internal/app/archied/bootstrap.go) applies dotted-key updates via overlay.Nest + configuration.ApplyOverlayValues, and overlay.Nest (internal/infrastructure/configuration/overlay/overlay.go:162) only builds nested maps by splitting on '.' -- it has no array-index handling, so a key like 'repos.0.allow_concurrent' cannot be expressed, and Repos is a []config.Repo slice, not a map, so ApplyOverlayValues's YAML-merge-onto-struct approach cannot target one element either.\n\nThis needs either: (a) a dedicated repo-update seam (e.g. a webui handler keyed by owner/name that reads-modifies-writes the Repos slice directly, bypassing the generic dotted-overlay path), or (b) extending overlay.Nest/ApplyOverlayValues to support array indices generically, which is broader-reaching (touches every list-shaped config field, not just Repos) and needs its own design decision about whether index-based overlay keys are stable across a file edit that reorders [[repos]] entries. Option (a) is almost certainly the smaller, safer change -- decide in a short design note before implementing, per this repo's settled-design-first rule, since option (b) has real footguns (index stability) that deserve a deliberate answer, not a guess.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-09-02T12:22:53Z","created_by":"Sam Catlow","updated_at":"2026-09-02T12:22:53Z","dependencies":[{"issue_id":"archie-core-b6ew.6","depends_on_id":"archie-core-b6ew","type":"parent-child","created_at":"2026-09-02T12:22:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-b6ew.6","title":"Inline editing for per-repo config fields (allow_concurrent, max_retries, review_enabled)","description":"archie-core-b6ew.4 shipped visibility for AllowConcurrent, MaxRetries, and ReviewEnabled on the repositories card (read-only), which was the concrete discoverability gap Sam hit. Actual inline editing was scoped out of that issue because it hits a real backend limitation discovered while implementing it: the dashboard's PATCH /api/config path (installUpdateConfigHandler in internal/app/archied/bootstrap.go) applies dotted-key updates via overlay.Nest + configuration.ApplyOverlayValues, and overlay.Nest (internal/infrastructure/configuration/overlay/overlay.go:162) only builds nested maps by splitting on '.' -- it has no array-index handling, so a key like 'repos.0.allow_concurrent' cannot be expressed, and Repos is a []config.Repo slice, not a map, so ApplyOverlayValues's YAML-merge-onto-struct approach cannot target one element either.\n\nThis needs either: (a) a dedicated repo-update seam (e.g. a webui handler keyed by owner/name that reads-modifies-writes the Repos slice directly, bypassing the generic dotted-overlay path), or (b) extending overlay.Nest/ApplyOverlayValues to support array indices generically, which is broader-reaching (touches every list-shaped config field, not just Repos) and needs its own design decision about whether index-based overlay keys are stable across a file edit that reorders [[repos]] entries. Option (a) is almost certainly the smaller, safer change -- decide in a short design note before implementing, per this repo's settled-design-first rule, since option (b) has real footguns (index stability) that deserve a deliberate answer, not a guess.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-09-02T12:22:53Z","created_by":"Sam Catlow","updated_at":"2026-09-02T12:34:55Z","started_at":"2026-09-02T12:26:59Z","closed_at":"2026-09-02T12:34:55Z","close_reason":"Traced the mechanism before implementing: overlay.Nest/ApplyOverlayValues has no array-index support, but Repos is addressed as a WHOLE dotted key ('repos', no dot) whose value is the full slice -- so no changes to overlay/configuration packages were needed at all. Added PATCH /api/config/repos/{owner}/{name} (webui.Server.UpdateRepoField seam + handleConfigRepoUpdate), wired in archied/bootstrap.go's installUpdateRepoFieldHandler: reads the daemon's own live, untrimmed Repos (not webui.RepoView, which omits Preflight/TestGlob and would silently drop them on a naive round-trip), mutates the one matched repo's one field via the pure applyRepoFieldUpdate helper, and republishes through the existing UpdateConfig(ctx, {\"repos\": repos}) path unchanged -- zero duplicated validate/persist/publish logic.\n\nFrontend: config-row.js's row() gained an opts.save override so a caller can redirect where an edit persists; the repositories table renders an autosaving checkbox (allow_concurrent, review_enabled) and a save-on-blur/Enter text input (max_retries) via api.configRepoUpdate, reverting/erroring inline on failure rather than reloading the whole page mid-edit.\n\nGo tests cover the pure applyRepoFieldUpdate function directly (matched-repo-only mutation, untouched-field preservation including Preflight, type coercion, unknown repo/field rejection) and the webui handler (seam delegation, editable-field allowlist enforced before the seam is called, 503/400 mapping). JS tests cover the structural render (checkbox/input initial state) -- the save round trip itself isn't exercisable through the test shim (addEventListener is a no-op there), consistent with existing config-row.test.js coverage.","dependencies":[{"issue_id":"archie-core-b6ew.6","depends_on_id":"archie-core-b6ew","type":"parent-child","created_at":"2026-09-02T12:22:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-c0y4","title":"TelegramConfig gains a bws-capable Token (SecretRef), not just TokenEnv","description":"internal/config/config.go's TelegramConfig only has TokenEnv (a plain OS env var name); it never resolves through secret.Registry the way Forge.Token and Provider.APIKey do (secret.SecretRef{engine,key}), per ARCHITECTURE.md:220-224's own note that TelegramConfig.TokenEnv is one of the older env-only fields kept for backwards compatibility. internal/app/archied/telegram_setup.go:75 does a bare os.Getenv(cfg.Chat.Telegram.TokenEnv), bypassing the secret registry entirely.\n\nThis means a bws-stored Telegram token cannot be referenced directly in config.toml the way [providers.openai].api_key or [forge.token] already can -- the operator has to bridge it into a real process env var by hand (bws secret get ... | export ARCHIE_TELEGRAM_TOKEN=...) instead of writing [chat.telegram.token] = { engine = \"bws\", key = \"...\" }.\n\nFix: add a Token secret.SecretRef field to TelegramConfig, mirroring Forge.Token's shape and resolution path. Keep TokenEnv working as a fallback/legacy path (same pattern documented for Provider.APIKeyEnv vs APIKey) rather than a breaking config change -- resolve Token first if set, fall back to TokenEnv. Update config.example.toml and docs/architecture identity/config docs to show the SecretRef form as the preferred one.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-09-02T12:21:10Z","created_by":"Sam Catlow","updated_at":"2026-09-02T12:21:10Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-b6ew.4","title":"Structured configuration editors: repositories, maps","description":"Repositories currently render as a static read-only table missing AllowConcurrent, MaxRetries, and ReviewEnabled entirely (ReviewEnabled is absent from RepoView in api_config.go, not just unrendered). Add ReviewEnabled to RepoView, and build a dedicated backend-defined editor for the repositories section (and the models/providers maps) so these stop being silently read-only. This is the concrete fix for the allow_concurrent discoverability gap Sam hit, delivered as a typed editor rather than a one-off card patch, since the schema this epic introduces is what should own its shape.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-09-02T12:00:46Z","created_by":"Sam Catlow","updated_at":"2026-09-02T12:23:52Z","started_at":"2026-09-02T12:21:13Z","closed_at":"2026-09-02T12:23:52Z","close_reason":"Scoped to visibility, not full inline editing -- while implementing, found that the dashboard's PATCH /api/config path (overlay.Nest + configuration.ApplyOverlayValues) has no array-index support, so a per-element update to the Repos slice cannot be expressed as a dotted key today. That's real, separate scope, filed as archie-core-b6ew.6 rather than bolted on.\n\nShipped: RepoView.ReviewEnabled (previously absent from the API entirely, not just unrendered) alongside AllowConcurrent and MaxRetries; the repositories card now shows Concurrent/Max retries/Self-review columns as read-only pills, closing the concrete discoverability gap (Sam couldn't see allow_concurrent without an agent tracing Go source). config.example.toml documents review_enabled, which was undocumented before this. Go test pins ReviewEnabled reaching ConfigView for both a configured and a zero-value repo.","dependencies":[{"issue_id":"archie-core-b6ew.4","depends_on_id":"archie-core-b6ew","type":"parent-child","created_at":"2026-09-02T12:00:46Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-b6ew.4","depends_on_id":"archie-core-b6ew.2","type":"blocks","created_at":"2026-09-02T12:00:51Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-b6ew.5","title":"Schema contract tests: metadata completeness and secret-safety","description":"Assert every field the schema exposes carries type, label, and section; assert restart_required and editable are set deliberately (not zero-value defaults hiding an unreviewed field); assert secrets still never appear (extend the existing TestHandleConfigNeverLeaksSecrets pattern to the schema response); assert the frontend's generic renderer can render the full schema fixture without any field-specific branch (a JS test walking the schema and asserting no field key appears literally in settings.js).","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-09-02T12:00:46Z","created_by":"Sam Catlow","updated_at":"2026-09-02T12:26:27Z","started_at":"2026-09-02T12:24:40Z","closed_at":"2026-09-02T12:26:27Z","close_reason":"Most of this issue's assertions were already covered incrementally by tests added in .1-.4 (key/label/type completeness, structured/locked non-editability, secret-leak guard on the schema block, schema values matching their flat-field source). This issue adds the two pieces still missing: TestConfigFieldDescriptorsRestartRequiredIsDeliberate pins the exact RestartRequired value per key against the reload.go evidence documented in configFieldDescriptors' own comment, so a reclassification without checking reload.go fails loudly. ui/test/settings-schema.test.js renders settingsPage against a schema fixture containing a field settings.js has never heard of (proving the renderer needs no field-specific branch to show it correctly) and asserts, by reading settings.js's own source text, that none of the generically-rendered section's field keys appear literally in it -- the direct regression test for archie-core-b6ew.3's whole point.","dependencies":[{"issue_id":"archie-core-b6ew.5","depends_on_id":"archie-core-b6ew","type":"parent-child","created_at":"2026-09-02T12:00:46Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-b6ew.5","depends_on_id":"archie-core-b6ew.3","type":"blocks","created_at":"2026-09-02T12:00:52Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-b6ew.5","depends_on_id":"archie-core-b6ew.4","type":"blocks","created_at":"2026-09-02T12:00:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 84d354153..dc71dbd73 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -1281,6 +1281,31 @@ func (b *boot) installUpdateConfigHandler() { } } +// installUpdateRepoFieldHandler installs the dashboard's PATCH +// /api/config/repos/{owner}/{name} handler (archie-core-b6ew.6). A +// repository is one element of a []config.Repo, not a flat dotted key, so +// this cannot go through UpdateConfig's dotted-key path directly (overlay's +// Nest/ApplyOverlayValues have no notion of "element N of this slice"). +// Instead it reads the daemon's own live, untrimmed Repos (never +// webui.RepoView, which omits fields like Preflight/TestGlob and would +// silently drop them on a naive round-trip), changes the one field on the +// matching repo, and republishes the *entire* repository list through +// UpdateConfig -- reusing its validate-persist-publish path unchanged, so +// this handler owns only "which repo, which field," never how an update is +// applied. An edit here therefore overrides the whole repos list in the +// runtime overlay, same granularity every other overlay key already has; +// [[repos]] file edits stay visible for every field this handler never +// touches until an operator resets the "repos" override. +func (b *boot) installUpdateRepoFieldHandler() { + b.web.UpdateRepoField = func(ctx context.Context, owner, name, field string, value any) error { + repos, err := applyRepoFieldUpdate(b.d.Cfg.Get().Clone().Repos, owner, name, field, value) + if err != nil { + return err + } + return b.web.UpdateConfig(ctx, map[string]any{"repos": repos}) + } +} + // installConfigHandlers installs the dashboard's config override // listing and per-row reset handlers, both going through the same // publish path as reload. diff --git a/internal/app/archied/config_update.go b/internal/app/archied/config_update.go index 6d1c25cdd..f43a5e8ea 100644 --- a/internal/app/archied/config_update.go +++ b/internal/app/archied/config_update.go @@ -1,9 +1,13 @@ package archied import ( + "fmt" + "slices" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" + "github.com/samcharles93/archie-core/internal/webui" ) // applyDottedOverlay decodes dotted-path updates into cfg. yaml cannot @@ -22,3 +26,43 @@ func applyDottedOverlay(cfg *config.Config, updates map[string]any) error { } return configuration.ApplyOverlayValues(cfg, nested) } + +// applyRepoFieldUpdate returns a copy of repos with one editable field +// changed on the repository matched by owner/name (archie-core-b6ew.6). +// repos must already be a caller-owned copy (config.Config.Clone's +// Repos) -- this mutates the matched element in place and returns the +// same slice, matching applyDottedOverlay's "caller owns the copy" +// contract. Kept as a pure function, separate from +// installUpdateRepoFieldHandler's closure, so the field-matching and +// type-coercion logic is directly unit-testable without constructing a +// full boot. +func applyRepoFieldUpdate(repos []config.Repo, owner, name, field string, value any) ([]config.Repo, error) { + if !webui.RepoEditableFields[field] { + return nil, fmt.Errorf("%w: repo field %s is not editable from the dashboard", webui.ErrConfigUpdateInvalid, field) + } + index := slices.IndexFunc(repos, func(r config.Repo) bool { return r.Owner == owner && r.Name == name }) + if index < 0 { + return nil, fmt.Errorf("%w: repository %s/%s is not configured", webui.ErrConfigUpdateInvalid, owner, name) + } + switch field { + case "allow_concurrent": + v, ok := value.(bool) + if !ok { + return nil, fmt.Errorf("%w: allow_concurrent must be a boolean", webui.ErrConfigUpdateInvalid) + } + repos[index].AllowConcurrent = v + case "review_enabled": + v, ok := value.(bool) + if !ok { + return nil, fmt.Errorf("%w: review_enabled must be a boolean", webui.ErrConfigUpdateInvalid) + } + repos[index].ReviewEnabled = v + case "max_retries": + v, ok := value.(float64) + if !ok { + return nil, fmt.Errorf("%w: max_retries must be a number", webui.ErrConfigUpdateInvalid) + } + repos[index].MaxRetries = int(v) + } + return repos, nil +} diff --git a/internal/app/archied/config_update_test.go b/internal/app/archied/config_update_test.go index 32ed91b84..99ee9594c 100644 --- a/internal/app/archied/config_update_test.go +++ b/internal/app/archied/config_update_test.go @@ -28,3 +28,83 @@ func TestApplyDottedOverlayRejectsEmptyKey(t *testing.T) { t.Fatal("empty dotted key accepted") } } + +func twoRepoFixture() []config.Repo { + return []config.Repo{ + {Owner: "acme", Name: "widget", Base: "main", Preflight: [][]string{{"go", "version"}}}, + {Owner: "acme", Name: "gadget", Base: "main"}, + } +} + +// TestApplyRepoFieldUpdateChangesOnlyTheMatchedRepo proves the update +// targets exactly one element by owner/name and leaves every other repo, +// and every other field on the matched repo, untouched -- including +// Preflight, which webui.RepoView never carries on the wire (the whole +// point of reading b.d.Cfg's live Repos instead of the trimmed view). +func TestApplyRepoFieldUpdateChangesOnlyTheMatchedRepo(t *testing.T) { + repos, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "allow_concurrent", true) + if err != nil { + t.Fatalf("applyRepoFieldUpdate: %v", err) + } + if !repos[0].AllowConcurrent { + t.Error("widget.AllowConcurrent = false, want true") + } + if len(repos[0].Preflight) != 1 || repos[0].Preflight[0][0] != "go" { + t.Errorf("widget.Preflight = %v, want it untouched", repos[0].Preflight) + } + if repos[1].AllowConcurrent { + t.Error("gadget.AllowConcurrent changed, want the non-matched repo left alone") + } +} + +func TestApplyRepoFieldUpdateSetsEachEditableField(t *testing.T) { + repos, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "max_retries", float64(7)) + if err != nil { + t.Fatalf("applyRepoFieldUpdate: %v", err) + } + if repos[0].MaxRetries != 7 { + t.Errorf("MaxRetries = %d, want 7 (JSON numbers decode as float64)", repos[0].MaxRetries) + } + + repos, err = applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "review_enabled", true) + if err != nil { + t.Fatalf("applyRepoFieldUpdate: %v", err) + } + if !repos[0].ReviewEnabled { + t.Error("ReviewEnabled = false, want true") + } +} + +func TestApplyRepoFieldUpdateRejectsUnknownRepo(t *testing.T) { + _, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "does-not-exist", "allow_concurrent", true) + if err == nil { + t.Fatal("expected an error for a repo that is not configured") + } +} + +func TestApplyRepoFieldUpdateRejectsUneditableField(t *testing.T) { + _, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", "gate", []any{}) + if err == nil { + t.Fatal("expected an error for a field outside RepoEditableFields") + } +} + +// TestApplyRepoFieldUpdateRejectsWrongValueType proves a bool field given a +// number (or vice versa) fails with a clear error instead of a silent +// zero-value write -- the JSON body is caller-controlled (the dashboard), +// not type-checked before it reaches this function. +func TestApplyRepoFieldUpdateRejectsWrongValueType(t *testing.T) { + cases := []struct { + field string + value any + }{ + {"allow_concurrent", "yes"}, + {"review_enabled", 1.0}, + {"max_retries", true}, + } + for _, tc := range cases { + if _, err := applyRepoFieldUpdate(twoRepoFixture(), "acme", "widget", tc.field, tc.value); err == nil { + t.Errorf("field %q accepted wrong-typed value %#v", tc.field, tc.value) + } + } +} diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index fe6d63c4a..2d009e254 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -382,6 +382,7 @@ func Run() int { b.buildDaemon() b.wireConfigPublishing(ctx, *cfgPath, *overlayPath) b.installUpdateConfigHandler() + b.installUpdateRepoFieldHandler() b.installConfigHandlers(*cfgPath, *overlayPath) if err := b.startServices(ctx); err != nil { diff --git a/internal/webui/api_config_repos.go b/internal/webui/api_config_repos.go new file mode 100644 index 000000000..4128d2d98 --- /dev/null +++ b/internal/webui/api_config_repos.go @@ -0,0 +1,62 @@ +package webui + +import ( + "encoding/json" + "errors" + "net/http" +) + +// RepoEditableFields are the per-repository fields the dashboard may change +// through handleConfigRepoUpdate. Deliberately narrow: these three are +// booleans/small ints with no cross-field validation, unlike Gate or +// Protect, which stay file-edited (archie-core-b6ew.4/.6). +var RepoEditableFields = map[string]bool{ + "allow_concurrent": true, + "max_retries": true, + "review_enabled": true, +} + +// handleConfigRepoUpdate applies one field change to one repository, +// identified by owner/name in the path. It exists because the repository +// list is a []config.Repo, not a flat dotted key -- PATCH /api/config's +// generic path (overlay.Nest + configuration.ApplyOverlayValues) has no way +// to address "element N of this slice." UpdateRepoField's implementation +// (wired by the composition root) reads the daemon's own live config.Repo +// values (never the trimmed, wire-safe RepoView), changes just the one +// field, and republishes the full repository list through the same +// validate-persist-publish path PATCH /api/config already uses -- see +// bootstrap.go's installUpdateConfigHandler for why that matters: the wire +// view omits fields (Preflight, TestGlob) that a naive round-trip through +// ConfigView would silently drop. +func (s *Server) handleConfigRepoUpdate(w http.ResponseWriter, r *http.Request) { + if s.UpdateRepoField == nil { + http.Error(w, ErrConfigUpdateUnavailable.Error(), http.StatusServiceUnavailable) + return + } + owner := r.PathValue("owner") + name := r.PathValue("name") + var body struct { + Field string `json:"field"` + Value any `json:"value"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest) + return + } + if !RepoEditableFields[body.Field] { + http.Error(w, "field "+body.Field+" is not editable from the dashboard", http.StatusBadRequest) + return + } + if err := s.UpdateRepoField(r.Context(), owner, name, body.Field, body.Value); err != nil { + switch { + case errors.Is(err, ErrConfigUpdateUnavailable): + http.Error(w, err.Error(), http.StatusServiceUnavailable) + case errors.Is(err, ErrConfigUpdateInvalid): + http.Error(w, err.Error(), http.StatusBadRequest) + default: + http.Error(w, "repo update failed: "+err.Error(), http.StatusInternalServerError) + } + return + } + writeJSON(w, map[string]any{"ok": true}) +} diff --git a/internal/webui/api_config_repos_test.go b/internal/webui/api_config_repos_test.go new file mode 100644 index 000000000..66f50f065 --- /dev/null +++ b/internal/webui/api_config_repos_test.go @@ -0,0 +1,88 @@ +package webui + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestHandleConfigRepoUpdateAppliesViaSeam(t *testing.T) { + srv := newTestServer(t) + type call struct { + owner, name, field string + value any + } + var got call + srv.UpdateRepoField = func(_ context.Context, owner, name, field string, value any) error { + got = call{owner, name, field, value} + return nil + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config/repos/acme/widget", + strings.NewReader(`{"field": "allow_concurrent", "value": true}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body) + } + if got != (call{"acme", "widget", "allow_concurrent", true}) { + t.Errorf("seam called with %+v", got) + } +} + +// TestHandleConfigRepoUpdateRejectsUneditableFields proves the handler +// itself refuses a field outside RepoEditableFields before ever calling the +// seam -- Gate, Protect, and every other repo field stay file-edited. +func TestHandleConfigRepoUpdateRejectsUneditableFields(t *testing.T) { + srv := newTestServer(t) + called := false + srv.UpdateRepoField = func(context.Context, string, string, string, any) error { + called = true + return nil + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config/repos/acme/widget", + strings.NewReader(`{"field": "gate", "value": [["rm", "-rf", "/"]]}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", w.Code) + } + if called { + t.Error("UpdateRepoField was called for a field outside RepoEditableFields") + } +} + +func TestHandleConfigRepoUpdateUnavailableMapsTo503(t *testing.T) { + srv := newTestServer(t) + srv.UpdateRepoField = nil + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config/repos/acme/widget", + strings.NewReader(`{"field": "allow_concurrent", "value": true}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503", w.Code) + } +} + +func TestHandleConfigRepoUpdateSeamErrorMapsTo400(t *testing.T) { + srv := newTestServer(t) + srv.UpdateRepoField = func(context.Context, string, string, string, any) error { + return ErrConfigUpdateInvalid + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config/repos/acme/widget", + strings.NewReader(`{"field": "max_retries", "value": 5}`)) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", w.Code) + } +} diff --git a/internal/webui/server.go b/internal/webui/server.go index 40daea692..59d01cbd9 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -92,6 +92,14 @@ type Server struct { // directly. ResetConfig func(context.Context, string) error + // UpdateRepoField changes one editable field (RepoEditableFields) on + // the repository identified by owner/name, republishing the full + // repository list through the same path as UpdateConfig. Optional: + // when nil, PATCH /api/config/repos/{owner}/{name} answers 503. See + // handleConfigRepoUpdate for why this needs its own seam rather than + // going through UpdateConfig's dotted-key path directly. + UpdateRepoField func(ctx context.Context, owner, name, field string, value any) error + // Channels reports actual adapter lifecycle, independently of configuration // presence. Nil preserves the configuration-only fallback for tests and // minimal embedding. @@ -276,6 +284,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/version", s.handleVersion) mux.HandleFunc("PATCH /api/config", s.handleConfigUpdate) mux.HandleFunc("POST /api/config/reset", s.handleConfigReset) + mux.HandleFunc("PATCH /api/config/repos/{owner}/{name}", s.handleConfigRepoUpdate) mux.HandleFunc("GET /api/logs", s.handleLogs) mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs) mux.HandleFunc("GET /api/logs/stream", s.handleLogStream) diff --git a/ui/src/base/api.js b/ui/src/base/api.js index 19a1b99cd..81f7b8340 100644 --- a/ui/src/base/api.js +++ b/ui/src/base/api.js @@ -100,6 +100,16 @@ export const api = { if (!res.ok) throw new ApiError(await errorMessage(res), res.status); return res.json(); }, + configRepoUpdate: async (owner, name, field, value) => { + const res = await fetch(`/api/config/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { + method: "PATCH", + headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" }, + body: JSON.stringify({ field, value }), + signal: AbortSignal.timeout(15000), + }); + if (!res.ok) throw new ApiError(await errorMessage(res), res.status); + return res.json(); + }, configReset: async (key) => { const res = await fetch("/api/config/reset", { method: "POST", diff --git a/ui/src/settings/config-row.js b/ui/src/settings/config-row.js index 72496c391..79a9e0653 100644 --- a/ui/src/settings/config-row.js +++ b/ui/src/settings/config-row.js @@ -111,6 +111,13 @@ function note(rowEl, message) { function startEdit(rowEl, label, opts, restore) { const { key, type, raw, options, onSaved } = opts; + // save lets a caller redirect where an edit is persisted -- the + // repositories table's per-repo fields PATCH /api/config/repos/{owner}/ + // {name} instead of the generic dotted-key /api/config path, since a + // repository is one element of a slice, not a flat key (see + // api.configRepoUpdate, archie-core-b6ew.6). Defaults to the ordinary + // dotted-key update every other row already used. + const save = opts.save || ((value) => api.configUpdate({ [key]: value })); const input = type === "bool" ? el( "select.kv-input", @@ -123,11 +130,11 @@ function startEdit(rowEl, label, opts, restore) { ...(options || []).map((o) => el("option", { value: o, selected: raw === o }, o)), ) : el("input.kv-input", { type: "text", value: String(raw ?? "") }); - const save = el("button.kv-save", { type: "button" }, "Save"); + const saveBtn = el("button.kv-save", { type: "button" }, "Save"); const cancel = el("button.kv-cancel", { type: "button" }, "Cancel"); const error = el("span.kv-note.is-error"); - mount(rowEl, el("span.kv-label", label), input, el("div.kv-actions", save, cancel), error); + mount(rowEl, el("span.kv-label", label), input, el("div.kv-actions", saveBtn, cancel), error); input.focus?.(); input.select?.(); @@ -136,26 +143,26 @@ function startEdit(rowEl, label, opts, restore) { input.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault?.(); - save.click(); + saveBtn.click(); } if (e.key === "Escape") done(); }); - save.addEventListener("click", async () => { + saveBtn.addEventListener("click", async () => { const parsed = parseEdit(type, input.value); if (parsed.error) { error.textContent = parsed.error; return; } - save.disabled = true; + saveBtn.disabled = true; try { - await api.configUpdate({ [key]: parsed.value }); + await save(parsed.value); onSaved?.(); } catch (err) { // The server's reason (validation failure, denylisted key) is the // part the operator can act on; show it instead of the status. error.textContent = String(err.message || err); - save.disabled = false; + saveBtn.disabled = false; } }); } diff --git a/ui/src/settings/settings.js b/ui/src/settings/settings.js index 69855de35..836e878a6 100644 --- a/ui/src/settings/settings.js +++ b/ui/src/settings/settings.js @@ -120,7 +120,7 @@ export function settingsPage() { body, ...banners, ...schemaCards(cfg.schema || []), - repositoriesCard(cfg.repositories), + repositoriesCard(cfg.repositories, reload), modelsAndProvidersCard(cfg.models, cfg.providers), provenanceCard(cfg.provenance), ); @@ -223,7 +223,7 @@ function roleButtonClass(kind) { return kind === "quiet" ? "btn-quiet" : kind === "danger" ? "btn-danger" : ""; } -function repositoriesCard(repos) { +function repositoriesCard(repos, onSaved) { if (!repos?.length) { return section( "Repositories", @@ -234,8 +234,8 @@ function repositoriesCard(repos) { return section( "Repositories", "Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. " + - "Concurrent tasks, retries, and self-review are set per repository in config.toml -- read-only here " + - "until archie-core-b6ew.4's follow-up gives them an inline editor.", + "Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, " + + "not the file config.toml directly.", el( "div.table-scroll", el( @@ -259,9 +259,9 @@ function repositoriesCard(repos) { el("td", r.ecosystem || "go"), el("td.mono", gateSummary(r.gate)), el("td.mono", r.protect?.length ? r.protect.join(", ") : "—"), - el("td", boolPill(r.allow_concurrent)), - el("td.mono", String(r.max_retries ?? 0)), - el("td", boolPill(r.review_enabled)), + repoBoolCell(r, "allow_concurrent", onSaved), + repoIntCell(r, "max_retries", onSaved), + repoBoolCell(r, "review_enabled", onSaved), ), ), ), @@ -270,11 +270,58 @@ function repositoriesCard(repos) { ); } -// boolPill renders a config flag as the same pill used elsewhere on this -// page (e.g. provider credential status), so "on"/"off" reads consistently -// with the rest of the dashboard rather than as raw true/false text. -function boolPill(value) { - return value ? pill("on", "ok") : pill("off", "idle"); +// repoBoolCell renders an immediately-autosaving checkbox, PATCHing +// api.configRepoUpdate on change and reverting the toggle if the save +// fails (archie-core-b6ew.6). A table cell doesn't fit config-row.js's +// label/value/actions Edit-then-Save flow, and a checkbox is the more +// natural control for a boolean in a table anyway. +function repoBoolCell(r, field, onSaved) { + const cb = el("input.repo-field-checkbox", { type: "checkbox", checked: !!r[field] }); + const note = el("span.kv-note.is-error"); + cb.addEventListener("change", async () => { + const next = cb.checked; + cb.disabled = true; + try { + await api.configRepoUpdate(r.owner, r.name, field, next); + onSaved?.(); + } catch (err) { + cb.checked = !next; + note.textContent = String(err.message || err); + cb.disabled = false; + } + }); + return el("td", cb, note); +} + +// repoIntCell renders a plain text input that saves on blur/Enter. Errors +// (a non-numeric entry, a rejected save) stay on the cell rather than +// reloading the page out from under the operator mid-edit. +function repoIntCell(r, field, onSaved) { + const input = el("input.kv-input", { type: "text", value: String(r[field] ?? 0) }); + const note = el("span.kv-note.is-error"); + const commit = async () => { + const n = parseInt(input.value, 10); + if (Number.isNaN(n)) { + note.textContent = "Enter a whole number"; + return; + } + input.disabled = true; + try { + await api.configRepoUpdate(r.owner, r.name, field, n); + onSaved?.(); + } catch (err) { + note.textContent = String(err.message || err); + input.disabled = false; + } + }; + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") { + e.preventDefault?.(); + input.blur(); + } + }); + input.addEventListener("blur", commit); + return el("td", input, note); } function gateSummary(gate) { diff --git a/ui/test/settings-schema.test.js b/ui/test/settings-schema.test.js index 7676333cc..60081fdfe 100644 --- a/ui/test/settings-schema.test.js +++ b/ui/test/settings-schema.test.js @@ -107,6 +107,40 @@ test("a structured field in a schema section renders no card of its own here", a // storage, web). A literal key string in the source is exactly the // regression archie-core-b6ew.3 removed -- a hardcoded row(...) call // re-appearing for one field while the rest stay generic. +// archie-core-b6ew.6: repositories gained inline editors for +// allow_concurrent/max_retries/review_enabled. The shim's addEventListener +// is a no-op (see ui/test/shim.js), so the save round trip itself is not +// exercisable here -- this pins the structural half: the right initial +// control with the right initial value renders per repo, matching the +// existing config-row.test.js convention of testing structure, not the +// live event round trip. +test("repositories render a checkbox and a text input reflecting each repo's current field values", async () => { + const root = await renderSettings({ + repositories: [ + { owner: "acme", name: "widget", base: "main", allow_concurrent: true, max_retries: 3, review_enabled: false }, + ], + }); + + const checkboxes = []; + const textInputs = []; + const walk = (node) => { + for (const c of node.childNodes || []) { + if (c.tagName === "INPUT" && c.attrs.type === "checkbox") checkboxes.push(c); + if (c.tagName === "INPUT" && c.attrs.type === "text") textInputs.push(c); + walk(c); + } + }; + walk(root); + + assert.equal(checkboxes.length, 2, "allow_concurrent and review_enabled should each render a checkbox"); + assert.equal(checkboxes[0].attrs.checked, "", "allow_concurrent=true should render checked"); + assert.equal(checkboxes[1].attrs.checked, undefined, "review_enabled=false should render unchecked"); + assert.ok( + textInputs.some((i) => i.attrs.value === "3"), + "max_retries' current value should populate a text input", + ); +}); + test("settings.js contains no literal field-specific branch for the generically-rendered sections", () => { const genericFieldKeys = [ "bot_user", "bot_email", "\"label\"", "forge.type", "forge.host", "diff_cap_lines",