d4e254b3494de7ce47477b9421e8c8d3e035e104
11
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
de47bf2398 |
fix(webhook): reject rate-limited deliveries with 429 instead of chat prose or a false 202
Router.Route returned the chat-facing rate-limit prose with a nil error, so the webhook handler had no way to tell a genuine dispatch outcome from a rejection: DeliverTo "origin" echoed the prose as a 200 reply, and any other route got a 202 for an event that was actually dropped before reaching the LLM, so the source never retries it. ChatReply now carries RateLimited, set by a new Router.RouteResult (Route is now a thin wrapper over it) so chat channels that render Text to a human are unaffected. The webhook handler checks it and answers 429, matching the precedent internal/webhookguard.RateLimiter's other callers already set. |
||
|
|
c70fb61bfc |
fix(gateway): stamp the session platform from the channel that carried the message
One Router serves every channel and named itself "web", so Source.Platform -- the FIRST component of the session natural key, and the platform GetByChannel filters on -- was a constant, true of no channel but the dashboard. Two consequences followed: the per-user identity policy was real code that no production call site reached with a real channel name, and a curator pass's write to agent-user memory could not be read back by the turn that wrote it, because that turn resolved no UserID. The channel now travels with the message. Frontends name the channel they carry (pb.Message.platform: telegram, email, webhook, web), and the Gateway stamps the session from it, falling back to its own name when a sender names none -- which is what every existing row holds and what a frontend that does not participate keeps doing. Identity resolution reads the platform off the inbound rather than closing over a channel name, so carriesPersonIdentity finally decides something in production: telegram and email resolve a person, the dashboard and a webhook resolve nothing, and an unknown platform fails closed. Deliberately NOT changed, because it is where this could quietly widen scope: TurnRunnerConfig.Channel still keys tool availability, so no channel gains or loses a tool here. Only session lookup and identity follow the message's platform. Consequence the maintainer accepted: a chat whose active session came from /new or /branch re-resolves once, since GetByChannel now filters on the channel's name. A chat with no /new re-resolves onto the same deterministic session id and heals silently. Verified: gateway, archied, gatewayrpc, messaging, webui, channels and cmd suites, go vet ./..., go build ./..., golangci-lint run ./... (0 issues), docs:check. New contracts: TestResolveSessionKeyStampsTheMessagesPlatform, the per-platform identity table, and the transport-context wire round trip. |
||
|
|
18cca53bab |
fix(webhook): keep a route path out of the sender identity
A webhook set SenderID to its configured route path. The turn path reads that field through a per-channel resolver which refuses webhook, but the session curator derives its participant from the raw field with no channel filter, so a webhook session with exactly one distinct sender and one extracted fact wrote agent-user memory addressed to User: "/hooks/...". Nothing reads it, and every pass added more, because the facts are identical strings with no dedup. docs/prds/memory-engine-unification.md criterion 7 requires that a route path never become a user identity. Clear it at the producer rather than teaching every consumer which channels are lying: a route path is a source, not a person, so it no longer enters SenderID. It still keys the inbound rate limit, where it is the documented per-source budget for webhooks (config.RateLimitConfig), so it travels in the new transport-only Inbound.BudgetKey -- carried on the wire beside Page, never persisted, and never read as an identity. pb.Message gains budget_key (field 9) for the same reason page (field 7) exists: transport context that rides with an inbound message and is deliberately absent from storedProto's rendering of a canonical record. The curator needs no change. An empty SenderID already fails closed as an unidentified user message, which is the path a dashboard session takes, and sessionParticipant's existing skip covers it; the test name now says so. |
||
|
|
4750ac097b |
feat(workflow): post line-anchored review comments with suggested fixes (#891)
* 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. |
||
|
|
db18d2675a |
feat(ratelimit): wire per-identity inbound rate limiting into the gateway
internal/ratelimit was fully built (sliding-window limiter, ticker-driven eviction) but had no consumer, leaving multi-identity deployments with no inbound request budget on any channel (archie-core-6wxb / GH #797). Adds Message.SenderID (Telegram numeric user ID, SMTP from address, or webhook route path -- the closest thing webhook has to a caller identity), threads it into Router.Route/RouteStream via a shared checkRateLimit, and wires an opt-in [chat.rate_limit] config section through bootstrap with the documented EvictStale ticker. |
||
|
|
e3b1a859a8 |
feat(gateway): flip channel boundary onto messaging.Message
Replaced gateway.Message as the currency at the channel-facing boundary with the canonical internal/domain/messaging.Message. Channel adapters now build the record directly (RoleUser, ConversationID, Sender) and the Router hands it back unchanged, so nothing converts between two shapes in process. gateway.Message is deleted; the dashboard route that had no home in the record lives in a new Inbound envelope (Message + transport-only Page), which reaches the system prompt and is never persisted. Role is now set at construction instead of derived at the store boundary, and the assistant reply is a direct messaging.Message (RoleAssistant, Sender=botUser). The gRPC proto is unchanged: pb.Message still carries no role, and both sides keep deriving it from the owning session's bot identity via gateway.RoleForSender (ToStoredMessage/FromStoredMessage are deleted). Adds tests that the old shape could not express: Page reaches the system prompt but not the persisted record, and a channel-built Inbound round-trips with the Role the channel set. Refs: archie-core-9g5e |
||
|
|
f820a89e32 |
fix(channels): call MarkRunning once a channel is actually up
channels.Manager.MarkRunning was never called for telegram, email, or
webhook -- every start path only called MarkStarting then MarkFailed
on error, so the dashboard showed a working channel stuck on
"Starting" forever (confirmed live: Telegram polling and delivering
messages while /api/channels still reported "starting").
Adds gateway.Lifecycle{Starting, Running func()}, threaded through
Gateway.Start(ctx, router, lifecycle). Email and webhook report
Running once their listener actually binds -- webhook moves off
http.Server.ListenAndServe's internal bind to an explicit
net.ListenConfig.Listen so binding is observable before Serve.
Telegram reports Running after StartWebhook launches in webhook mode,
or after the first successful getUpdates response in long-poll mode,
observed via a pollReadinessClient http.Client wrapper since the
go-telegram/bot library keeps polling errors inside its own worker
goroutine. Restart re-reports Starting/Running each cycle.
|
||
|
|
543b657472 |
feat(webhookguard): shared HMAC, rate-limit, and redaction mechanics
archie-core-7d5u.3 -- storage-agnostic building blocks for vetting inbound webhook-shaped requests, extracted rather than duplicated: - VerifyHMAC: behavior-preserving extraction of internal/channels/webhook's private validateHMAC. internal/channels/webhook now calls it instead of keeping its own copy; all 10 of that package's existing tests still pass unmodified, and the one now-redundant unit test was removed with a comment pointing to where its coverage relocated. - RateLimiter: per-source token bucket. Source IDs come from a registered, operator-controlled set, not unbounded attacker input, so the bucket map is not itself bounded -- documented explicitly rather than left implicit. - RedactPayload: key-name-based redaction, matching gateway/stream.go's sensitiveParameterKey marker list. Deliberately does NOT reuse that function's actual behavior: it replaces every string value regardless of key, correct for a bounded chat summary and wrong here -- a captured payload exists to be inspected for field mapping (t2db.3), so only values under a sensitive-looking key are touched. Narrowed from 7d5u.3's original scope, which bundled capture storage and an approval state machine into this package. Both moved to the beads that own that state (t2db.1's capture store depends on 7d5u.2's still-open NATS storage decision; t2db.4's binding is the only consumer of approval state today) rather than building shared abstractions ahead of a second real consumer. Adversarially reviewed by a fresh subagent with zero surviving findings: token-bucket math hand-traced on two scenarios and race-clean under -race, the redaction/gateway-stream.go behavioral divergence verified by reading both functions side by side, both the redaction and rate-limit guards mutation-tested by disabling each and confirming the suite catches it. task check exit 0, golangci-lint 0 issues, gofumpt clean. |
||
|
|
a9e8cda4f2 |
fix(qa4.3): resolve nilerr, bodyclose, contextcheck, containedctx, fatcontext lint findings
- bodyclose: add deferred resp.Body.Close() in storage_test.go Docker test handler
- contextcheck: thread context through email handleSMTP/processMessage; replace
context.Background() with context.WithoutCancel(ctx) in telegram, webhook, webui
shutdown paths and container pool cleanup; add ctx parameter to Pool.Release
- containedctx: replace ctx context.Context struct field with stopCh chan struct{}
in StdioTransport and SSETransport; thread lifecycle context through goroutine
chains instead of storing it in structs
- fatcontext: lift context deadline derivation out of PrefetchContext loop
|
||
|
|
f4787a819d |
feat: email channel + Channel interface with config schema validation
Email channel (internal/channels/email): - SMTP server receiving inbound emails on configurable port - Multipart body extraction (text/plain from MIME) - SMTP relay for outbound replies with STARTTLS + AUTH - 8 tests, race-clean Channel interface (internal/channels/channel.go): - ConfigSchema() — JSON Schema for channel configuration - ValidateConfig() — validates channel-specific config at startup - All three channels (Telegram, Email, Webhook) implement it - Compile-time guard: var _ channels.Channel = (*Gateway)(nil) Config: ChatConfig.Email added (listen_addr, relay_addr). Daemon: email gateway wired into main.go behind chat.email block. 40 packages pass with -race. |
||
|
|
20a1210d0e |
feat: webhook platform + persona registry (items 5+6)
Webhook platform (internal/channels/webhook): - Gateway adapter with HTTP server, HMAC validation, dot-notation template extraction - Per-route configuration with secret-based signing - Deliver-to-origin mode for sync responses - 11 tests, race-clean Persona registry (internal/gateway/persona.go): - PersonaRegistry with per-session active persona selection - DefaultPersonas(): helpful, concise, technical, creative, teacher - Persona prompt prepended to system prompt in LLMResponder - Thread-safe, 5 tests Config: ChatConfig.WebhookAddr added for webhook listen address. All 39 packages pass with -race. Closes abg.5.3, abg.34. |