feat(messaging): Messaging Service operator surface, chat report rendering, and the diff-cap config fix (#899)

* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.

* fix(gateway): render chat reports as lines, not one run-on paragraph

/status and /tasks are line-oriented reports, but their newlines were plain
"\n" -- CommonMark's soft wrap. The Telegram rich-block renderer space-joins
soft-wrapped lines, by design: a Telegram paragraph renders an embedded
newline as nothing at all, so a space is the only separator that survives.
The reports therefore arrived as one line each: "Runtime Provider: DeepSeek
Model: deepseek/deepseek-flash", and every task's title, state and park
reason jammed together.

The renderer now implements CommonMark's hard line break (two trailing
spaces, or a trailing backslash): the line closes its own block and the next
one hugs it, so a stanza keeps its lines without the spacer paragraph that
separates unrelated blocks. Ordinary prose is untouched -- a model's wrapped
paragraph still joins with a space. The producers mark their report lines
with it.

Two report fixes alongside:

- A park reason is capped to its first line at 160 runes. It carries whatever
  the failing stage reported, which for a lint gate is the whole tool log;
  unbounded, one parked task pushed every other task out of the reply. The
  full reason is still on the task.
- /status loses its "Runtime" sub-header. A section header over two fields
  made a four-fact report read like a document.

* fix(config): let diff_cap_lines = 0 actually switch the cap off

Config.DiffCapLines was a plain int, so the defaults pass could not tell an
absent key from an explicit 0 and rewrote both to 400. The dashboard schema
said "0 means unlimited" and StageDiffCap treated <= 0 as unlimited, but 0
never reached the step: the documented way to switch the cap off was
unreachable through config.

Same root cause, worse instance: configForIdentity assigned
root.DiffCapLines = identity.DiffCapLines unconditionally, so an identity
that simply omitted the key overwrote the shared cap with the zero value and
silently disabled the safety rail for that identity.

DiffCapLines is now *int on both Config and IdentityConfig -- nil is absent,
0 is no cap -- read through Config.DiffCap(). Defaults fill only nil, and an
identity overrides only when it set the key. TaskConfig keeps a resolved int,
so the daemon/agent wire format is unchanged and a version-skewed agent
cannot misread a null.

The park reason changes too. It told the operator to "approve manually", but
a parked task's actions are retry, abandon and reject (internal/taskstate):
there is no approve path out of diff-cap, so it sent them looking for a
button that does not exist. It now names the two things that work.

* feat(config): make the daemon's readiness dependency timeout configurable

The daemon's gateway probe bounded its call with a hardcoded 5s constant,
while every other NewContractProbe call site (archie-ui, archie-messaging)
passes the service's configured DependencyTimeout. It was the only magic
number among them.

[health].dependency_timeout carries it, defaulting to the same 5s the
extracted services' -dependency-timeout flag defaults to, so every process
bounds a probe into a dependency the same way out of the box.

It is not added to the dashboard config schema or the reloadable set:
[health] appears in neither today, health.listen included, and a probe
assembled at boot would not observe a reload anyway.
This commit is contained in:
sam authored and GitHub committed 2026-09-20 00:32:13 +10:00
1 parent 800352a692
commit c35d9b6fdd
15 files changed
+218 -29

No files matched your search

+6
View File
@@ -26,6 +26,7 @@
poll_interval = "60s"
label = "archie"
bot_user = "vectis-labs-archie"
# 0 switches the cap off; omit the key to take the built-in default (400).
diff_cap_lines = 400
# how many operator-triggered retries a parked task gets
@@ -222,6 +223,11 @@ class = "ollama"
# in the extracted UI topology.
[health]
listen = "127.0.0.1:8485"
# Bounds one readiness probe's call into a service the daemon depends on but
# does not own (the Gateway), so a hung dependency degrades that probe instead
# of stalling the whole report. Omit for the default; a negative value leaves
# only the caller's own deadline in force.
# dependency_timeout = "5s"
# Web dashboard and API: task board, activity stream, chat, config,
# memory, SSE events. Served as an embedded SPA with a full REST
+1 -5
View File
@@ -41,17 +41,13 @@ func (b *boot) setupReadinessProbes() {
// this process depends on is the Gateway answering, so that is what it
// reports (docs/prds/ui-service-boundary.md, "Listen, authentication,
// and readiness").
readiness.NewContractProbe("gateway", gatewayProbeTimeout, func(ctx context.Context) error {
readiness.NewContractProbe("gateway", time.Duration(cfg.Health.DependencyTimeout), func(ctx context.Context) error {
return pingChat(ctx, b.chat)
}),
}
b.healthRegistry = health.NewRegistry(probes...)
}
// gatewayProbeTimeout bounds the Gateway readiness call so a hung Gateway
// degrades this probe rather than stalling the whole health report.
const gatewayProbeTimeout = 5 * time.Second
// pingChat asks the Gateway for a snapshot. An unwired chat surface is
// reported as degraded rather than silently OK: a daemon with no Gateway
// serves no chat at all.
+1 -1
View File
@@ -201,7 +201,7 @@ func TestChangedNonReloadableFields(t *testing.T) {
reloadableOnly.Repos = []config.Repo{{Owner: "x", Name: "z"}}
reloadableOnly.Budgets = config.Budgets{MaxSteps: 99}
reloadableOnly.Dispatch = config.Dispatch{Trigger: "label"}
reloadableOnly.DiffCapLines = 1234
reloadableOnly.DiffCapLines = new(1234)
reloadableOnly.Models = map[string]string{"builder": "provider/model"}
reloadableOnly.Notify = config.Notify{Webhook: "https://notify.example/hook"}
reloadableOnly.Label = "archie"
+39 -6
View File
@@ -485,8 +485,14 @@ type Config struct {
BotUser string `toml:"bot_user" yaml:"bot_user"`
// BotEmail is the git author email; defaults to the GitHub noreply
// address for BotUser.
BotEmail string `toml:"bot_email" yaml:"bot_email"`
DiffCapLines int `toml:"diff_cap_lines" yaml:"diff_cap_lines"`
BotEmail string `toml:"bot_email" yaml:"bot_email"`
// DiffCapLines parks a task whose diff exceeds this many changed lines.
// It is a pointer so an explicit 0 ("no cap") is distinguishable from an
// absent key, which takes the default: with a plain int the documented
// way to switch the cap off was indistinguishable from not configuring
// it, and the defaults pass silently rewrote it. Read it through
// [Config.DiffCap].
DiffCapLines *int `toml:"diff_cap_lines" yaml:"diff_cap_lines"`
Forge Forge `toml:"forge" yaml:"forge"`
Dispatch Dispatch `toml:"dispatch" yaml:"dispatch"`
@@ -550,8 +556,10 @@ type IdentityConfig struct {
BotUser string `toml:"bot_user" yaml:"bot_user"`
// BotEmail is the git author email. Falls back to a forge-appropriate
// default from BotUser when empty.
BotEmail string `toml:"bot_email" yaml:"bot_email"`
DiffCapLines int `toml:"diff_cap_lines" yaml:"diff_cap_lines"`
BotEmail string `toml:"bot_email" yaml:"bot_email"`
// DiffCapLines overrides the shared cap for this identity. Nil (absent)
// inherits it; an explicit 0 switches the cap off for this identity only.
DiffCapLines *int `toml:"diff_cap_lines" yaml:"diff_cap_lines"`
// PollInterval overrides the shared PollInterval. When 0, the shared
// interval is used.
PollInterval Duration `toml:"poll_interval" yaml:"poll_interval"`
@@ -586,6 +594,25 @@ type TaskConfig struct {
ToolPolicy ToolPolicy `json:"tool_policy"`
}
// DiffCapOf returns a DiffCapLines value for n. It exists because the field is
// a pointer to keep "absent" distinct from an explicit 0, and a literal config
// cannot take the address of a constant.
//
//go:fix inline
func DiffCapOf(n int) *int { return new(n) }
// DiffCap returns the effective changed-line cap: 0 means no cap, which is
// also what an unconfigured value means once a Config has been built by hand
// rather than loaded (tests, archie-agent's reconstructed Config). The loader's
// defaults pass fills the absent case, so a loaded Config never reports 0
// unless the operator asked for it.
func (c Config) DiffCap() int {
if c.DiffCapLines == nil {
return 0
}
return *c.DiffCapLines
}
// TaskForge is the non-secret forge configuration needed by workflow stages.
type TaskForge struct {
Host string `json:"host"`
@@ -601,7 +628,7 @@ func (c Config) ForTask() TaskConfig {
ModelLimits: maps.Clone(c.ModelLimits),
Budgets: c.Budgets,
Dispatch: Dispatch{Trigger: c.Dispatch.Trigger, AckReaction: c.Dispatch.AckReaction, Labels: cloneStringMap(c.Dispatch.Labels)},
DiffCapLines: c.DiffCapLines,
DiffCapLines: c.DiffCap(),
Notify: c.Notify,
Forge: TaskForge{Host: c.Forge.Host},
ToolPolicy: c.Tools.Policy,
@@ -620,7 +647,7 @@ func (tc TaskConfig) ToConfig() Config {
ModelLimits: maps.Clone(tc.ModelLimits),
Budgets: tc.Budgets,
Dispatch: Dispatch{Trigger: tc.Dispatch.Trigger, AckReaction: tc.Dispatch.AckReaction, Labels: cloneStringMap(tc.Dispatch.Labels)},
DiffCapLines: tc.DiffCapLines,
DiffCapLines: &tc.DiffCapLines,
Notify: tc.Notify,
Forge: Forge{Host: tc.Forge.Host},
Tools: ToolsConfig{Policy: tc.ToolPolicy},
@@ -1015,6 +1042,12 @@ type Health struct {
// Listen is the address the daemon serves /healthz, /health and
// /health/detailed on. Defaulted, never empty in a loaded config.
Listen string `toml:"listen" yaml:"listen"`
// DependencyTimeout bounds one readiness probe's call into a service this
// process depends on but does not own, so a hung dependency degrades that
// probe instead of stalling the whole health report. It is the daemon's
// equivalent of the extracted services' -dependency-timeout flag.
// Defaulted, never zero in a loaded config.
DependencyTimeout Duration `toml:"dependency_timeout" yaml:"dependency_timeout"`
}
// URL renders Listen as an address a local caller can dial, which is what
+7 -5
View File
@@ -14,7 +14,7 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) {
cfg := Config{
BotUser: "archie-bot",
BotEmail: "archie-bot@users.noreply.github.com",
DiffCapLines: 321,
DiffCapLines: new(321),
Models: map[string]string{"builder": "anthropic/claude"},
Budgets: Budgets{MaxSteps: 12, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3},
Dispatch: Dispatch{Trigger: "label", AckReaction: "eyes", Labels: map[string]string{"working": "bot:working"}},
@@ -36,8 +36,10 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) {
if !reflect.DeepEqual(got.Dispatch, cfg.Dispatch) {
t.Fatalf("Dispatch = %#v, want %#v", got.Dispatch, cfg.Dispatch)
}
if got.DiffCapLines != cfg.DiffCapLines {
t.Fatalf("DiffCapLines = %d, want %d", got.DiffCapLines, cfg.DiffCapLines)
// Compared by effective value, not pointer: the round trip through
// TaskConfig carries the resolved cap and rebuilds a fresh pointer.
if got.DiffCap() != cfg.DiffCap() {
t.Fatalf("DiffCap() = %d, want %d", got.DiffCap(), cfg.DiffCap())
}
if got.Notify != cfg.Notify {
t.Fatalf("Notify = %#v, want %#v", got.Notify, cfg.Notify)
@@ -89,7 +91,7 @@ models = ["openai/gpt-5.6-sol", "openrouter/openai/gpt-5.6-sol"]
func TestConfigForTaskJSONRoundTrip(t *testing.T) {
cfg := Config{
DiffCapLines: 321,
DiffCapLines: new(321),
Models: map[string]string{
"builder": "anthropic/claude",
"planner": "openai/gpt",
@@ -124,7 +126,7 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) {
Models: cfg.Models,
Budgets: cfg.Budgets,
Dispatch: cfg.Dispatch,
DiffCapLines: cfg.DiffCapLines,
DiffCapLines: cfg.DiffCap(),
Notify: cfg.Notify,
Forge: TaskForge{Host: cfg.Forge.Host},
ToolPolicy: cfg.Tools.Policy,
+6 -1
View File
@@ -1611,7 +1611,12 @@ func (d *Daemon) captureAttemptConfig(ctx context.Context, task *workflow.Task,
func configForIdentity(root config.Config, identity config.IdentityConfig) config.Config {
root.BotUser = identity.BotUser
root.BotEmail = identity.BotEmail
root.DiffCapLines = identity.DiffCapLines
// Only an identity that set the cap overrides the shared one. Assigning
// unconditionally made an identity that omits the key inherit a nil cap,
// which reads as "no cap" and silently disabled the safety rail.
if identity.DiffCapLines != nil {
root.DiffCapLines = identity.DiffCapLines
}
root.Forge = identity.Forge
root.Dispatch = identity.Dispatch
root.Models = identity.Models
+27 -2
View File
@@ -759,7 +759,7 @@ func TestRunViaAgentParksOnRunError(t *testing.T) {
func TestRunViaAgentSendsExpectedRequest(t *testing.T) {
d, s, busClient := daemonWithNATS(t)
prev := d.Cfg.Get()
prev.DiffCapLines = 999
prev.DiffCapLines = new(999)
d.Cfg.Set(prev)
ctx := context.Background()
@@ -1975,7 +1975,7 @@ func configWithCanarySecrets() config.Config {
},
},
Budgets: config.Budgets{MaxSteps: 40, GateMaxFailures: 2},
DiffCapLines: 800,
DiffCapLines: new(800),
Dispatch: config.Dispatch{
Trigger: "either", AckReaction: "eyes",
Labels: map[string]string{"queued": "archie:queued"},
@@ -2259,3 +2259,28 @@ func TestReconcilePRsAttributesTheOutcomeToTheTasksAttempt(t *testing.T) {
t.Fatal("reconcilePRs published no merge event")
}
}
// TestConfigForIdentityInheritsAnUnsetDiffCap is the regression case for an
// identity silently disabling the diff cap. configForIdentity copied every
// identity field over the root unconditionally, so an identity that simply did
// not mention diff_cap_lines overwrote the shared cap with the zero value --
// which StageDiffCap reads as "no cap". The safety rail vanished for exactly
// the deployments that never configured it per identity.
func TestConfigForIdentityInheritsAnUnsetDiffCap(t *testing.T) {
root := config.Config{DiffCapLines: new(400)}
inherited := configForIdentity(root, config.IdentityConfig{BotUser: "one"})
if inherited.DiffCap() != 400 {
t.Fatalf("DiffCap() = %d, want the shared 400 when the identity sets none", inherited.DiffCap())
}
overridden := configForIdentity(root, config.IdentityConfig{BotUser: "two", DiffCapLines: new(50)})
if overridden.DiffCap() != 50 {
t.Fatalf("DiffCap() = %d, want the identity's 50", overridden.DiffCap())
}
off := configForIdentity(root, config.IdentityConfig{BotUser: "three", DiffCapLines: new(0)})
if off.DiffCap() != 0 {
t.Fatalf("DiffCap() = %d, want 0: an identity may switch its own cap off explicitly", off.DiffCap())
}
}
+5 -1
View File
@@ -457,6 +457,8 @@ type fakeTrees struct {
pushErr error
dir string
// changedLines is what ChangedLines reports, for StageDiffCap.
changedLines int
resumed bool
resumeDir string
@@ -485,7 +487,9 @@ func (f *fakeTrees) Diff(context.Context, string, string) (string, error) { retu
func (f *fakeTrees) ChangedFiles(context.Context, string, string) ([]string, error) { return nil, nil }
func (f *fakeTrees) ChangedLines(context.Context, string, string) (int, error) { return 0, nil }
func (f *fakeTrees) ChangedLines(context.Context, string, string) (int, error) {
return f.changedLines, nil
}
func (f *fakeTrees) Snapshot(context.Context, string, string) error { return nil }
+7 -3
View File
@@ -188,17 +188,21 @@ func closeNoChangesIssue(ctx context.Context, tc *TaskContext) error {
// oversized changes need human pre-approval, not an auto-opened PR.
func StageDiffCap() Stage {
return Stage{Name: "diff-cap", Run: func(ctx context.Context, tc *TaskContext) error {
if tc.Cfg.DiffCapLines <= 0 {
capLines := tc.Cfg.DiffCap()
if capLines <= 0 {
return nil
}
lines, err := tc.Trees.ChangedLines(ctx, tc.Dir, tc.Repo.BaseBranch())
if err != nil {
return err
}
if lines > tc.Cfg.DiffCapLines {
if lines > capLines {
// No "approve" here: a parked task's operator actions are retry,
// abandon and reject (internal/taskstate), so telling the operator
// to approve sent them looking for a button that does not exist.
tc.Outcome = Outcome{
Status: StatusParked,
Detail: fmt.Sprintf("diff is %d changed lines (cap %d) -- split the issue or approve manually", lines, tc.Cfg.DiffCapLines),
Detail: fmt.Sprintf("diff is %d changed lines (cap %d) -- split the issue, or raise diff_cap_lines and retry", lines, capLines),
}
}
return nil
+48
View File
@@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
@@ -224,3 +225,50 @@ func TestStageRepoStagesPropagatesLoaderError(t *testing.T) {
t.Fatal("StageRepoStages() = nil, want the loader's error propagated")
}
}
// TestStageDiffCapUnlimitedWhenCapIsZero pins that an explicit 0 switches the
// cap off. The dashboard schema documents 0 that way, and this is the step that
// has to honour it -- for a long time it could not, because the config loader
// rewrote an explicit 0 to the default before the step ever saw it.
func TestStageDiffCapUnlimitedWhenCapIsZero(t *testing.T) {
tc := &TaskContext{
Cfg: config.Config{DiffCapLines: new(0)},
Trees: &fakeTrees{changedLines: 10_000},
Repo: config.Repo{Owner: "acme", Name: "app"},
}
if err := StageDiffCap().Run(context.Background(), tc); err != nil {
t.Fatalf("StageDiffCap: %v", err)
}
if tc.Outcome.Status == StatusParked {
t.Fatalf("task parked with the cap switched off: %q", tc.Outcome.Detail)
}
}
// TestStageDiffCapParksWithAnActionableReason is the regression case for a park
// reason that told the operator to do something impossible. A parked task's
// actions are retry, abandon and reject (internal/taskstate), so "approve
// manually" sent them looking for a button that does not exist -- which is
// exactly what happened on task 11.
func TestStageDiffCapParksWithAnActionableReason(t *testing.T) {
tc := &TaskContext{
Cfg: config.Config{DiffCapLines: new(400)},
Trees: &fakeTrees{changedLines: 789},
Repo: config.Repo{Owner: "acme", Name: "app"},
}
if err := StageDiffCap().Run(context.Background(), tc); err != nil {
t.Fatalf("StageDiffCap: %v", err)
}
if tc.Outcome.Status != StatusParked {
t.Fatalf("Outcome.Status = %q, want parked at 789 lines over a 400 cap", tc.Outcome.Status)
}
if strings.Contains(tc.Outcome.Detail, "approve") {
t.Errorf("park reason offers approve, which is not an action a parked task has: %q", tc.Outcome.Detail)
}
for _, want := range []string{"789", "400", "diff_cap_lines"} {
if !strings.Contains(tc.Outcome.Detail, want) {
t.Errorf("park reason %q is missing %q", tc.Outcome.Detail, want)
}
}
}
@@ -50,6 +50,11 @@ const (
// defaultHealthListen is the daemon's own liveness address. The update
// watchdog's fallback in scripts/archie-update-watchdog must match it.
defaultHealthListen = "127.0.0.1:8485"
// defaultHealthDependencyTimeout matches the extracted services'
// -dependency-timeout default, so every process bounds a probe into a
// dependency the same way out of the box.
defaultHealthDependencyTimeout = 5 * time.Second
)
// applyDefaults fills in every absent value. It never reports an error and
@@ -66,6 +71,9 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
if cfg.Health.Listen == "" {
cfg.Health.Listen = defaultHealthListen
}
if cfg.Health.DependencyTimeout == 0 {
cfg.Health.DependencyTimeout = config.Duration(defaultHealthDependencyTimeout)
}
l.applyGeneralDefaults(cfg)
applyForgeDefaults(cfg)
applyDispatchDefaults(cfg)
@@ -208,8 +216,11 @@ func (l *Loader) applyGeneralDefaults(cfg *config.Config) {
if cfg.PollInterval == 0 {
cfg.PollInterval = config.Duration(defaultPollInterval)
}
if cfg.DiffCapLines == 0 {
cfg.DiffCapLines = defaultDiffCapLines
// Only an absent key takes the default. An explicit 0 is the documented
// way to switch the cap off and must survive.
if cfg.DiffCapLines == nil {
capLines := defaultDiffCapLines
cfg.DiffCapLines = &capLines
}
if cfg.Web.Listen == "" {
cfg.Web.Listen = defaultWebListen
@@ -147,3 +147,58 @@ func TestApplyMemoryDefaultsLeavesExplicitEngineAlone(t *testing.T) {
t.Errorf("Memory.Engine = %q, want unchanged %q", cfg.Memory.Engine, "honcho")
}
}
// TestDefaultsKeepAnExplicitUnlimitedDiffCap is the regression case for
// diff_cap_lines = 0 silently becoming 400. The dashboard schema, and
// StageDiffCap itself, both document 0 as "no cap", but the defaults pass could
// not tell an explicit 0 from an absent key and rewrote both to 400 -- so the
// documented way to switch the cap off was unreachable through config.
func TestDefaultsKeepAnExplicitUnlimitedDiffCap(t *testing.T) {
unlimited := 0
cfg := config.Config{DiffCapLines: &unlimited}
(&Loader{}).applyDefaults(&cfg)
if cfg.DiffCapLines == nil {
t.Fatal("DiffCapLines = nil, want the explicit 0 preserved")
}
if *cfg.DiffCapLines != 0 {
t.Fatalf("DiffCapLines = %d, want 0: an explicit 0 means no cap", *cfg.DiffCapLines)
}
if cfg.DiffCap() != 0 {
t.Fatalf("DiffCap() = %d, want 0 (unlimited)", cfg.DiffCap())
}
}
// TestDefaultsApplyTheDiffCapWhenUnset pins the other half: an absent key still
// gets the safety cap, so omitting it never silently auto-opens huge PRs.
func TestDefaultsApplyTheDiffCapWhenUnset(t *testing.T) {
cfg := config.Config{}
(&Loader{}).applyDefaults(&cfg)
if cfg.DiffCapLines == nil || *cfg.DiffCapLines != defaultDiffCapLines {
t.Fatalf("DiffCapLines = %v, want %d when the key is absent", cfg.DiffCapLines, defaultDiffCapLines)
}
}
// TestDefaultsFillTheHealthDependencyTimeout pins that the probe timeout has a
// default, so a config that never mentions it still bounds the Gateway call
// rather than letting a hung dependency stall the whole health report.
func TestDefaultsFillTheHealthDependencyTimeout(t *testing.T) {
cfg := config.Config{}
(&Loader{}).applyDefaults(&cfg)
if got := time.Duration(cfg.Health.DependencyTimeout); got != defaultHealthDependencyTimeout {
t.Fatalf("Health.DependencyTimeout = %v, want %v", got, defaultHealthDependencyTimeout)
}
}
// TestDefaultsKeepAConfiguredHealthDependencyTimeout pins that an operator's
// value is not overwritten, which is the whole point of making it configurable.
func TestDefaultsKeepAConfiguredHealthDependencyTimeout(t *testing.T) {
cfg := config.Config{Health: config.Health{DependencyTimeout: config.Duration(30 * time.Second)}}
(&Loader{}).applyDefaults(&cfg)
if got := time.Duration(cfg.Health.DependencyTimeout); got != 30*time.Second {
t.Fatalf("Health.DependencyTimeout = %v, want the configured 30s", got)
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ func TestRequestJSONRoundTrip(t *testing.T) {
Status: workflow.StatusRunning,
},
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
Cfg: config.Config{DiffCapLines: 500}.ForTask(),
Cfg: config.Config{DiffCapLines: new(500)}.ForTask(),
Providers: map[string]agentexec.Provider{
"anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY"},
},
+1 -1
View File
@@ -374,7 +374,7 @@ func BuildConfigView(in ConfigViewInput) ConfigView {
Label: cfg.Label,
ForgeType: cfg.Forge.Type,
ForgeHost: cfg.Forge.Host,
DiffCapLines: cfg.DiffCapLines,
DiffCapLines: cfg.DiffCap(),
},
Repositories: reposView(cfg.Repos),
MultiIdentity: len(cfg.Identities) > 0,
+1 -1
View File
@@ -108,7 +108,7 @@ func configFieldDescriptors() []ConfigSection {
{Key: "label", Label: "Pickup label", Type: FieldString, Editable: true},
{Key: "forge.type", Label: "Forge type", Type: FieldString, Editable: true, RestartRequired: true},
{Key: "forge.host", Label: "Forge host", Type: FieldString, Editable: true},
{Key: "diff_cap_lines", Label: "Max diff size (lines)", Description: "0 means unlimited.", Type: FieldInt, Editable: true},
{Key: "diff_cap_lines", Label: "Max diff size (lines)", Description: "0 switches the cap off; leave unset for the default.", Type: FieldInt, Editable: true},
},
},
{