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.
This commit is contained in:
108 files changed
+5133
-2523
No files matched your search
+5
-4
@@ -32,6 +32,7 @@ See `docs/architecture/organisation.md` for the target structure and
|
||||
| `internal/domain/workflow/task/` | Task-execution vocabulary (`Task`, statuses, mid-run `Store`, `Definition`) importable without the engine |
|
||||
| `internal/domain/messaging/` | Canonical messages plus the chat wire contracts (`ChatContract`, sessions, turns, streaming) shared by gateway, channels, webui, and archie-ui |
|
||||
| `internal/channels/status/` | Operator-facing channel lifecycle ledger (`State`/`Descriptor`/`Status`/`Manager`); the plugin contract stays in `internal/channels` |
|
||||
| `internal/app/archiemessaging/` | Messaging Service composition: Telegram/email/webhook channels, dialling the Gateway's `ChatContract` over gRPC. The daemon runs no channel and builds no `gateway.Router` |
|
||||
| `internal/domain/workintake/`| `TaskEnvelope`, routing `Kind`, label vocabulary, task subjects |
|
||||
| `internal/agentexec/` | Worker-local stage protocol and ai-sdk loop runner |
|
||||
| `internal/forge/` | Forge interface: GitHub and Gitea implementations |
|
||||
@@ -375,10 +376,10 @@ each narrowed to exactly the operations it needs:
|
||||
field to override. `ScopeGlobal` is never model-writable.
|
||||
|
||||
`boot.setupMemoryEngine` (`internal/app/archied/bootstrap.go`) registers and
|
||||
starts the engine and must run before `setupGateways`/`setupGatewayChat`:
|
||||
those construct every chat turn runner, which captures the engine at
|
||||
construction time (`internal/app/archied/composition_order_test.go` pins the
|
||||
ordering). The session curator (`internal/infrastructure/sessioncurator`)
|
||||
starts the engine and must run before `setupGatewayChat`, which constructs the
|
||||
only chat turn runner in production and captures the engine at construction
|
||||
time (`internal/app/archied/composition_order_test.go` pins the ordering), and
|
||||
before `setupCurators`, whose `Registrar` captures the engine registry. The session curator (`internal/infrastructure/sessioncurator`)
|
||||
writes derived records onto `ScopeAgentUser`, making it the engine's other
|
||||
live producer besides the chat write path.
|
||||
|
||||
|
||||
@@ -72,13 +72,6 @@ ARG GOLANGCI_LINT_VERSION=2.13.2
|
||||
ARG GOFUMPT_VERSION=0.11.0
|
||||
ARG BUF_VERSION=1.72.0
|
||||
|
||||
# Fail the build rather than ship an image whose two formatters disagree.
|
||||
RUN want="$(curl -fsSL "https://raw.githubusercontent.com/golangci/golangci-lint/v${GOLANGCI_LINT_VERSION}/go.mod" | awk '$1 == "mvdan.cc/gofumpt" { sub(/^v/, "", $2); print $2 }')" && \
|
||||
if [ "$want" != "${GOFUMPT_VERSION}" ]; then \
|
||||
echo "golangci-lint v${GOLANGCI_LINT_VERSION} vendors gofumpt v${want}, but GOFUMPT_VERSION=${GOFUMPT_VERSION}: task fmt and task lint would disagree." >&2; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
RUN curl -fsSL "https://github.com/golangci/golangci-lint/releases/download/v${GOLANGCI_LINT_VERSION}/golangci-lint-${GOLANGCI_LINT_VERSION}-linux-amd64.tar.gz" \
|
||||
| tar -xz -C /usr/local/bin --strip-components=1 \
|
||||
"golangci-lint-${GOLANGCI_LINT_VERSION}-linux-amd64/golangci-lint" && \
|
||||
|
||||
@@ -300,12 +300,14 @@ tasks:
|
||||
- "{{.BIN_DIR}}/archie-gateway"
|
||||
- "{{.BIN_DIR}}/archie-state-store"
|
||||
- "{{.BIN_DIR}}/archie-ui"
|
||||
- "{{.BIN_DIR}}/archie-messaging"
|
||||
- "{{.BIN_DIR}}/archie-agent"
|
||||
cmds:
|
||||
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/app/archied.runtimeVersion={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archied ./cmd/archied
|
||||
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-gateway ./cmd/archie-gateway
|
||||
- go build -o {{.BIN_DIR}}/archie-state-store ./cmd/archie-state-store
|
||||
- go build -o {{.BIN_DIR}}/archie-ui ./cmd/archie-ui
|
||||
- go build -o {{.BIN_DIR}}/archie-messaging ./cmd/archie-messaging
|
||||
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-agent ./cmd/archie-agent
|
||||
|
||||
test:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Command archie-messaging hosts the external channel frontends as their own
|
||||
// process, against a Gateway reached over its gRPC contract.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/archiemessaging"
|
||||
)
|
||||
|
||||
func main() { os.Exit(run()) }
|
||||
|
||||
func run() int {
|
||||
base, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
var options archiemessaging.Options
|
||||
flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory")
|
||||
flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory")
|
||||
flag.StringVar(&options.Gateway.Target, "gateway-target", "", "archie-gateway gRPC address (defaults to [services.gateway].target, else 127.0.0.1:8585)")
|
||||
flag.StringVar(&options.Gateway.Token, "gateway-token", "", "bearer token presented to archie-gateway")
|
||||
flag.DurationVar(&options.DependencyTimeout, "dependency-timeout", 0, "readiness probe timeout (default 5s)")
|
||||
flag.DurationVar(&options.ShutdownTimeout, "shutdown-timeout", 0, "shutdown timeout (default 5s)")
|
||||
flag.Parse()
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
if err := archiemessaging.Run(ctx, options); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
)
|
||||
|
||||
func repoRoot(t *testing.T) string {
|
||||
t.Helper()
|
||||
_, file, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
t.Fatal("runtime.Caller failed")
|
||||
}
|
||||
dir := filepath.Dir(file)
|
||||
for {
|
||||
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
|
||||
return dir
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
t.Fatal("could not find repo root")
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
|
||||
func buildBinary(t *testing.T) string {
|
||||
t.Helper()
|
||||
bin := filepath.Join(t.TempDir(), "archie-messaging")
|
||||
cmd := exec.CommandContext(t.Context(), "go", "build", "-o", bin, "./cmd/archie-messaging")
|
||||
cmd.Dir = repoRoot(t)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("go build archie-messaging: %v\n%s", err, string(out))
|
||||
}
|
||||
return bin
|
||||
}
|
||||
|
||||
type fakeChatServer struct {
|
||||
messaging.ChatContract
|
||||
}
|
||||
|
||||
func (f *fakeChatServer) Snapshot(ctx context.Context) (messaging.ChatSnapshot, error) {
|
||||
return messaging.ChatSnapshot{}, nil
|
||||
}
|
||||
|
||||
func startTestGateway(t *testing.T) (target string, cleanup func()) {
|
||||
t.Helper()
|
||||
lis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("net.Listen: %v", err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
gatewayrpc.RegisterServer(srv, &fakeChatServer{})
|
||||
go func() {
|
||||
_ = srv.Serve(lis)
|
||||
}()
|
||||
return lis.Addr().String(), func() {
|
||||
srv.GracefulStop()
|
||||
_ = lis.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestBinaryHelp(t *testing.T) {
|
||||
bin := buildBinary(t)
|
||||
cmd := exec.CommandContext(t.Context(), bin, "-help")
|
||||
out, err := cmd.CombinedOutput()
|
||||
// flag.ExitOnError or flag help returns exit 0 or 2 depending on standard library
|
||||
if !strings.Contains(string(out), "gateway-target") {
|
||||
t.Fatalf("help output missing gateway-target flag: %v\n%s", err, string(out))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBinaryStartsAndShutsDownCleanly(t *testing.T) {
|
||||
bin := buildBinary(t)
|
||||
gatewayTarget, cleanup := startTestGateway(t)
|
||||
defer cleanup()
|
||||
|
||||
cmd := exec.CommandContext(t.Context(), bin, "-gateway-target", gatewayTarget)
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("cmd.Start: %v", err)
|
||||
}
|
||||
|
||||
// Allow the process to start up.
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
// Send SIGTERM to shut down gracefully.
|
||||
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
|
||||
t.Fatalf("send SIGTERM: %v", err)
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- cmd.Wait()
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
t.Fatalf("process exited with error on SIGTERM: %v", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
_ = cmd.Process.Kill()
|
||||
t.Fatal("process did not exit in time after SIGTERM")
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,8 @@ class = "ollama"
|
||||
# token = { engine = "bws", key = "TELEGRAM_BOT_TOKEN" }
|
||||
# Legacy compatibility: read the token from this environment variable.
|
||||
# token_env = "TELEGRAM_BOT_TOKEN" # env var holding the bot token from @BotFather
|
||||
# Run by archie-messaging, which serves /update, so these commands execute on
|
||||
# whichever host runs that process.
|
||||
# update_check_command = ["/usr/local/bin/archie-update-check"]
|
||||
# update_install_command = ["/usr/local/bin/archie-update-install"]
|
||||
|
||||
|
||||
@@ -55,7 +55,12 @@ surviving blocking finding — or a review that failed to run — parks the task
|
||||
(`StatusParked`, not `waiting_human`) with the findings rendered into the park
|
||||
reason; `StageOpenPR` never runs. Warn/plausible findings and the zero-finding
|
||||
case leave the outcome unset, so the PR opens with a findings section rendered
|
||||
onto its body.
|
||||
onto its body. `StagePostReviewComments` then runs after `StageOpenPR` and posts
|
||||
the **line-anchored** findings as inline review comments, carrying a one-click
|
||||
suggestion on a confirmed finding the reviewer could state a fix for. That stage
|
||||
is best-effort — a comment that fails to post is logged, never a park — because
|
||||
the body section already lists every finding, and it is the record a whole-file
|
||||
finding (no line to anchor to) only ever appears in.
|
||||
|
||||
## Model and budget
|
||||
|
||||
|
||||
@@ -188,6 +188,35 @@ describes the target, not today's tree. Kept rather than deleted because the
|
||||
migration it serves is deferred by this very section, and re-deriving a tested
|
||||
wire adapter once that lands is pure cost.
|
||||
|
||||
**Phase 4 Messaging Service extraction (2026-09-19, `archie-core-8cda.6.1`).**
|
||||
The process boundary for external channels (Telegram, email, webhook) is ratified
|
||||
in [`docs/prds/messaging-service-boundary.md`](../prds/messaging-service-boundary.md).
|
||||
Messaging is extracted into `cmd/archie-messaging` / `internal/app/archiemessaging`,
|
||||
calling Gateway's `messaging.ChatContract` exclusively over gRPC. Channel frontends
|
||||
hold no direct database handles, daemon state, or model runtimes.
|
||||
|
||||
**Telegram operator surface after extraction (2026-09-19, `archie-core-8cda.6.6`).**
|
||||
`setupTelegramGateway` wired eight `telegram.Gateway` seams the daemon could
|
||||
satisfy from its own process. Each is resolved by where the fact it needs is
|
||||
actually owned, not by where it used to be built:
|
||||
|
||||
| Seam | Resolution |
|
||||
|---|---|
|
||||
| `Version` | Sourced from the Gateway via `ChatSnapshot.Version`. The Messaging Service never stamps or infers a build version; `cmd/archie-messaging` deliberately takes no version ldflags, so it cannot report a partial upgrade as a matched one. |
|
||||
| `Updates` (`/update`) | Built in the Messaging Service from `[chat.telegram].update_check_command` / `update_install_command` — its own configuration. `Enrich` is dropped: `componentInstallTypeEnricher` reads `[nats]`, which this service must not decode, so the check command's own reported install type stands unmodified. |
|
||||
| `UpdateReportPath` | A local state file under `work_dir`, keyed by the same `sha256(bot_user)[:8]` scheme the daemon used, so a pending report is found rather than written afresh. |
|
||||
| `ReleaseAnnouncements` | **Deliberately left nil**, for the same reason as `RunningVersions`. `releaseannounce.Announcer` announces nothing unless each `Component` carries a parseable version, and the only versions this service can obtain are the Gateway's own build stamps, not archied's. Wiring the announcer without them yields a no-op that reads as configured, so it stays unwired until component self-reporting exists. |
|
||||
| `SetShowToolCalls` | Projected from `[chat].show_tool_calls`. |
|
||||
| `Reload` | Local: re-resolves the token and allowlist from this service's own config file and overlay. Reload was never a daemon fact. |
|
||||
| `RunningVersions` | **Deliberately left nil.** It exists to turn an installer's claim into a checked one, and only a component's own compiled-in build can vouch for it. The Messaging Service knows neither archied's build nor the observed archie-agent version (`daemon.AgentStatus`), and the Gateway's own `gatewayVersion` is a different binary's stamp — reporting it as the daemon's would manufacture exactly the false success the check exists to catch. Update reports therefore relay as unverified claims until a component self-report contract exists. |
|
||||
| `Dangerous` | Stays nil. No daemon composition ever set it; `/rollback` and `/stop` reported "not configured" before the extraction and still do. |
|
||||
|
||||
The Messaging Service consequently reads `work_dir`, `bot_user`, `[chat]` and
|
||||
`[health]` in addition to the PRD's `[chat.*]` / `[services.gateway]` list.
|
||||
`[health]` is the daemon's health URL, which `releaseupdate.CommandInstaller`
|
||||
polls from outside to confirm an update came back up; the rest of the PRD's
|
||||
prohibition list is untouched.
|
||||
|
||||
### 3. Identity data migration
|
||||
|
||||
The migration must define:
|
||||
|
||||
@@ -304,73 +304,57 @@
|
||||
},
|
||||
"MessageEvent": {
|
||||
"additionalProperties": false,
|
||||
"description": "MessageEvent is the rich message model for all gateway channels.",
|
||||
"description": "MessageEvent is the rich message model for gateway channels.",
|
||||
"properties": {
|
||||
"callback_data": {
|
||||
"description": "CallbackData is the payload from a button or inline-keyboard\npress (Type == MsgCallback).",
|
||||
"type": "string"
|
||||
},
|
||||
"channel_id": {
|
||||
"description": "ChannelID identifies the conversation within the platform\n(chat ID, channel name, DM thread).",
|
||||
"type": "string"
|
||||
},
|
||||
"edited_from": {
|
||||
"description": "EditedFrom is the original text before the edit. Set only when\nType is MsgEdited.",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "ID is the platform-assigned message identifier. Used for reply\nthreading, reactions, and edit/delete tracking.",
|
||||
"type": "string"
|
||||
},
|
||||
"media": {
|
||||
"description": "Media holds attached files. Nil for text-only messages.",
|
||||
"items": {
|
||||
"$ref": "#/schemas/MediaAttachment"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"platform": {
|
||||
"description": "Platform names the source adapter (\"telegram\", \"discord\",\n\"web\", \"slack\").",
|
||||
"type": "string"
|
||||
},
|
||||
"raw": {
|
||||
"description": "Raw is the original platform-specific payload. Adapters set\nthis for debug logging or handlers that need platform details\nnot captured by the generic fields.",
|
||||
"type": "object"
|
||||
},
|
||||
"reacted_to_id": {
|
||||
"description": "ReactedToID is the message being reacted to.",
|
||||
"type": "string"
|
||||
},
|
||||
"reaction": {
|
||||
"description": "Reaction is the emoji used when Type is MsgReaction.",
|
||||
"type": "string"
|
||||
},
|
||||
"reply_to_id": {
|
||||
"description": "ReplyToID is the platform message ID this message is in reply\nto. Empty for top-level messages.",
|
||||
"type": "string"
|
||||
},
|
||||
"sender_id": {
|
||||
"description": "SenderID is the platform-specific sender identifier.",
|
||||
"type": "string"
|
||||
},
|
||||
"sender_name": {
|
||||
"description": "SenderName is the display name when available.",
|
||||
"type": "string"
|
||||
},
|
||||
"text": {
|
||||
"description": "Text is the human-readable message body. It carries the caption\nfor media messages and the full content for text and system\nmessages.",
|
||||
"type": "string"
|
||||
},
|
||||
"thread_id": {
|
||||
"description": "ThreadID identifies the conversation thread for platforms that\nsupport threading (Slack, Discord forums).",
|
||||
"type": "string"
|
||||
},
|
||||
"timestamp": {
|
||||
"description": "Timestamp is the platform-assigned message time in Unix\nmilliseconds. Zero when unknown.",
|
||||
"type": "integer"
|
||||
},
|
||||
"type": {
|
||||
"description": "Type discriminates the message kind.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
|
||||
+42
-10
@@ -1,6 +1,6 @@
|
||||
# Inline review -- decision
|
||||
|
||||
**Status:** Proposed
|
||||
**Status:** Implemented
|
||||
**Beads issue:** `archie-core-q9au`
|
||||
**Builds on:** `archie-core-h019` (adversarial self-review), `docs/architecture/adversarial-review.md`
|
||||
|
||||
@@ -26,15 +26,30 @@ Both halves are missing today:
|
||||
|
||||
### 1. A narrow, type-asserted write surface
|
||||
|
||||
The set of comments travels in one call, so a forge that can only carry them on
|
||||
a submitted review needs one request rather than one per finding:
|
||||
|
||||
```go
|
||||
type ReviewCommentWriter interface {
|
||||
CreateReviewComment(ctx context.Context, owner, repo string, number int,
|
||||
commitID, path string, line int, body string) error
|
||||
CreateReviewComments(ctx context.Context, owner, repo string, number int,
|
||||
comments []InlineReviewComment) error
|
||||
}
|
||||
```
|
||||
|
||||
Type-asserted like `PullRequestReader`/`PullRequestReviewReader`, so a forge
|
||||
that cannot do it is skipped rather than faked.
|
||||
that cannot do it is skipped rather than faked. The stage reaches it through
|
||||
`workflow.Forger`, whose production implementation is `forgerpc.Client` — the
|
||||
worker holds no forge credentials, so the daemon's forgerpc server type-asserts
|
||||
`forge.ReviewCommentWriter` and answers an incapable forge with an error the
|
||||
best-effort stage logs.
|
||||
|
||||
The comment's line is anchored to the pull request's **current head revision**,
|
||||
resolved inside each implementation rather than passed in by the caller: it is
|
||||
the revision the comments are attached to, and the caller that produced the line
|
||||
numbers holds no forge credentials to read it. The caller does pass the revision
|
||||
those line numbers were **measured on** (`TaskContext.ReviewedHeadSHA`,
|
||||
recorded when `StageOpenPR` opens the pull request), and the implementation
|
||||
posts only while the head it read still matches it — see §4.
|
||||
|
||||
Per-forge reality (verified against the SDKs, 2026-09-11):
|
||||
|
||||
@@ -59,9 +74,14 @@ definition the verdict the reviewer traced and can state the failure for. A
|
||||
`plausible` finding is a worry, and a worry gets a sentence, not a patch. This is
|
||||
the h019.5 calibration rule reused, not a new one.
|
||||
|
||||
`Suggestion` replaces the anchored line exactly. Single-line only in this cut;
|
||||
`Suggestion` replaces the anchored line exactly, and is only rendered when
|
||||
`Verdict == confirmed`. Single-line only in this cut;
|
||||
multi-line (GitHub's `StartLine`/`StartSide`) is a follow-up, because a
|
||||
multi-line suggestion that is off by one line silently corrupts the file.
|
||||
multi-line suggestion that is off by one line silently corrupts the file. The
|
||||
rule is enforced in `ReviewFinding.Validate` — an embedded newline is rejected
|
||||
there, so the `record_finding` tool refuses it with feedback the model can act
|
||||
on, rather than the renderer silently posting a fence that applies only its
|
||||
first line.
|
||||
|
||||
### 3. Which findings are posted inline
|
||||
|
||||
@@ -80,10 +100,22 @@ otherwise be a body-only list the author has to map back to lines by hand.
|
||||
New `StagePostReviewComments`, after `StageOpenPR`:
|
||||
|
||||
1. Read the report stashed by `StageReview` (`tc.ReviewReport`, h019.6).
|
||||
2. Resolve the head SHA via `PullRequestReader.GetPullRequest` (the PR now
|
||||
exists).
|
||||
3. Post each line-anchored finding as an inline comment, with a suggestion block
|
||||
when `Verdict == confirmed && Suggestion != ""`.
|
||||
2. Post each line-anchored finding as an inline comment, with a suggestion block
|
||||
when `Verdict == confirmed && Suggestion != ""`. The head SHA the comments are
|
||||
anchored to is resolved by the forge implementation, not here; there is no
|
||||
`PullRequestReader` on this side of the agent boundary. The stage passes
|
||||
`tc.ReviewedHeadSHA` alongside them.
|
||||
|
||||
Nothing in the run pushes between `StageReview` and this stage, so at that
|
||||
moment the pull request's head *is* the revision the review read. That was an
|
||||
assumption, and a collaborator can falsify it by pushing to the branch between
|
||||
the review and the posting. A line number is not validated against a revision:
|
||||
both forges anchor it to whatever now occupies that line, so a stale anchor
|
||||
mislabels rather than failing. The revision is therefore carried with the
|
||||
comments and the set is refused when the head has moved off it
|
||||
(`reviewHeadDrift`) — a refusal lands in the failure path below, leaving the PR
|
||||
body as the record. With no measured revision (a `Trees` that cannot report one)
|
||||
the comments post unverified rather than being dropped.
|
||||
|
||||
**Failures log and never fail the task.** The PR is already open; a comment that
|
||||
failed to post must not park a task whose actual work succeeded, and the body
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Messaging Service boundary and transport design
|
||||
|
||||
**Status:** Ratified (rev. 1)
|
||||
**Date:** 2026-09-19
|
||||
**Beads issue:** `archie-core-8cda.6.1`
|
||||
**Parent:** [`service-decomposition.md`](service-decomposition.md)
|
||||
**Prerequisites:** Gateway contract extraction (Phase 1), State Store extraction (Phase 2), UI extraction (Phase 3)
|
||||
|
||||
This document is the authoritative specification for Phase 4: Messaging Service extraction. It fixes the process boundary, configuration ownership, client contracts, security posture, readiness behavior, channel invariants, and deletion criteria required by `archie-core-8cda.6` and its child tasks.
|
||||
|
||||
## Decision
|
||||
|
||||
The Messaging Service (`cmd/archie-messaging`, composed via `internal/app/archiemessaging`) owns external channel connections (Telegram, email, webhook) and dispatches inbound messages and commands to the standalone Gateway Service over gRPC via `messaging.ChatContract`.
|
||||
|
||||
It is a peer service to the UI Service and the daemon:
|
||||
- It serves external chat participants across configured communication platforms.
|
||||
- It consumes Gateway's `messaging.ChatContract` exclusively for chat turn execution, streaming, session queries, cancellation, persona selection, and task control actions.
|
||||
- It holds no direct database connections (`*store.Store` or SQLite), owns no LLM execution or model provider credentials, and has no dependency on the daemon runtime or the UI HTTP server.
|
||||
|
||||
## Boundary and Ownership
|
||||
|
||||
| Concern | Messaging Service owns | Messaging Service consumes | Messaging Service must not own or link |
|
||||
|---|---|---|---|
|
||||
| **Channel transports** | Telegram bot long-polling, Email IMAP/SMTP loops, Inbound Webhook HTTP listener | Gateway `ChatContract` | Direct LLM providers, model runtimes, tokenizer libraries |
|
||||
| **Turn dispatch** | Inbound message packaging, typing indicators, live streaming updates | `ChatContract.Route`, `ChatContract.Stream` | `gateway.Router`, `runtime.Runtime`, agent prompt builders |
|
||||
| **Sessions & History** | Platform-to-session key mapping, conversation thread ID translation | `ChatContract.GetSession`, `RecentMessages`, `RecentTurns` | `*store.Store`, `SessionStore` SQLite handles, direct database files |
|
||||
| **Control & Actions** | Platform command parsing (`/status`, `/tasks`, `/cancel`, `/stop`, `/persona`) | `ChatContract.Snapshot`, `ApplyTaskAction`, `Cancel`, `SetPersona` | `daemon.Daemon`, workflow execution engine, worktree operations |
|
||||
| **Task Approvals** | Channel interactive keyboards, approval callbacks | `ChatContract.ApplyTaskAction` | Direct task status mutations, forge comment posters |
|
||||
| **Configuration** | Platform bot tokens, allowed sender/user IDs, webhook listen ports | `[chat.*]` channel configs, Gateway target/token | `config.Holder`, forge tokens, repo configs, agent container specs |
|
||||
| **Readiness** | Messaging process liveness, channel connectivity, Gateway probe | Gateway `ChatContract.Snapshot` | Internal daemon subsystem probes |
|
||||
|
||||
## Target Service Shape
|
||||
|
||||
1. **Binary entry point**: `cmd/archie-messaging/main.go` parses CLI flags (`-config`, `-config-overlay`, `-gateway-target`, `-gateway-token`) and hands execution to `internal/app/archiemessaging.Run`.
|
||||
2. **Application composition**: `internal/app/archiemessaging/` wires:
|
||||
- Config loading scoped strictly to `[chat.*]` and `[services.gateway]`.
|
||||
- Secret resolution for channel credentials (e.g. Telegram bot token).
|
||||
- Gateway gRPC client (`internal/infrastructure/gatewayrpc.Client`).
|
||||
- Channel lifecycle managers (`internal/channels/status`).
|
||||
- Channel instances (`internal/channels/telegram`, `email`, `webhook`).
|
||||
3. **Turn and Stream Execution**:
|
||||
- Channels adapt inbound platform messages to `messaging.Inbound`.
|
||||
- Streaming channels (Telegram) consume `ChatContract.Stream(ctx, inbound)` which returns `<-chan messaging.ChatEvent`, mapping `started`, `delta`, `tool`, `media`, `done`, and `error` events directly to live message frames.
|
||||
- Non-streaming channels (email, synchronous webhooks) consume `ChatContract.Route(ctx, inbound)`.
|
||||
|
||||
## Load-Bearing Channel Invariants
|
||||
|
||||
The Messaging Service preserves existing invariants defined in `AGENTS.md` and channel documentation:
|
||||
1. **Telegram long-polling**: Must call `dropPendingUpdates(ctx, b)` before `b.Start(ctx)` and on `/restart`.
|
||||
2. **Telegram command menus**: Must register command menus simultaneously to `default`, `all_private_chats`, and `all_group_chats` via `commands.go` to prevent menu shadowing.
|
||||
3. **No UI detour**: Turns and task actions route directly to Gateway's `ChatContract`; no HTTP request may ever be sent to `archie-ui` or `internal/webui`.
|
||||
4. **Sender Confinement**: Telegram sender checks against `allowed_user_ids` must continue to fail closed before initiating any turn dispatch.
|
||||
|
||||
## Configuration Ownership
|
||||
|
||||
`cmd/archie-messaging` reads only:
|
||||
- `[services.gateway].target` and `[services.gateway].target_token` (or CLI flags).
|
||||
- `[chat.telegram]` (token, allowed user IDs).
|
||||
- `[chat.email]` (IMAP/SMTP host, ports, credentials).
|
||||
- `[chat.webhook]` (listen address, secret).
|
||||
- `[secrets]` (for resolving token secret references).
|
||||
|
||||
It does not read or decode `[forge]`, `[repos]`, `[models]`, `[providers]`, `[runners]`, `[containers]`, or `[nats]`.
|
||||
|
||||
## Deletion Gate and Verification
|
||||
|
||||
The extraction is guarded by `cmd/archie-messaging/architecture_test.go`, verifying that `go list -deps ./cmd/archie-messaging` links zero banned runtime packages:
|
||||
- `modernc.org/sqlite` and `internal/store` (State Store)
|
||||
- `internal/daemon`, `internal/app/archied`, `internal/container`, `internal/worktree` (Daemon runtime)
|
||||
- `internal/domain/workflow`, `internal/agentexec`, `internal/taskrun` (Workflow engine)
|
||||
- `internal/forge`, `internal/forgerpc` (Forge client)
|
||||
- `internal/gateway` runtime (only `internal/domain/messaging` and `internal/infrastructure/gatewayrpc` are permitted)
|
||||
- `internal/webui` (Dashboard)
|
||||
@@ -2,16 +2,21 @@ cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
|
||||
cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
|
||||
cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
|
||||
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cloud.google.com/go/auth v0.23.1/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE=
|
||||
code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg=
|
||||
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
|
||||
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
|
||||
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
|
||||
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4=
|
||||
@@ -20,14 +25,18 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
|
||||
github.com/bwesterb/go-ristretto v1.2.4/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
|
||||
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||
github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g=
|
||||
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0=
|
||||
@@ -42,6 +51,10 @@ github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
|
||||
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
||||
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.39.0/go.mod h1:5e4ylfTZO723MEEFsCpSW4ZEBWR8mwkEyXfwJBTCZ9c=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
|
||||
@@ -56,13 +69,17 @@ github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4s
|
||||
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.5 h1:sE+OlkHgYWNMVmN1s9sR7uyFgsWLtxcNWse/vBYKxRE=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.5/go.mod h1:3IjhiZnM+uBmUrOGSeqrJpsmi4Vd0H2NZO/uK2a7d0s=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
|
||||
github.com/go-telegram/bot v1.27.0 h1:PG9yBDzM8O26oUerE9SZwWlHon4RpH8WcNslZ7CEZmE=
|
||||
github.com/go-telegram/bot v1.27.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/codesearch v1.3.0-rc.1 h1:vSFGuF5wS3sjimuLzqPG+PGjWQ9VvEtPFbxdZD7YuuQ=
|
||||
@@ -76,10 +93,14 @@ github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfh
|
||||
github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
|
||||
github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
|
||||
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
|
||||
github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
@@ -107,6 +128,7 @@ github.com/moby/moby/api v1.56.0 h1:GQzua3NA599ASSIICx0iFgiJeO9YkdDARvQsm23ZZuQ=
|
||||
github.com/moby/moby/api v1.56.0/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
|
||||
github.com/moby/moby/client v0.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs=
|
||||
github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ=
|
||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.15.0 h1:M99yf0y05rTr46/qc/Is6ZAowI58Ryp2SjufLCUeVJc=
|
||||
@@ -127,15 +149,20 @@ github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
|
||||
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
|
||||
github.com/samcharles93/ai-sdk v0.1.39 h1:gbNPYeA27MifReCruBiqMgb4fFSjCDi1Zv57a9bo0Vo=
|
||||
github.com/samcharles93/ai-sdk v0.1.39/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk=
|
||||
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
@@ -144,6 +171,7 @@ github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
|
||||
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
@@ -171,6 +199,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -192,8 +221,11 @@ golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
|
||||
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
|
||||
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679 h1:FEp7JNE32DTAwbnI/ixagnmj7Xm1eTONofGEUXFjZ4w=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679/go.mod h1:52bV8FLAQ9Qmcqaq9ECLmuEHZthk+6OPV45aKBBrsNw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260918162117-cecb64721679 h1:KmqdJU4vrNcxy/6qdg3JduZtalEXrJLspVltnR1cE+8=
|
||||
|
||||
@@ -162,6 +162,8 @@ Verdict is "confirmed" only when you have traced the actual failure -- read the
|
||||
|
||||
Level is "error" for a defect that blocks; "warn" for something worth knowing but not blocking.
|
||||
|
||||
When a confirmed defect's fix is mechanical, and only then, pass suggestion: the exact text that should replace the anchored line, so the author can apply it in one click. It replaces that line exactly, so include the whole line (indentation included) and nothing else, and never guess -- a wrong one-click fix is worse than none. Do not pass a suggestion for a plausible finding, or for a fix you cannot state as a single line.
|
||||
|
||||
When you have finished checking, reply with a short summary of what you checked and what you found (or that you found nothing). If you find nothing, say so plainly -- reporting zero findings on properties you actually checked is a valid and expected outcome, not a failure to find something.`
|
||||
|
||||
// reviewerPrompt renders the reviewer's mission: the diff and issue text.
|
||||
@@ -234,6 +236,7 @@ type findingInput struct {
|
||||
Line int `json:"line" jsonschema:"description=Line number where the defect is located."`
|
||||
Defect string `json:"defect" jsonschema:"description=One-sentence statement of the defect."`
|
||||
FailureScenario string `json:"failure_scenario" jsonschema:"description=Concrete inputs or state that produce the wrong output or a crash -- not a hypothetical."`
|
||||
Suggestion string `json:"suggestion,omitempty" jsonschema:"description=Optional. The exact replacement for the anchored line, when the fix is mechanical and you are certain of it -- it is offered as a one-click apply, so an approximate or partial line is worse than none. Only a confirmed finding may carry one; omit it for a plausible finding. Single line only."`
|
||||
Verdict string `json:"verdict" jsonschema:"description=Only 'confirmed' may block. Use 'plausible' for a real worry you have not fully traced.,enum=confirmed|plausible"`
|
||||
Level string `json:"level" jsonschema:"description=error blocks when confirmed; warn is advisory only.,enum=error|warn"`
|
||||
Category string `json:"category" jsonschema:"enum=dead-code|unchecked-error|hardcoded-value|interface-satisfaction|nil-risk|goroutine-leak|race|other"`
|
||||
@@ -254,6 +257,7 @@ func recordFindingTool(findings *[]workflow.ReviewFinding) *core.Tool {
|
||||
Line: in.Line,
|
||||
Defect: in.Defect,
|
||||
FailureScenario: in.FailureScenario,
|
||||
Suggestion: in.Suggestion,
|
||||
Verdict: workflow.ReviewVerdict(in.Verdict),
|
||||
Level: workflow.ReviewLevel(in.Level),
|
||||
Category: workflow.ReviewCategory(in.Category),
|
||||
|
||||
@@ -108,6 +108,22 @@ func (h *hybridTrees) Snapshot(ctx context.Context, dir, destDir string) error {
|
||||
return h.local.Snapshot(ctx, dir, destDir)
|
||||
}
|
||||
|
||||
// Resume is a no-op here for the same reason Prepare is: resuming a PR
|
||||
// branch needs the daemon's forge credential to fetch, so archied must run
|
||||
// it against the bind-mounted worktree before the container starts, the
|
||||
// same way it runs Prepare today. The container's worktree is already
|
||||
// resumed by the time a remediate run reaches this stage.
|
||||
func (h *hybridTrees) Resume(ctx context.Context, dir, branch string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Dir returns the bind-mounted worktree path archied already prepared,
|
||||
// ignoring its arguments -- the sandbox has no way to independently derive
|
||||
// or verify the path, same as Prepare above.
|
||||
func (h *hybridTrees) Dir(owner, repo string, issue int) string {
|
||||
return h.localDir
|
||||
}
|
||||
|
||||
func (h *hybridTrees) ChangedLines(ctx context.Context, dir, base string) (int, error) {
|
||||
return h.local.ChangedLines(ctx, dir, base)
|
||||
}
|
||||
|
||||
@@ -271,6 +271,14 @@ func (f *prCapturingForge) VerifyPush(context.Context, string, string) error {
|
||||
|
||||
func (f *prCapturingForge) LinkBranch(context.Context, string, string, int, string) error { return nil }
|
||||
|
||||
func (f *prCapturingForge) CreateReviewComments(context.Context, string, string, int, string, []workflow.ReviewComment) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) ReplyToReview(context.Context, string, string, int, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type remoteManager struct {
|
||||
manager *worktree.Manager
|
||||
dir string
|
||||
|
||||
@@ -23,9 +23,6 @@ import (
|
||||
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/email"
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/channels/webhook"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
@@ -123,8 +120,7 @@ type boot struct {
|
||||
catalog modelcatalog.Snapshot
|
||||
catalogModels []string
|
||||
|
||||
bus *events.Bus
|
||||
channelManager *status.Manager
|
||||
bus *events.Bus
|
||||
// rateLimiter is the shared per-(channel, sender) inbound budget every
|
||||
// chat Router is given. Nil when [chat.rate_limit] is not configured,
|
||||
// which leaves rate limiting off.
|
||||
@@ -402,44 +398,13 @@ func (b *boot) loadCatalog(ctx context.Context, cfgPath string) {
|
||||
b.log.Info("model catalog loaded", "providers", len(catalog.Providers), "models", len(b.catalogModels))
|
||||
}
|
||||
|
||||
// channelDescriptors projects the configured chat front-ends into the
|
||||
// dashboard's channel-status descriptors.
|
||||
//
|
||||
// Configured comes from config.ChatConfig.FrontEnds so this list and the
|
||||
// configuration projection published for the extracted UI process cannot
|
||||
// disagree about whether a front-end is set up (GitHub #821). ReloadSupported
|
||||
// and Detail stay here because they are channel-lifecycle facts about the bot
|
||||
// the daemon runs, not configuration: only Telegram can be reloaded in place
|
||||
// today, and its allowlist caveat is about who the running bot answers.
|
||||
func channelDescriptors(chat config.ChatConfig) []status.Descriptor {
|
||||
frontEnds := chat.FrontEnds()
|
||||
descriptors := make([]status.Descriptor, 0, len(frontEnds))
|
||||
for _, frontEnd := range frontEnds {
|
||||
descriptor := status.Descriptor{
|
||||
ID: frontEnd.ID,
|
||||
Name: frontEnd.Name,
|
||||
Configured: frontEnd.Configured,
|
||||
}
|
||||
if frontEnd.ID == "telegram" {
|
||||
descriptor.ReloadSupported = frontEnd.Configured
|
||||
if frontEnd.Configured && len(chat.Telegram.AllowedUserIDs) == 0 {
|
||||
descriptor.Detail = "Token set, but the allowlist is empty -- the bot answers nobody."
|
||||
}
|
||||
}
|
||||
descriptors = append(descriptors, descriptor)
|
||||
}
|
||||
return descriptors
|
||||
}
|
||||
|
||||
// setupObservability builds the event bus, channel manager and dashboard
|
||||
// server. Every event is logged to SQLite (stamped with its row id) and
|
||||
// setupObservability builds the event bus and dashboard server. Every event is logged to SQLite (stamped with its row id) and
|
||||
// then fanned out to live dashboard connections.
|
||||
func (b *boot) setupObservability(ctx context.Context) {
|
||||
cfg, log := b.cfg, b.log
|
||||
bus := events.NewBus()
|
||||
b.bus = bus
|
||||
b.addCleanup(func() { bus.Close() })
|
||||
b.channelManager = status.NewManager(channelDescriptors(cfg.Chat))
|
||||
b.cfgHolder = config.NewHolder(cfg)
|
||||
// The watchdog leaves its verdict in a file on this host, so the daemon
|
||||
// reads it and publishes the outcome as an event; the dashboard renders
|
||||
@@ -633,7 +598,9 @@ const rateLimiterEvictInterval = time.Minute
|
||||
|
||||
// startRateLimiter constructs b.rateLimiter from cfg when configured, and
|
||||
// drives its documented EvictStale ticker for the life of ctx. Leaves
|
||||
// b.rateLimiter nil (rate limiting off) when cfg is not enabled.
|
||||
// b.rateLimiter nil (rate limiting off) when cfg is not enabled. Only the
|
||||
// Gateway process calls it: it owns the sole Router, so it is the one place
|
||||
// an inbound budget can be applied to every channel's turns.
|
||||
func (b *boot) startRateLimiter(ctx context.Context, cfg config.RateLimitConfig) {
|
||||
if !cfg.Enabled() {
|
||||
return
|
||||
@@ -654,161 +621,6 @@ func (b *boot) startRateLimiter(ctx context.Context, cfg config.RateLimitConfig)
|
||||
}()
|
||||
}
|
||||
|
||||
// setupGateways assembles the Telegram, email and webhook gateways. It
|
||||
// returns false when the Telegram gateway could not start, which the
|
||||
// caller treats as a fatal boot error.
|
||||
//
|
||||
// Multi-agent collaboration PRD phase C (docs/prds/multi-agent-collaboration.md).
|
||||
func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) bool {
|
||||
cfg, log := b.cfg, b.log
|
||||
b.startRateLimiter(ctx, cfg.Chat.RateLimit)
|
||||
start, ok := setupTelegramGateway(ctx, telegramSetup{
|
||||
Cfg: config.NewHolder(cfg), CfgPath: cfgPath, OverlayPath: overlayPath,
|
||||
St: b.stateStore, LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg,
|
||||
Personas: b.personas, ChatTasks: b.chatTasks, ChatController: b.chatController,
|
||||
ChatTaskLister: chatTaskListerAdapter{tasks: b.stateStore.Tasks},
|
||||
ChatTaskLogs: chatTaskLogReaderAdapter{
|
||||
tasks: b.stateStore.TaskByID,
|
||||
taskLogs: b.taskLogs,
|
||||
},
|
||||
ChatTaskActor: chatTaskActorAdapter{
|
||||
contract: func() gateway.ChatContract {
|
||||
if b.chat != nil {
|
||||
return b.chat.Contract
|
||||
}
|
||||
return nil
|
||||
}(),
|
||||
},
|
||||
ChatPRReviewer: b.prReviewer(),
|
||||
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, Updates: b.updateService,
|
||||
Secrets: b.secrets,
|
||||
Bus: b.bus,
|
||||
Log: log,
|
||||
ChannelManager: b.channelManager, AgentStatus: b.agentStatus,
|
||||
RateLimiter: b.rateLimiter,
|
||||
MemoryEngine: b.memoryStore(),
|
||||
MemoryWriter: b.memoryWriter(),
|
||||
})
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if start != nil {
|
||||
b.startGateways = append(b.startGateways, start)
|
||||
}
|
||||
|
||||
if !b.setupEmailGateway(ctx, cfg, log) {
|
||||
return false
|
||||
}
|
||||
if !b.setupWebhookGateway(ctx, cfg, log) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// setupEmailGateway registers the optional inbound email gateway when
|
||||
// chat.email.listen_addr is configured. It returns false when the
|
||||
// configured gateway fails its own ConfigSchema validation, which the
|
||||
// caller treats as a fatal boot error -- the same convention
|
||||
// setupTelegramGateway already uses.
|
||||
func (b *boot) setupEmailGateway(ctx context.Context, cfg config.Config, log *slog.Logger) bool {
|
||||
if cfg.Chat.Email.ListenAddr == "" {
|
||||
return true
|
||||
}
|
||||
em := email.New(cfg.Chat.Email.ListenAddr, cfg.Chat.Email.RelayAddr, log)
|
||||
if err := em.ValidateConfig(map[string]any{
|
||||
"listen_addr": cfg.Chat.Email.ListenAddr,
|
||||
"relay_addr": cfg.Chat.Email.RelayAddr,
|
||||
}); err != nil {
|
||||
log.Error("chat.email config invalid", "err", err)
|
||||
return false
|
||||
}
|
||||
emRouter := gateway.NewRouter(b.stateStore, nil, "email")
|
||||
emRouter.Limiter = b.rateLimiter
|
||||
configureTaskCommands(emRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.stateStore.Tasks}, b.defaultChatIdentity)
|
||||
b.startGateways = append(b.startGateways, func() {
|
||||
go func() {
|
||||
lifecycle := gateway.Lifecycle{
|
||||
Starting: func() { b.channelManager.MarkStarting("email") },
|
||||
Running: func() {
|
||||
b.channelManager.MarkRunning("email")
|
||||
log.Info("email gateway started", "addr", cfg.Chat.Email.ListenAddr)
|
||||
},
|
||||
}
|
||||
if err := em.Start(ctx, emRouter, lifecycle); err != nil && ctx.Err() == nil {
|
||||
b.channelManager.MarkFailed("email", err.Error())
|
||||
log.Error("email gateway stopped", "err", err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// setupWebhookGateway registers the optional inbound webhook gateway when
|
||||
// chat.webhook_addr is configured. It returns false when the configured
|
||||
// gateway fails its own ConfigSchema validation, which the caller treats
|
||||
// as a fatal boot error -- the same convention setupTelegramGateway
|
||||
// already uses.
|
||||
func (b *boot) setupWebhookGateway(ctx context.Context, cfg config.Config, log *slog.Logger) bool {
|
||||
if cfg.Chat.WebhookAddr == "" {
|
||||
return true
|
||||
}
|
||||
host, port := parseListenAddr(cfg.Chat.WebhookAddr, "0.0.0.0", 8644)
|
||||
secretValue, err := b.secrets.Resolve(cfg.Chat.Webhook.Secret)
|
||||
if err != nil {
|
||||
log.Error("webhook gateway secret unresolvable; starting with signature validation disabled",
|
||||
"engine", cfg.Chat.Webhook.Secret.Engine, "key", cfg.Chat.Webhook.Secret.Key, "err", err)
|
||||
}
|
||||
wh := webhook.New(
|
||||
host, port,
|
||||
webhookRoutes(cfg.Chat.Webhook, secretValue),
|
||||
log,
|
||||
)
|
||||
if err := wh.ValidateConfig(map[string]any{
|
||||
"host": host,
|
||||
"port": port,
|
||||
}); err != nil {
|
||||
log.Error("chat.webhook config invalid", "err", err)
|
||||
return false
|
||||
}
|
||||
whRouter := gateway.NewRouter(b.stateStore, nil, "webhook")
|
||||
whRouter.Limiter = b.rateLimiter
|
||||
configureTaskCommands(whRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.stateStore.Tasks}, b.defaultChatIdentity)
|
||||
b.startGateways = append(b.startGateways, func() {
|
||||
go func() {
|
||||
lifecycle := gateway.Lifecycle{
|
||||
Starting: func() { b.channelManager.MarkStarting("webhook") },
|
||||
Running: func() {
|
||||
b.channelManager.MarkRunning("webhook")
|
||||
log.Info("webhook gateway started", "addr", fmt.Sprintf("%s:%d", host, port))
|
||||
},
|
||||
}
|
||||
if err := wh.Start(ctx, whRouter, lifecycle); err != nil && ctx.Err() == nil {
|
||||
b.channelManager.MarkFailed("webhook", err.Error())
|
||||
log.Error("webhook gateway stopped", "err", err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// webhookRoutes translates the configured [chat.webhook] route into the
|
||||
// gateway's RouteConfig. It is the composition site config.WebhookRoute
|
||||
// exists for: the HMAC/template/deliver-to fields have been implemented and
|
||||
// tested in internal/channels/webhook since it was written, reachable only
|
||||
// through this translation.
|
||||
func webhookRoutes(route config.WebhookRoute, secretValue string) []webhook.RouteConfig {
|
||||
path := route.Path
|
||||
if path == "" {
|
||||
path = "/webhook"
|
||||
}
|
||||
return []webhook.RouteConfig{{
|
||||
Path: path,
|
||||
Secret: secretValue,
|
||||
Template: route.Template,
|
||||
DeliverTo: route.DeliverTo,
|
||||
}}
|
||||
}
|
||||
|
||||
// loadWorkflows builds the workflow registry from the skill catalog.
|
||||
// Plugin-defined workflows override built-ins of the same name;
|
||||
// built-ins fill gaps.
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func TestConfiguredNetworkGatewaysBecomeRunning(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
id string
|
||||
cfg config.Config
|
||||
}{
|
||||
{
|
||||
name: "email",
|
||||
id: "email",
|
||||
cfg: config.Config{Chat: config.ChatConfig{Email: config.EmailConfig{
|
||||
ListenAddr: "127.0.0.1:0",
|
||||
}}},
|
||||
},
|
||||
{
|
||||
name: "webhook",
|
||||
id: "webhook",
|
||||
cfg: config.Config{Chat: config.ChatConfig{
|
||||
WebhookAddr: "127.0.0.1:0",
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "archie.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
manager := status.NewManager([]status.Descriptor{{
|
||||
ID: test.id, Name: test.name, Configured: true,
|
||||
}})
|
||||
b := &boot{
|
||||
cfg: test.cfg,
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
st: st,
|
||||
stateStore: st,
|
||||
channelManager: manager,
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
if ok := b.setupGateways(ctx, "", ""); !ok {
|
||||
t.Fatal("setupGateways returned false")
|
||||
}
|
||||
if len(b.startGateways) != 1 {
|
||||
t.Fatalf("start gateways = %d, want 1", len(b.startGateways))
|
||||
}
|
||||
b.startGateways[0]()
|
||||
|
||||
deadline := time.Now().Add(250 * time.Millisecond)
|
||||
for time.Now().Before(deadline) {
|
||||
if got := manager.Snapshot()[0].State; got == status.StateRunning {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatalf("channel state = %q, want %q after successful startup",
|
||||
manager.Snapshot()[0].State, status.StateRunning)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -13,61 +12,42 @@ import (
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/ratelimit"
|
||||
"github.com/samcharles93/archie-core/internal/releaseannounce"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// telegramSetup contains the inputs needed to initialise the Telegram
|
||||
// chat gateway. Every field is intentionally explicit so the function
|
||||
// signature acts as a contract of what the gateway depends on.
|
||||
type telegramSetup struct {
|
||||
// Cfg is read once per setup function via Get(); the daemon is not
|
||||
// chatSetup contains the inputs needed to build a chat turn runner and the
|
||||
// services that support it. Every field is intentionally explicit so the
|
||||
// function signature acts as a contract of what a chat turn depends on.
|
||||
type chatSetup struct {
|
||||
// Cfg is read once per setup function via Get(); the process is not
|
||||
// running yet at this point, so the reload-safe Holder is mostly a
|
||||
// formality, but matching the daemon's API keeps callers honest.
|
||||
Cfg *config.Holder
|
||||
CfgPath string
|
||||
OverlayPath string
|
||||
St storecontract.TaskStore
|
||||
LLM *runtime.Runtime
|
||||
ChatModels gateway.ModelManager
|
||||
ToolReg *tools.Registry
|
||||
Personas *gateway.PersonaRegistry
|
||||
ChatTasks gateway.TaskCreator
|
||||
ChatController gateway.TaskController
|
||||
ChatTaskLister gateway.ChatTaskLister
|
||||
ChatTaskLogs gateway.ChatTaskLogReader
|
||||
ChatTaskActor gateway.ChatTaskActor
|
||||
ChatPRReviewer gateway.ChatPRReviewer
|
||||
DefaultChatIdentity string
|
||||
SessionStore gateway.SessionStore
|
||||
Updates telegram.UpdateService
|
||||
Dangerous gateway.DangerousCommandAuthority
|
||||
// Bus carries primary-input events (archie-core-035): a completed
|
||||
// chat turn is published here so input-driven curators can wake. Nil
|
||||
// disables turn events (tests, minimal setups).
|
||||
Bus *events.Bus
|
||||
Log *slog.Logger
|
||||
ChannelManager *status.Manager
|
||||
Bus *events.Bus
|
||||
Log *slog.Logger
|
||||
// AgentStatus is the composition root's shared tracker for the most
|
||||
// recently observed archie-agent version (see daemon.AgentStatus).
|
||||
// Nil disables the agent component of RunningVersions.
|
||||
AgentStatus *daemon.AgentStatus
|
||||
Secrets *secret.Registry
|
||||
// RateLimiter budgets inbound messages per sender when set. Nil
|
||||
// leaves rate limiting off.
|
||||
RateLimiter *ratelimit.Limiter
|
||||
// MemoryEngine is the durable-memory read surface (b.memEngines' active
|
||||
// engine, resolved by cfg.Memory.Engine). Nil disables the chat <memory>
|
||||
// block for every turn runner built from this setup.
|
||||
@@ -78,106 +58,6 @@ type telegramSetup struct {
|
||||
MemoryWriter gateway.MemoryWriteStore
|
||||
}
|
||||
|
||||
// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects
|
||||
// from the typed config, carrying whichever credential source is set
|
||||
// (token takes precedence, matching resolveTelegramToken).
|
||||
func telegramValidateConfigMap(cfg config.TelegramConfig) map[string]any {
|
||||
m := map[string]any{"token_env": cfg.TokenEnv}
|
||||
if cfg.Token != (secret.SecretRef{}) {
|
||||
m["token"] = map[string]any{"engine": cfg.Token.Engine, "key": cfg.Token.Key}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func resolveTelegramToken(cfg config.TelegramConfig, registry *secret.Registry) (string, error) {
|
||||
if cfg.Token != (secret.SecretRef{}) {
|
||||
return registry.Resolve(cfg.Token)
|
||||
}
|
||||
if cfg.TokenEnv == "" {
|
||||
return "", nil
|
||||
}
|
||||
return os.Getenv(cfg.TokenEnv), nil
|
||||
}
|
||||
|
||||
// setupTelegramGateway initialises the Telegram chat gateway when a
|
||||
// token is configured. It returns a start function (nil when no token
|
||||
// is configured) and ok=false to signal the caller must exit early.
|
||||
func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), ok bool) {
|
||||
cfg := s.Cfg.Get()
|
||||
if cfg.Chat.Telegram.Token == (secret.SecretRef{}) && cfg.Chat.Telegram.TokenEnv == "" {
|
||||
return nil, true
|
||||
}
|
||||
tgToken, err := resolveTelegramToken(cfg.Chat.Telegram, s.Secrets)
|
||||
if err != nil {
|
||||
s.Log.Error("chat.telegram token resolution failed", "err", err)
|
||||
return nil, false
|
||||
}
|
||||
if tgToken == "" {
|
||||
s.Log.Error("chat.telegram configured but token is empty")
|
||||
return nil, false
|
||||
}
|
||||
if len(cfg.Chat.Telegram.AllowedUserIDs) == 0 {
|
||||
s.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " +
|
||||
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
|
||||
}
|
||||
tg := telegram.New(tgToken, cfg.Chat.Telegram.AllowedUserIDs, s.Log)
|
||||
if err := tg.ValidateConfig(telegramValidateConfigMap(cfg.Chat.Telegram)); err != nil {
|
||||
s.Log.Error("chat.telegram config invalid", "err", err)
|
||||
return nil, false
|
||||
}
|
||||
tg.Version = func() string {
|
||||
return fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
|
||||
}
|
||||
if s.Updates != nil {
|
||||
tg.Updates = s.Updates
|
||||
} else {
|
||||
configureTelegramUpdates(tg, s)
|
||||
}
|
||||
tg.Dangerous = s.Dangerous
|
||||
tg.SetShowToolCalls(cfg.Chat.ShowToolCalls)
|
||||
tg.ReleaseAnnouncements = &releaseannounce.Announcer{
|
||||
StatePath: releaseAnnouncementStatePath(cfg.WorkDir, cfg.BotUser),
|
||||
Components: []releaseannounce.Component{
|
||||
{ID: "gateway", Label: "THE GATEWAY", Version: gatewayVersion, ChangelogPath: packagedGatewayChangelogPath},
|
||||
{ID: "runtime", Label: "THE RUNTIME", Version: runtimeVersion, ChangelogPath: packagedRuntimeChangelogPath},
|
||||
},
|
||||
}
|
||||
tg.UpdateReportPath = updateReportPath(cfg.WorkDir, cfg.BotUser)
|
||||
agentStatus := s.AgentStatus
|
||||
tg.RunningVersions = func() map[string]string { return daemonRunningVersions(agentStatus) }
|
||||
tg.Reload = makeTelegramReload(s)
|
||||
|
||||
sessionStore := s.SessionStore
|
||||
if sessionStore == nil {
|
||||
s.Log.Error("telegram conversation store is not configured")
|
||||
return nil, false
|
||||
}
|
||||
router := buildTelegramRouter(ctx, tg, s, sessionStore)
|
||||
return func() {
|
||||
go func() {
|
||||
lifecycle := gateway.Lifecycle{
|
||||
Starting: func() {
|
||||
if s.ChannelManager != nil {
|
||||
s.ChannelManager.MarkStarting("telegram")
|
||||
}
|
||||
},
|
||||
Running: func() {
|
||||
if s.ChannelManager != nil {
|
||||
s.ChannelManager.MarkRunning("telegram")
|
||||
}
|
||||
s.Log.Info("telegram gateway started")
|
||||
},
|
||||
}
|
||||
if err := tg.Start(ctx, router, lifecycle); err != nil && ctx.Err() == nil {
|
||||
if s.ChannelManager != nil {
|
||||
s.ChannelManager.MarkFailed("telegram", err.Error())
|
||||
}
|
||||
s.Log.Error("telegram gateway stopped", "err", err)
|
||||
}
|
||||
}()
|
||||
}, true
|
||||
}
|
||||
|
||||
// daemonRunningVersions reports the component versions this process can
|
||||
// vouch for, for checking a pending update report against (see
|
||||
// releaseupdate.Report.Verify).
|
||||
@@ -241,13 +121,7 @@ func componentInstallTypeEnricher(agentStatus *daemon.AgentStatus, nats config.N
|
||||
}
|
||||
}
|
||||
|
||||
func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) {
|
||||
if updates := makeUpdateService(s); updates != nil {
|
||||
tg.Updates = updates
|
||||
}
|
||||
}
|
||||
|
||||
func makeUpdateService(s telegramSetup) *releaseupdate.Service {
|
||||
func makeUpdateService(s chatSetup) *releaseupdate.Service {
|
||||
cfg := s.Cfg.Get()
|
||||
if len(cfg.Chat.Telegram.UpdateCheckCommand) == 0 {
|
||||
return nil
|
||||
@@ -267,30 +141,6 @@ func makeUpdateService(s telegramSetup) *releaseupdate.Service {
|
||||
return updates
|
||||
}
|
||||
|
||||
func makeTelegramReload(s telegramSetup) func(*telegram.Gateway) error {
|
||||
return func(g *telegram.Gateway) error {
|
||||
doc, err := configuration.New(s.Log).Resolve(s.CfgPath, s.OverlayPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reload config: %w", err)
|
||||
}
|
||||
newCfg := doc.Config
|
||||
token, err := resolveTelegramToken(newCfg.Chat.Telegram, s.Secrets)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reload config: resolve telegram token: %w", err)
|
||||
}
|
||||
if token == "" {
|
||||
return fmt.Errorf("reload config: chat.telegram token is empty")
|
||||
}
|
||||
g.Token = token
|
||||
g.AllowedUserIDs = newCfg.Chat.Telegram.AllowedUserIDs
|
||||
g.SetShowToolCalls(newCfg.Chat.ShowToolCalls)
|
||||
s.Log.Info("chat gateway config reloaded",
|
||||
"allowed_user_ids", len(g.AllowedUserIDs),
|
||||
"show_tool_calls", g.ShowToolCalls())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func makeTelegramSessionStore(cfg config.Config) (gateway.SessionStore, error) {
|
||||
return gateway.OpenSQLiteSessionStore(conversationDBPath(cfg.DBPath))
|
||||
}
|
||||
@@ -300,33 +150,10 @@ func conversationDBPath(taskDBPath string) string {
|
||||
return taskDBPath + "-conversations.sqlite"
|
||||
}
|
||||
|
||||
func buildTelegramRouter(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore) *gateway.Router {
|
||||
// The router is built before the responder so the responder can resolve
|
||||
// sessions through it. Both orderings work at runtime -- the responder is
|
||||
// a closure -- but this way the dependency is visible rather than
|
||||
// captured by reference.
|
||||
router := gateway.NewRouter(s.St, nil, "telegram")
|
||||
router.Limiter = s.RateLimiter
|
||||
router.Models = s.ChatModels
|
||||
router.Updates = s.Updates
|
||||
router.Personas = s.Personas
|
||||
router.InitSessions(sessionStore)
|
||||
router.Titles = newChatTitleGenerator(s)
|
||||
router.Log = s.Log
|
||||
configureTaskCommands(router, s.ChatTasks, s.ChatController, s.ChatTaskLister, s.DefaultChatIdentity)
|
||||
|
||||
if s.LLM != nil {
|
||||
turnRunner := newChatTurnRunner(ctx, tg.Name(), s, sessionStore, router)
|
||||
router.LLM = turnRunner.Respond
|
||||
router.LLMStream = turnRunner.RespondStream
|
||||
}
|
||||
return router
|
||||
}
|
||||
|
||||
func makeChatLLMResponder(
|
||||
ctx context.Context,
|
||||
channel string,
|
||||
s telegramSetup,
|
||||
s chatSetup,
|
||||
sessionStore gateway.SessionStore,
|
||||
router *gateway.Router,
|
||||
) (gateway.LLMResponder, gateway.LLMStreamResponder) {
|
||||
@@ -340,7 +167,7 @@ func makeChatLLMResponder(
|
||||
func newChatTurnRunner(
|
||||
ctx context.Context,
|
||||
channel string,
|
||||
s telegramSetup,
|
||||
s chatSetup,
|
||||
sessionStore gateway.SessionStore,
|
||||
router *gateway.Router,
|
||||
) *gateway.TurnRunner {
|
||||
@@ -535,7 +362,7 @@ type chatTitleGenerator struct {
|
||||
// newChatTitleGenerator wires an LLM-backed title generator for a chat
|
||||
// setup, or nil when no model is available. Title generation is optional
|
||||
// everywhere, so every caller tolerates nil.
|
||||
func newChatTitleGenerator(s telegramSetup) gateway.TitleGenerator {
|
||||
func newChatTitleGenerator(s chatSetup) gateway.TitleGenerator {
|
||||
if s.LLM == nil || s.ChatModels == nil {
|
||||
return nil
|
||||
}
|
||||
+2
-64
@@ -7,70 +7,8 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
type telegramTestSecretEngine struct{}
|
||||
|
||||
func (telegramTestSecretEngine) Name() string { return "bws" }
|
||||
func (telegramTestSecretEngine) Version() string { return "test" }
|
||||
func (telegramTestSecretEngine) Resolve(key string) (string, error) {
|
||||
if key == "telegram-token" {
|
||||
return "token-from-bws", nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenPrefersSecretRef(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(telegramTestSecretEngine{})
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
|
||||
}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got != "token-from-bws" {
|
||||
t.Fatalf("resolveTelegramToken = %q, want token-from-bws", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenFallsBackToTokenEnv(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
cfg := config.TelegramConfig{TokenEnv: "TELEGRAM_LEGACY_TOKEN"}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got != "token-from-env" {
|
||||
t.Fatalf("resolveTelegramToken = %q, want token-from-env", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenDoesNotUseTokenEnvWhenSecretRefIsSet(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(telegramTestSecretEngine{})
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
|
||||
}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got == "token-from-env" {
|
||||
t.Fatal("resolveTelegramToken used TokenEnv despite Token being configured")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMakeUpdateServiceWiresInstallType is the regression test for
|
||||
// archie-core-522's fail-closed guarantee actually reaching production: a
|
||||
// Service built without InstallType always refuses to install (see
|
||||
@@ -81,7 +19,7 @@ func TestMakeUpdateServiceWiresInstallType(t *testing.T) {
|
||||
cfg.Chat.Telegram.UpdateCheckCommand = []string{"archie-update-check"}
|
||||
cfg.Chat.Telegram.UpdateInstallCommand = []string{"archie-update-install"}
|
||||
|
||||
service := makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)})
|
||||
service := makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)})
|
||||
|
||||
if service == nil {
|
||||
t.Fatal("makeUpdateService returned nil despite a configured check command")
|
||||
@@ -220,7 +158,7 @@ func TestMakeUpdateServiceProbesTheDaemonsOwnHealthAddress(t *testing.T) {
|
||||
cfg.Chat.Telegram.UpdateCheckCommand = []string{"archie-update-check"}
|
||||
cfg.Chat.Telegram.UpdateInstallCommand = []string{"archie-update-install"}
|
||||
|
||||
service := makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)})
|
||||
service := makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)})
|
||||
|
||||
if service == nil {
|
||||
t.Fatal("makeUpdateService returned nil despite a configured check command")
|
||||
@@ -6,65 +6,16 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestRunBuildsWorktreeManagerBeforeGateways pins the composition order that
|
||||
// review_pr depends on.
|
||||
//
|
||||
// boot.prReviewer captures b.trees, and it refuses to produce a reviewer when
|
||||
// b.trees is nil so that a process which can never run a review does not
|
||||
// advertise the tool. In the daemon that makes the order load-bearing: if the
|
||||
// gateway wiring runs first it asks for a reviewer before the worktree manager
|
||||
// exists, gets nil, and the daemon silently offers no review_pr at all. Nothing
|
||||
// at runtime observes the order, so it is asserted by source position, the same
|
||||
// way TestSetupBackendsRegistersContainerCleanupAfterNATS in
|
||||
// TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat pins the ordering
|
||||
// docs/prds/memory-engine-unification.md §4's "Prerequisite" note requires.
|
||||
// startGatewayRuntime (gateway.go) constructs the only chat turn runner in
|
||||
// production via setupGatewayChat, and a turn runner captures b.memEngines at
|
||||
// construction time via boot.memoryStore(). Built the other way round it
|
||||
// captures a nil engine and the chat <memory> block never appears, silently,
|
||||
// because renderMemory treats a nil engine the same as a failed read. Nothing
|
||||
// at runtime observes the order, so it is asserted by source position, the
|
||||
// same way TestSetupBackendsRegistersContainerCleanupAfterNATS in
|
||||
// bootstrap_nats_test.go pins cleanup ordering for the same reason.
|
||||
func TestRunBuildsWorktreeManagerBeforeGateways(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "main.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := methodBody(t, file, "Run")
|
||||
trees := methodCallPosition(run, "buildTreesAndIdentities")
|
||||
gateways := methodCallPosition(run, "setupGateways")
|
||||
if trees == token.NoPos || gateways == token.NoPos {
|
||||
t.Fatalf("Run call positions: buildTreesAndIdentities=%v setupGateways=%v, want both present", trees, gateways)
|
||||
}
|
||||
if gateways < trees {
|
||||
t.Fatal("Run wires the gateways before buildTreesAndIdentities; prReviewer captures b.trees, so review_pr would be dropped instead of advertised")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSetsUpMemoryBeforeGateways pins the ordering
|
||||
// docs/prds/memory-engine-unification.md §4's "Prerequisite" note requires:
|
||||
// setupGateways constructs every chat turn runner (setupGatewayChat,
|
||||
// setupTelegramGateway), and a turn runner captures b.memEngines at
|
||||
// construction time via boot.memoryStore(). Built the other way round, every
|
||||
// turn runner captures a nil engine and the chat <memory> block never
|
||||
// appears, silently, because renderMemory treats a nil engine the same as a
|
||||
// failed read. Nothing at runtime observes the order, so it is asserted by
|
||||
// source position, the same way TestRunBuildsWorktreeManagerBeforeGateways
|
||||
// pins the worktree-manager ordering above.
|
||||
func TestRunSetsUpMemoryBeforeGateways(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "main.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := methodBody(t, file, "Run")
|
||||
memoryEngine := methodCallPosition(run, "setupMemoryEngine")
|
||||
gateways := methodCallPosition(run, "setupGateways")
|
||||
if memoryEngine == token.NoPos || gateways == token.NoPos {
|
||||
t.Fatalf("Run call positions: setupMemoryEngine=%v setupGateways=%v, want both present", memoryEngine, gateways)
|
||||
}
|
||||
if gateways < memoryEngine {
|
||||
t.Fatal("Run wires the gateways before setupMemoryEngine; every turn runner would capture a nil memory engine")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat is the standalone
|
||||
// Gateway process's half of the same prerequisite: startGatewayRuntime
|
||||
// (gateway.go) constructs the turn runner via setupGatewayChat, which must
|
||||
// see a non-nil b.memEngines already.
|
||||
func TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "gateway.go", nil, 0)
|
||||
|
||||
@@ -11,16 +11,15 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// TestPublishedProjectionAgreesWithTheChannelManagerOnConfiguredChannels: the
|
||||
// daemon answers "is a chat channel configured" twice -- once through the
|
||||
// channel status manager it exposes on /api/channels, and once through the
|
||||
// ChatView.ChannelConfigured boolean it publishes for the dashboard's setup
|
||||
// checklist. Those two answers are read by different pages of the same
|
||||
// extracted process, so a deployment that the manager calls configured must
|
||||
// not be told by the checklist to connect a channel it already has. Both sides
|
||||
// now derive from one definition (config.ChatConfig.FrontEnds); this test is
|
||||
// what keeps them from being re-decided separately.
|
||||
func TestPublishedProjectionAgreesWithTheChannelManagerOnConfiguredChannels(t *testing.T) {
|
||||
// TestPublishedProjectionAgreesWithFrontEndsOnConfiguredChannels: "is a chat
|
||||
// channel configured" is answered twice -- once by config.ChatConfig.FrontEnds,
|
||||
// which the channel status surface on /api/channels is built from, and once by
|
||||
// the ChatView.ChannelConfigured boolean this process publishes for the
|
||||
// dashboard's setup checklist. A deployment that FrontEnds calls configured
|
||||
// must not be told by the checklist to connect a channel it already has. Both
|
||||
// sides derive from that one definition; this test is what keeps them from
|
||||
// being re-decided separately.
|
||||
func TestPublishedProjectionAgreesWithFrontEndsOnConfiguredChannels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg config.Config
|
||||
@@ -64,11 +63,11 @@ func TestPublishedProjectionAgreesWithTheChannelManagerOnConfiguredChannels(t *t
|
||||
}
|
||||
b.setupObservability(t.Context())
|
||||
|
||||
// What the dashboard's /api/channels page reads.
|
||||
managerSaysConfigured := false
|
||||
for _, descriptor := range b.channelManager.Snapshot() {
|
||||
if descriptor.Configured {
|
||||
managerSaysConfigured = true
|
||||
// What the dashboard's /api/channels page is built from.
|
||||
frontEndsSayConfigured := false
|
||||
for _, frontEnd := range tc.cfg.Chat.FrontEnds() {
|
||||
if frontEnd.Configured {
|
||||
frontEndsSayConfigured = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,9 +82,9 @@ func TestPublishedProjectionAgreesWithTheChannelManagerOnConfiguredChannels(t *t
|
||||
t.Fatalf("decode the published projection: %v", err)
|
||||
}
|
||||
|
||||
if published.Chat.ChannelConfigured != managerSaysConfigured {
|
||||
t.Errorf("published Chat.ChannelConfigured = %v, but the channel manager reports a configured front-end = %v (%+v)",
|
||||
published.Chat.ChannelConfigured, managerSaysConfigured, published.Chat)
|
||||
if published.Chat.ChannelConfigured != frontEndsSayConfigured {
|
||||
t.Errorf("published Chat.ChannelConfigured = %v, but ChatConfig.FrontEnds reports a configured front-end = %v (%+v)",
|
||||
published.Chat.ChannelConfigured, frontEndsSayConfigured, published.Chat)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -125,6 +125,7 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc
|
||||
b.bus = events.NewBus()
|
||||
b.addCleanup(b.bus.Close)
|
||||
b.capabilityHost = plugin.NewHost()
|
||||
b.startRateLimiter(ctx, b.cfg.Chat.RateLimit)
|
||||
// setupMemoryEngine must run before setupGatewayChat: setupGatewayChat
|
||||
// constructs the turn runner, which captures b.memEngines at
|
||||
// construction time (see the identical ordering note in main.go's Run).
|
||||
|
||||
@@ -12,13 +12,12 @@ import (
|
||||
|
||||
// setupChatRuntime wires the model runtime, tool registry, persona registry,
|
||||
// chat task creator/controller, default chat identity and the release-update
|
||||
// service. Both the daemon (its own Telegram/email routers) and the standalone
|
||||
// Gateway (the web router) build through this one constructor so the two
|
||||
// processes cannot diverge.
|
||||
// service. The daemon and the standalone Gateway build through this one
|
||||
// constructor so the two processes cannot diverge.
|
||||
func (b *boot) setupChatRuntime(cfg config.Config) {
|
||||
// ── LLM runtime ──────────────────────────────────────────────────
|
||||
// Created before gateways so the LLMResponder can be wired into the
|
||||
// Telegram router for non-command message processing.
|
||||
// Created before the router so the LLMResponder can be wired in for
|
||||
// non-command message processing.
|
||||
providers := executionProviders(cfg)
|
||||
b.llm = agentexec.NewRuntime(providers)
|
||||
b.toolReg = tools.NewRegistry()
|
||||
@@ -44,7 +43,7 @@ func (b *boot) setupChatRuntime(cfg config.Config) {
|
||||
requeue: b.stateStore.Requeue,
|
||||
transition: b.stateStore.Transition,
|
||||
})
|
||||
b.updateService = makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)})
|
||||
b.updateService = makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)})
|
||||
}
|
||||
|
||||
// setupGatewayChat is the sole production constructor of the local contract.
|
||||
@@ -53,20 +52,21 @@ func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor
|
||||
b.setupChatRuntime(b.cfg)
|
||||
cfg := b.cfg
|
||||
router := gateway.NewRouter(b.stateStore, nil, "web")
|
||||
router.Limiter = b.rateLimiter
|
||||
router.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
|
||||
router.Models = b.chatModels
|
||||
router.Personas = b.personas
|
||||
router.Updates = b.updateService
|
||||
router.InitSessions(b.chatSessionStore)
|
||||
configureTaskCommands(router, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.stateStore.Tasks}, b.defaultChatIdentity)
|
||||
setup := telegramSetup{
|
||||
Cfg: config.NewHolder(cfg), St: b.stateStore, LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg,
|
||||
Personas: b.personas, ChatTasks: b.chatTasks, ChatController: b.chatController,
|
||||
setup := chatSetup{
|
||||
Cfg: config.NewHolder(cfg), LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg,
|
||||
Personas: b.personas, ChatTasks: b.chatTasks,
|
||||
ChatTaskLister: chatTaskListerAdapter{tasks: b.stateStore.Tasks},
|
||||
ChatTaskLogs: chatTaskLogReaderAdapter{tasks: b.stateStore.TaskByID, taskLogs: b.taskLogs},
|
||||
ChatTaskActor: actor, ChatPRReviewer: b.prReviewer(),
|
||||
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore,
|
||||
Bus: b.bus, Log: b.log, Secrets: b.secrets,
|
||||
DefaultChatIdentity: b.defaultChatIdentity,
|
||||
Bus: b.bus, Log: b.log,
|
||||
MemoryEngine: b.memoryStore(),
|
||||
MemoryWriter: b.memoryWriter(),
|
||||
}
|
||||
|
||||
@@ -56,9 +56,7 @@ import (
|
||||
const (
|
||||
// defaultChatMaxSteps bounds the model/tool round-trips in one chat
|
||||
// turn when [config.ChatConfig.MaxSteps] is unset.
|
||||
defaultChatMaxSteps = 100
|
||||
packagedGatewayChangelogPath = "/usr/share/archie/CHANGELOG.archied.md"
|
||||
packagedRuntimeChangelogPath = "/usr/share/archie/CHANGELOG.archie.md"
|
||||
defaultChatMaxSteps = 100
|
||||
)
|
||||
|
||||
// Component versions are injected from their independent release tags.
|
||||
@@ -410,19 +408,12 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
|
||||
if err := b.buildTreesAndIdentities(ctx); err != nil {
|
||||
return 1
|
||||
}
|
||||
// setupMemoryEngine must run before setupGateways: setupGateways
|
||||
// constructs every chat turn runner (setupGatewayChat /
|
||||
// setupTelegramGateway), and a turn runner captures b.memEngines at
|
||||
// construction time. Built the other way round, every turn runner would
|
||||
// capture a nil engine and the chat read path
|
||||
// (docs/prds/memory-engine-unification.md §4) would silently never see a
|
||||
// record.
|
||||
// setupMemoryEngine must run before setupCurators: curator.Registrar
|
||||
// captures b.memEngines at construction time, so built the other way
|
||||
// round every curator would hold a nil engine source.
|
||||
if err := b.setupMemoryEngine(); err != nil {
|
||||
return 1
|
||||
}
|
||||
if !b.setupGateways(ctx, args.cfgPath, args.overlayPath) {
|
||||
return 1
|
||||
}
|
||||
|
||||
if err := b.loadWorkflows(ctx); err != nil {
|
||||
return 1
|
||||
@@ -957,18 +948,10 @@ func configHome() string {
|
||||
return filepath.Join(home, ".config")
|
||||
}
|
||||
|
||||
func releaseAnnouncementStatePath(workDir, identity string) string {
|
||||
identityHash := sha256.Sum256([]byte(identity))
|
||||
return filepath.Join(
|
||||
workDir,
|
||||
fmt.Sprintf("release-announcements-%x.json", identityHash[:8]),
|
||||
)
|
||||
}
|
||||
|
||||
// updateReportPath is where the update watchdog leaves the phase-2 outcome
|
||||
// of an update for this identity to relay on its next launch. Hashed the
|
||||
// same way as releaseAnnouncementStatePath so multiple identities sharing
|
||||
// one daemon (see docs/architecture/identity.md) never collide.
|
||||
// of an update for this identity to relay on its next launch. The identity is
|
||||
// hashed so multiple identities sharing one daemon (see
|
||||
// docs/architecture/identity.md) never collide.
|
||||
func updateReportPath(workDir, identity string) string {
|
||||
identityHash := sha256.Sum256([]byte(identity))
|
||||
return filepath.Join(
|
||||
|
||||
@@ -6,6 +6,7 @@ package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -13,7 +14,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
@@ -36,44 +36,33 @@ func (b *boot) setupReadinessProbes() {
|
||||
readiness.NewConfigProbe(b.cfgHolder.Get, configuration.Validate),
|
||||
readiness.NewDiskProbeTargets(diskProbeTargets(cfg)),
|
||||
readiness.NewModelProbe(b.chatModels.ActiveModel, b.chatModels.Models, modelReachProbe(cfg, b.chatModels.ActiveModel)),
|
||||
readiness.NewGatewayProbe(
|
||||
func() []readiness.ChannelState { return channelStates(b.channelManager) },
|
||||
func(ctx context.Context) int { return sessionCount(ctx, b.chat) },
|
||||
),
|
||||
// The daemon no longer runs a chat channel, so it cannot observe one's
|
||||
// lifecycle; channel health is the Messaging Service's own probe. What
|
||||
// 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 {
|
||||
return pingChat(ctx, b.chat)
|
||||
}),
|
||||
}
|
||||
b.healthRegistry = health.NewRegistry(probes...)
|
||||
}
|
||||
|
||||
// channelStates projects a channel lifecycle snapshot into the readiness
|
||||
// probe's view, so the probe does not depend on the channels package's
|
||||
// concrete type.
|
||||
func channelStates(m *status.Manager) []readiness.ChannelState {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
snapshot := m.Snapshot()
|
||||
states := make([]readiness.ChannelState, 0, len(snapshot))
|
||||
for _, s := range snapshot {
|
||||
states = append(states, readiness.ChannelState{
|
||||
ID: s.ID,
|
||||
Configured: s.Configured,
|
||||
State: string(s.State),
|
||||
})
|
||||
}
|
||||
return states
|
||||
}
|
||||
// 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
|
||||
|
||||
// sessionCount returns the number of gateway sessions. An unwired chat
|
||||
// surface returns 0 rather than reporting a false failure.
|
||||
func sessionCount(ctx context.Context, chat *webui.ChatService) int {
|
||||
// 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.
|
||||
func pingChat(ctx context.Context, chat *webui.ChatService) error {
|
||||
if chat == nil || chat.Contract == nil {
|
||||
return 0
|
||||
return errors.New("chat contract not wired")
|
||||
}
|
||||
snapshot, err := chat.Contract.Snapshot(ctx)
|
||||
if err != nil {
|
||||
return 0
|
||||
if _, err := chat.Contract.Snapshot(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return len(snapshot.Sessions)
|
||||
return nil
|
||||
}
|
||||
|
||||
// diskProbeTargets returns the filesystems whose capacity matters to the
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
@@ -32,36 +31,15 @@ func TestDiskProbePath_FallsBackToCwd(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelStates_ProjectsSnapshot(t *testing.T) {
|
||||
m := status.NewManager([]status.Descriptor{
|
||||
{ID: "telegram", Name: "Telegram", Configured: true},
|
||||
{ID: "email", Name: "Email", Configured: false},
|
||||
})
|
||||
m.MarkRunning("telegram")
|
||||
states := channelStates(m)
|
||||
if len(states) != 2 {
|
||||
t.Fatalf("states = %d, want 2", len(states))
|
||||
// TestPingChat_ReportsUnwiredChat pins that a daemon with no Gateway contract
|
||||
// degrades its gateway probe rather than passing it: chat is served entirely
|
||||
// by the Gateway now, so an unwired contract means no chat at all.
|
||||
func TestPingChat_ReportsUnwiredChat(t *testing.T) {
|
||||
if err := pingChat(context.Background(), nil); err == nil {
|
||||
t.Fatal("pingChat(nil chat) = nil, want an error")
|
||||
}
|
||||
if states[0].ID != "telegram" || !states[0].Configured || states[0].State != "running" {
|
||||
t.Fatalf("states[0] = %+v, want telegram running", states[0])
|
||||
}
|
||||
if states[1].ID != "email" || states[1].Configured || states[1].State != "stopped" {
|
||||
t.Fatalf("states[1] = %+v, want email stopped", states[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelStates_NilManager(t *testing.T) {
|
||||
if got := channelStates(nil); got != nil {
|
||||
t.Fatalf("channelStates(nil) = %#v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCount_ToleratesUnwiredChat(t *testing.T) {
|
||||
if got := sessionCount(context.Background(), nil); got != 0 {
|
||||
t.Fatalf("sessionCount(nil chat) = %d, want 0", got)
|
||||
}
|
||||
if got := sessionCount(context.Background(), &webui.ChatService{}); got != 0 {
|
||||
t.Fatalf("sessionCount(unwired Sessions) = %d, want 0", got)
|
||||
if err := pingChat(context.Background(), &webui.ChatService{}); err == nil {
|
||||
t.Fatal("pingChat(unwired contract) = nil, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,9 +70,8 @@ func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
|
||||
}
|
||||
|
||||
b := &boot{
|
||||
st: st,
|
||||
cfgHolder: config.NewHolder(cfg),
|
||||
channelManager: status.NewManager([]status.Descriptor{{ID: "telegram", Name: "Telegram", Configured: true}}),
|
||||
st: st,
|
||||
cfgHolder: config.NewHolder(cfg),
|
||||
chat: &webui.ChatService{
|
||||
Contract: &gateway.LocalChatAdapter{
|
||||
Router: &gateway.Router{},
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
func TestBuildTelegramRouterWiresPersonas(t *testing.T) {
|
||||
personas := gateway.NewPersonaRegistry(gateway.DefaultPersonas())
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
router := buildTelegramRouter(context.Background(), nil, telegramSetup{
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
Personas: personas,
|
||||
SessionStore: sessions,
|
||||
Log: slog.Default(),
|
||||
}, sessions)
|
||||
|
||||
if router.Personas != personas {
|
||||
t.Fatalf("router.Personas = %p, want the configured registry %p", router.Personas, personas)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupTelegramGatewayAcceptsTokenRefWithoutTokenEnv is the regression
|
||||
// guard for channels-telegram-5: wiring Gateway.ValidateConfig into the
|
||||
// startup path without first fixing it to accept a Token secret ref (not
|
||||
// just TokenEnv) would have rejected every deployment configured via
|
||||
// chat.telegram.token, even though resolveTelegramToken already treats
|
||||
// Token as taking precedence over TokenEnv.
|
||||
func TestSetupTelegramGatewayAcceptsTokenRefWithoutTokenEnv(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(telegramTestSecretEngine{})
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
cfg := config.Config{Chat: config.ChatConfig{Telegram: config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
// TokenEnv deliberately left empty.
|
||||
}}}
|
||||
|
||||
start, ok := setupTelegramGateway(context.Background(), telegramSetup{
|
||||
Cfg: config.NewHolder(cfg),
|
||||
Secrets: registry,
|
||||
SessionStore: sessions,
|
||||
Log: slog.Default(),
|
||||
})
|
||||
if !ok {
|
||||
t.Fatal("setupTelegramGateway ok = false, want true: chat.telegram.token alone is a valid credential source")
|
||||
}
|
||||
if start == nil {
|
||||
t.Fatal("setupTelegramGateway start = nil, want a start function")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupTelegramGatewayRejectsMissingCredential is the companion
|
||||
// negative case: with neither token nor token_env resolvable to a
|
||||
// non-empty value, ValidateConfig's wiring must still refuse to start.
|
||||
func TestSetupTelegramGatewayRejectsMissingCredential(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
cfg := config.Config{Chat: config.ChatConfig{Telegram: config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
}}}
|
||||
|
||||
_, ok := setupTelegramGateway(context.Background(), telegramSetup{
|
||||
Cfg: config.NewHolder(cfg),
|
||||
Secrets: registry, // bws engine not registered: resolution fails, token stays empty
|
||||
SessionStore: sessions,
|
||||
Log: slog.Default(),
|
||||
})
|
||||
if ok {
|
||||
t.Fatal("setupTelegramGateway ok = true, want false: token cannot be resolved")
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// TestBuildTelegramRouterLeavesRestartUnwired pins that the Telegram router
|
||||
// never wires Router.Restart, regardless of whether a Telegram adapter is in
|
||||
// scope. Telegram's /restart is served by a dedicated exact-match handler
|
||||
// (registerCommandHandlers → restartHandler), which is the only path that
|
||||
// reaches RequestRestart; the router's own handleRestartAdapter is never
|
||||
// reached on Telegram, so wiring Router.Restart here would be unreachable in
|
||||
// production. It must stay nil and the router's /restart reply must keep
|
||||
// reporting not-configured.
|
||||
func TestBuildTelegramRouterLeavesRestartUnwired(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
tg *telegram.Gateway
|
||||
}{
|
||||
{name: "telegram adapter present", tg: telegram.New("test-token", nil, slog.Default())},
|
||||
{name: "no telegram adapter", tg: nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
router := buildTelegramRouter(ctx, tt.tg, telegramSetup{
|
||||
Cfg: config.NewHolder(config.Config{}),
|
||||
SessionStore: sessions,
|
||||
Log: slog.Default(),
|
||||
}, sessions)
|
||||
|
||||
if router.Restart != nil {
|
||||
t.Fatalf("router.Restart = %T, want nil: Telegram /restart is served by restartHandler, not this router", router.Restart)
|
||||
}
|
||||
|
||||
reply, err := router.Route(ctx, gateway.Inbound{Message: messaging.Message{
|
||||
Role: messaging.RoleUser,
|
||||
Text: "/restart",
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("Route(/restart) error = %v", err)
|
||||
}
|
||||
if reply != "Chat adapter restart is not configured." {
|
||||
t.Fatalf("Route(/restart) = %q, want %q", reply, "Chat adapter restart is not configured.")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/channels/email"
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/channels/webhook"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
type deps struct {
|
||||
Config ResolvedConfig
|
||||
Log *slog.Logger
|
||||
Chat messaging.ChatContract
|
||||
Health *health.Registry
|
||||
}
|
||||
|
||||
type channelInstance struct {
|
||||
name string
|
||||
channel channels.Channel
|
||||
}
|
||||
|
||||
// Service manages the lifecycle of the extracted Messaging Service and its
|
||||
// channel adapters.
|
||||
type Service struct {
|
||||
cfg ResolvedConfig
|
||||
log *slog.Logger
|
||||
chat messaging.ChatContract
|
||||
health *health.Registry
|
||||
channels []channelInstance
|
||||
|
||||
mu sync.Mutex
|
||||
running bool
|
||||
stop func()
|
||||
}
|
||||
|
||||
// compose builds the Service from resolved configuration. ctx is the service
|
||||
// lifetime: seams a channel invokes later (the Gateway version lookup) derive
|
||||
// their calls from it, so a shutdown cancels them. A channel whose
|
||||
// configuration is present but invalid fails composition rather than being
|
||||
// dropped: a front-end the operator configured must never silently not run.
|
||||
func compose(ctx context.Context, d deps) (*Service, error) {
|
||||
srv := &Service{
|
||||
cfg: d.Config,
|
||||
log: d.Log,
|
||||
chat: d.Chat,
|
||||
health: d.Health,
|
||||
}
|
||||
|
||||
if d.Config.TelegramToken != "" {
|
||||
if len(d.Config.Telegram.AllowedUserIDs) == 0 {
|
||||
d.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " +
|
||||
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
|
||||
}
|
||||
tg := telegram.New(d.Config.TelegramToken, d.Config.Telegram.AllowedUserIDs, d.Log)
|
||||
configureTelegram(ctx, tg, d.Config, d.Chat, d.Log)
|
||||
if err := srv.add("telegram", tg, telegramValidateConfigMap(d.Config.Telegram)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if d.Config.Email.ListenAddr != "" {
|
||||
em := email.New(d.Config.Email.ListenAddr, d.Config.Email.RelayAddr, d.Log)
|
||||
if err := srv.add("email", em, map[string]any{
|
||||
"listen_addr": d.Config.Email.ListenAddr,
|
||||
"relay_addr": d.Config.Email.RelayAddr,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if d.Config.WebhookAddr != "" {
|
||||
host, port := parseListenAddr(d.Config.WebhookAddr, "0.0.0.0", 8644)
|
||||
wh := webhook.New(host, port, webhookRoutes(d.Config.Webhook, d.Config.WebhookSecret), d.Log)
|
||||
if err := srv.add("webhook", wh, map[string]any{"host": host, "port": port}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return srv, nil
|
||||
}
|
||||
|
||||
// add validates a channel against its own ConfigSchema contract and
|
||||
// registers it.
|
||||
func (s *Service) add(name string, ch channels.Channel, cfg map[string]any) error {
|
||||
if err := ch.ValidateConfig(cfg); err != nil {
|
||||
return fmt.Errorf("chat.%s config invalid: %w", name, err)
|
||||
}
|
||||
s.channels = append(s.channels, channelInstance{name: name, channel: ch})
|
||||
return nil
|
||||
}
|
||||
|
||||
// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects
|
||||
// from the typed config, carrying whichever credential source is set
|
||||
// (token takes precedence, matching resolveTelegramToken).
|
||||
func telegramValidateConfigMap(cfg config.TelegramConfig) map[string]any {
|
||||
m := map[string]any{"token_env": cfg.TokenEnv}
|
||||
if cfg.Token != (secret.SecretRef{}) {
|
||||
m["token"] = map[string]any{"engine": cfg.Token.Engine, "key": cfg.Token.Key}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func webhookRoutes(route config.WebhookRoute, secretValue string) []webhook.RouteConfig {
|
||||
path := route.Path
|
||||
if path == "" {
|
||||
path = "/webhook"
|
||||
}
|
||||
return []webhook.RouteConfig{{
|
||||
Path: path,
|
||||
Secret: secretValue,
|
||||
Template: route.Template,
|
||||
DeliverTo: route.DeliverTo,
|
||||
}}
|
||||
}
|
||||
|
||||
func parseListenAddr(addr, defaultHost string, defaultPort int) (string, int) {
|
||||
if addr == "" {
|
||||
return defaultHost, defaultPort
|
||||
}
|
||||
host, portStr, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return defaultHost, defaultPort
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil {
|
||||
return defaultHost, defaultPort
|
||||
}
|
||||
return host, port
|
||||
}
|
||||
|
||||
// Start launches the configured messaging channels.
|
||||
func (s *Service) Start(ctx context.Context) error {
|
||||
s.mu.Lock()
|
||||
if s.running {
|
||||
s.mu.Unlock()
|
||||
return fmt.Errorf("messaging service is already running")
|
||||
}
|
||||
s.running = true
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
s.stop = cancel
|
||||
s.mu.Unlock()
|
||||
|
||||
s.log.Info("messaging service started", "gateway_target", s.cfg.Options.Gateway.Target, "channels", len(s.channels))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for _, ch := range s.channels {
|
||||
c := ch
|
||||
wg.Go(func() {
|
||||
s.log.Info("starting channel", "name", c.name)
|
||||
if err := c.channel.Start(ctx, s.chat, channels.Lifecycle{}); err != nil && ctx.Err() == nil {
|
||||
s.log.Error("channel stopped with error", "name", c.name, "err", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
<-ctx.Done()
|
||||
|
||||
for _, ch := range s.channels {
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.WithoutCancel(ctx), s.cfg.Options.ShutdownTimeout)
|
||||
if err := ch.channel.Stop(shutdownCtx); err != nil {
|
||||
s.log.Warn("channel stop failed", "name", ch.name, "err", err)
|
||||
}
|
||||
shutdownCancel()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop stops the messaging service and its channels.
|
||||
func (s *Service) Stop() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !s.running {
|
||||
return
|
||||
}
|
||||
s.running = false
|
||||
if s.stop != nil {
|
||||
s.stop()
|
||||
}
|
||||
s.log.Info("messaging service stopped")
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// ResolvedConfig contains the resolved inputs needed by the Messaging Service.
|
||||
type ResolvedConfig struct {
|
||||
Options Options
|
||||
TelegramToken string
|
||||
Telegram config.TelegramConfig
|
||||
Email config.EmailConfig
|
||||
Webhook config.WebhookRoute
|
||||
WebhookSecret string
|
||||
WebhookAddr string
|
||||
// WorkDir, BotUser and HealthURL are not channel transport settings. They
|
||||
// locate this identity's release-announcement and update-report state
|
||||
// files, and give the update installer the daemon health endpoint to poll
|
||||
// after it applies one (docs/architecture/migration-decisions.md, "Telegram
|
||||
// operator surface after extraction").
|
||||
WorkDir string
|
||||
BotUser string
|
||||
HealthURL string
|
||||
ShowToolCalls bool
|
||||
}
|
||||
|
||||
type projection struct {
|
||||
gateway ServiceTarget
|
||||
telegram config.TelegramConfig
|
||||
email config.EmailConfig
|
||||
webhook config.WebhookRoute
|
||||
webhookAddr string
|
||||
workDir string
|
||||
botUser string
|
||||
healthURL string
|
||||
showToolCalls bool
|
||||
}
|
||||
|
||||
// Resolve loads the configuration, extracts the messaging projection, resolves
|
||||
// credentials, and applies defaults.
|
||||
func Resolve(o Options, log *slog.Logger) (ResolvedConfig, error) {
|
||||
var proj projection
|
||||
if o.Config != "" {
|
||||
p, found, err := readProjection(o.Config, o.Overlay, log)
|
||||
if err != nil {
|
||||
return ResolvedConfig{}, err
|
||||
}
|
||||
if found {
|
||||
proj = p
|
||||
o = merge(o, proj)
|
||||
}
|
||||
}
|
||||
o = withDefaults(o)
|
||||
o = withEnvTokens(o)
|
||||
if err := o.validate(); err != nil {
|
||||
return ResolvedConfig{}, err
|
||||
}
|
||||
|
||||
secrets := secret.NewRegistry()
|
||||
tgToken, err := resolveTelegramToken(proj.telegram, secrets)
|
||||
if err != nil {
|
||||
return ResolvedConfig{}, fmt.Errorf("resolve telegram token: %w", err)
|
||||
}
|
||||
|
||||
// An unresolvable webhook secret is not fatal: the route still serves,
|
||||
// with signature validation off, which is what it did before a secret
|
||||
// was ever configurable. It is logged so the degradation is visible.
|
||||
whSecret, err := resolveWebhookSecret(proj.webhook, secrets)
|
||||
if err != nil {
|
||||
log.Error("webhook secret unresolvable; starting with signature validation disabled",
|
||||
"engine", proj.webhook.Secret.Engine, "key", proj.webhook.Secret.Key, "err", err)
|
||||
}
|
||||
|
||||
return ResolvedConfig{
|
||||
Options: o,
|
||||
TelegramToken: tgToken,
|
||||
Telegram: proj.telegram,
|
||||
Email: proj.email,
|
||||
Webhook: proj.webhook,
|
||||
WebhookSecret: whSecret,
|
||||
WebhookAddr: proj.webhookAddr,
|
||||
WorkDir: proj.workDir,
|
||||
BotUser: proj.botUser,
|
||||
HealthURL: proj.healthURL,
|
||||
ShowToolCalls: proj.showToolCalls,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func readProjection(path, overlay string, log *slog.Logger) (projection, bool, error) {
|
||||
if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) {
|
||||
return projection{}, false, nil
|
||||
}
|
||||
doc, err := configuration.New(log).Resolve(path, overlay)
|
||||
if err != nil {
|
||||
return projection{}, false, fmt.Errorf("read messaging configuration: %w", err)
|
||||
}
|
||||
return project(doc.Config), true, nil
|
||||
}
|
||||
|
||||
func project(cfg config.Config) projection {
|
||||
return projection{
|
||||
gateway: ServiceTarget{
|
||||
Target: cfg.Services.Get(config.ServiceNameGateway).Target,
|
||||
Token: cfg.Services.Get(config.ServiceNameGateway).TargetToken,
|
||||
},
|
||||
telegram: cfg.Chat.Telegram,
|
||||
email: cfg.Chat.Email,
|
||||
webhook: cfg.Chat.Webhook,
|
||||
webhookAddr: cfg.Chat.WebhookAddr,
|
||||
workDir: cfg.WorkDir,
|
||||
botUser: cfg.BotUser,
|
||||
healthURL: cfg.Health.URL(),
|
||||
showToolCalls: cfg.Chat.ShowToolCalls,
|
||||
}
|
||||
}
|
||||
|
||||
func withEnvTokens(o Options) Options {
|
||||
if o.Gateway.Token == "" {
|
||||
o.Gateway.Token = os.Getenv("GATEWAY_TOKEN")
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func merge(o Options, p projection) Options {
|
||||
if o.Gateway.Target == "" {
|
||||
o.Gateway.Target = p.gateway.Target
|
||||
}
|
||||
if o.Gateway.Token == "" {
|
||||
o.Gateway.Token = p.gateway.Token
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
// resolveTelegramToken reads whichever credential source is configured. A
|
||||
// secret ref takes precedence over token_env, so a deployment that moved to
|
||||
// a secret engine is not silently served by a stale environment variable.
|
||||
func resolveTelegramToken(cfg config.TelegramConfig, secrets *secret.Registry) (string, error) {
|
||||
if cfg.Token != (secret.SecretRef{}) {
|
||||
return secrets.Resolve(cfg.Token)
|
||||
}
|
||||
if cfg.TokenEnv != "" {
|
||||
return os.Getenv(cfg.TokenEnv), nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func resolveWebhookSecret(route config.WebhookRoute, secrets *secret.Registry) (string, error) {
|
||||
if route.Secret != (secret.SecretRef{}) {
|
||||
return secrets.Resolve(route.Secret)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestOptionsDefaultsAndValidation(t *testing.T) {
|
||||
opts := withDefaults(Options{})
|
||||
if opts.Gateway.Target != defaultGatewayTarget {
|
||||
t.Errorf("Gateway.Target = %q, want %q", opts.Gateway.Target, defaultGatewayTarget)
|
||||
}
|
||||
if opts.DependencyTimeout != defaultDependencyTimeout {
|
||||
t.Errorf("DependencyTimeout = %v, want %v", opts.DependencyTimeout, defaultDependencyTimeout)
|
||||
}
|
||||
if err := opts.validate(); err != nil {
|
||||
t.Errorf("validate default loopback options: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionsNonLoopbackRequiresToken(t *testing.T) {
|
||||
opts := Options{
|
||||
Gateway: ServiceTarget{Target: "192.168.1.50:8585"},
|
||||
}
|
||||
opts = withDefaults(opts)
|
||||
if err := opts.validate(); err == nil {
|
||||
t.Error("validate non-loopback gateway target with empty token want error, got nil")
|
||||
}
|
||||
|
||||
opts.Gateway.Token = "secret"
|
||||
if err := opts.validate(); err != nil {
|
||||
t.Errorf("validate non-loopback gateway target with token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWithConfigFile(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
cfgPath := filepath.Join(tmp, "config.toml")
|
||||
content := `
|
||||
bot_user = "testbot"
|
||||
|
||||
[services.gateway]
|
||||
target = "127.0.0.1:8999"
|
||||
target_token = "tok-123"
|
||||
|
||||
[chat.telegram]
|
||||
token_env = "TEST_TG_TOKEN"
|
||||
allowed_user_ids = [12345]
|
||||
`
|
||||
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("TEST_TG_TOKEN", "resolved-tg-token")
|
||||
|
||||
resolved, err := Resolve(Options{Config: cfgPath}, slog.Default())
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
|
||||
if resolved.Options.Gateway.Target != "127.0.0.1:8999" {
|
||||
t.Errorf("Gateway.Target = %q, want 127.0.0.1:8999", resolved.Options.Gateway.Target)
|
||||
}
|
||||
if resolved.TelegramToken != "resolved-tg-token" {
|
||||
t.Errorf("TelegramToken = %q, want resolved-tg-token", resolved.TelegramToken)
|
||||
}
|
||||
if len(resolved.Telegram.AllowedUserIDs) != 1 || resolved.Telegram.AllowedUserIDs[0] != 12345 {
|
||||
t.Errorf("AllowedUserIDs = %v, want [12345]", resolved.Telegram.AllowedUserIDs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceStartAndStop(t *testing.T) {
|
||||
d := deps{
|
||||
Config: ResolvedConfig{
|
||||
Options: withDefaults(Options{}),
|
||||
},
|
||||
Log: slog.Default(),
|
||||
}
|
||||
srv, err := compose(t.Context(), d)
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := contextWithTimeout(t, 200*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- srv.Start(ctx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
t.Fatalf("srv.Start: %v", err)
|
||||
}
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("srv.Start timed out waiting for context cancel")
|
||||
}
|
||||
|
||||
srv.Stop()
|
||||
}
|
||||
|
||||
func contextWithTimeout(t *testing.T, d time.Duration) (context.Context, context.CancelFunc) {
|
||||
t.Helper()
|
||||
return context.WithTimeout(context.Background(), d)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// Package archiemessaging composes the standalone Messaging Service: the external
|
||||
// channel connections (Telegram, email, webhook) served against a Gateway running
|
||||
// over its gRPC contract.
|
||||
//
|
||||
// docs/prds/messaging-service-boundary.md is the authority. The Messaging Service
|
||||
// owns channel persistent connections and dispatches turns directly to Gateway's
|
||||
// ChatContract over gRPC.
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Process defaults.
|
||||
const (
|
||||
defaultGatewayTarget = "127.0.0.1:8585"
|
||||
defaultDependencyTimeout = 5 * time.Second
|
||||
defaultShutdownTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// ServiceTarget is one remote contract's endpoint and the service-to-service
|
||||
// bearer token this process presents to it.
|
||||
type ServiceTarget struct {
|
||||
Target string
|
||||
Token string
|
||||
}
|
||||
|
||||
// Options contains the process inputs for the Messaging Service.
|
||||
type Options struct {
|
||||
Config string
|
||||
Overlay string
|
||||
|
||||
Gateway ServiceTarget
|
||||
DependencyTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
func withDefaults(o Options) Options {
|
||||
if o.Gateway.Target == "" {
|
||||
o.Gateway.Target = defaultGatewayTarget
|
||||
}
|
||||
if o.DependencyTimeout <= 0 {
|
||||
o.DependencyTimeout = defaultDependencyTimeout
|
||||
}
|
||||
if o.ShutdownTimeout <= 0 {
|
||||
o.ShutdownTimeout = defaultShutdownTimeout
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (o Options) validate() error {
|
||||
if o.Gateway.Target == "" {
|
||||
return errors.New("gateway target is required (pass -gateway-target or configure [services.gateway].target)")
|
||||
}
|
||||
if err := validateServiceTarget("gateway", o.Gateway); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateServiceTarget(serviceName string, target ServiceTarget) error {
|
||||
host, _, err := net.SplitHostPort(target.Target)
|
||||
if err != nil {
|
||||
host = target.Target
|
||||
}
|
||||
if isLoopback(host) {
|
||||
return nil
|
||||
}
|
||||
if target.Token == "" {
|
||||
return fmt.Errorf("%s target %q is non-loopback and requires a bearer token", serviceName, target.Target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isLoopback(host string) bool {
|
||||
if host == "localhost" {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(host, "[]"))
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/readiness"
|
||||
)
|
||||
|
||||
// newReadinessRegistry builds the health registry for the Messaging Service.
|
||||
// Messaging is ready when the Gateway Service responds to Snapshot within
|
||||
// the dependency timeout.
|
||||
func newReadinessRegistry(o Options, chat messaging.ChatContract) *health.Registry {
|
||||
return health.NewRegistry(
|
||||
readiness.NewContractProbe("gateway", o.DependencyTimeout, func(ctx context.Context) error {
|
||||
_, err := chat.Snapshot(ctx)
|
||||
return err
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
)
|
||||
|
||||
// Run runs the standalone Messaging Service process until ctx is cancelled.
|
||||
func Run(ctx context.Context, o Options) error {
|
||||
log := slog.Default().With("service", "archie-messaging")
|
||||
|
||||
cfg, err := Resolve(o, log)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve messaging options: %w", err)
|
||||
}
|
||||
|
||||
chat, closeGateway, err := gatewayrpc.Dial(cfg.Options.Gateway.Target, cfg.Options.Gateway.Token)
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial gateway (%s): %w", cfg.Options.Gateway.Target, err)
|
||||
}
|
||||
defer closeGateway()
|
||||
|
||||
health := newReadinessRegistry(cfg.Options, chat)
|
||||
|
||||
srv, err := compose(ctx, deps{
|
||||
Config: cfg,
|
||||
Log: log,
|
||||
Chat: chat,
|
||||
Health: health,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return srv.Start(ctx)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type dummyChatContract struct {
|
||||
messaging.ChatContract
|
||||
}
|
||||
|
||||
func TestServiceStartsConfiguredChannels(t *testing.T) {
|
||||
d := deps{
|
||||
Config: ResolvedConfig{
|
||||
TelegramToken: "token-123",
|
||||
Telegram: config.TelegramConfig{
|
||||
TokenEnv: "TEST_TG_TOKEN",
|
||||
AllowedUserIDs: []int64{123},
|
||||
},
|
||||
Email: config.EmailConfig{
|
||||
ListenAddr: "127.0.0.1:0",
|
||||
},
|
||||
WebhookAddr: "127.0.0.1:0",
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &dummyChatContract{},
|
||||
}
|
||||
|
||||
srv, err := compose(t.Context(), d)
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
if len(srv.channels) != 3 {
|
||||
t.Fatalf("len(srv.channels) = %d, want 3", len(srv.channels))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- srv.Start(ctx)
|
||||
}()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
srv.Stop()
|
||||
|
||||
select {
|
||||
case startErr := <-errCh:
|
||||
if startErr != nil {
|
||||
t.Fatalf("srv.Start error: %v", startErr)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("srv.Start did not exit after Stop")
|
||||
}
|
||||
}
|
||||
|
||||
// TestComposeRejectsInvalidChannelConfig pins that a configured front-end
|
||||
// whose own ValidateConfig refuses the config fails composition. Dropping it
|
||||
// instead would leave the operator with a service that starts cleanly and
|
||||
// answers nothing on that channel.
|
||||
func TestComposeRejectsInvalidChannelConfig(t *testing.T) {
|
||||
_, err := compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
Email: config.EmailConfig{ListenAddr: "127.0.0.1:0"},
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &dummyChatContract{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("compose with a valid email listen addr: %v", err)
|
||||
}
|
||||
|
||||
_, err = compose(t.Context(), deps{
|
||||
Config: ResolvedConfig{
|
||||
TelegramToken: "token-123",
|
||||
// Neither token_env nor a token ref: telegram.ValidateConfig refuses.
|
||||
},
|
||||
Log: slog.Default(),
|
||||
Chat: &dummyChatContract{},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("compose error = nil, want an error: telegram has no configured credential source")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
// configureTelegram wires the operator seams telegram.Gateway leaves to its
|
||||
// composition root. Which process may satisfy each one is settled in
|
||||
// docs/architecture/migration-decisions.md ("Telegram operator surface after
|
||||
// extraction"); notably RunningVersions, ReleaseAnnouncements and Dangerous
|
||||
// stay nil deliberately, because nothing this process can observe would make
|
||||
// them true.
|
||||
func configureTelegram(ctx context.Context, g *telegram.Gateway, cfg ResolvedConfig, chat messaging.ChatContract, log *slog.Logger) {
|
||||
g.Version = gatewayVersionReporter(ctx, chat, cfg.Options.DependencyTimeout)
|
||||
g.SetShowToolCalls(cfg.ShowToolCalls)
|
||||
g.Reload = telegramReloader(cfg.Options, log)
|
||||
|
||||
if updates := updateService(cfg); updates != nil {
|
||||
g.Updates = updates
|
||||
}
|
||||
if cfg.WorkDir != "" {
|
||||
g.UpdateReportPath = identityStatePath(cfg.WorkDir, "update-report", cfg.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
// gatewayVersionReporter renders /version from the Gateway's own build block.
|
||||
// It is read per call rather than captured at compose so an upgraded Gateway
|
||||
// is reported without restarting this process, and bounded by the same
|
||||
// dependency timeout the readiness probe uses so a hung Gateway answers the
|
||||
// command instead of leaving the operator with no reply at all. The service
|
||||
// context bounds it too, so a shutdown does not wait on an in-flight call.
|
||||
func gatewayVersionReporter(ctx context.Context, chat messaging.ChatContract, timeout time.Duration) func() string {
|
||||
return func() string {
|
||||
callCtx := ctx
|
||||
if timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
callCtx, cancel = context.WithTimeout(callCtx, timeout)
|
||||
defer cancel()
|
||||
}
|
||||
snapshot, err := chat.Snapshot(callCtx)
|
||||
if err != nil {
|
||||
return "Version information is unavailable: the Gateway could not be reached."
|
||||
}
|
||||
if snapshot.Version == "" {
|
||||
return "Version information is unavailable: the Gateway reported no build."
|
||||
}
|
||||
return snapshot.Version
|
||||
}
|
||||
}
|
||||
|
||||
// updateService builds /update from this service's own [chat.telegram]
|
||||
// commands, or nil when none is configured, which leaves the channel reporting
|
||||
// the command as unconfigured.
|
||||
//
|
||||
// Enrich is deliberately unset: the daemon filled it from [nats], which this
|
||||
// service must not decode, so the check command's own reported install type
|
||||
// stands.
|
||||
func updateService(cfg ResolvedConfig) *releaseupdate.Service {
|
||||
if len(cfg.Telegram.UpdateCheckCommand) == 0 {
|
||||
return nil
|
||||
}
|
||||
updates := &releaseupdate.Service{
|
||||
Catalog: releaseupdate.CommandCatalog{Command: cfg.Telegram.UpdateCheckCommand},
|
||||
StatePath: filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"),
|
||||
InstallType: installtype.Type(),
|
||||
}
|
||||
if len(cfg.Telegram.UpdateInstallCommand) != 0 {
|
||||
updates.Installer = releaseupdate.CommandInstaller{
|
||||
Command: cfg.Telegram.UpdateInstallCommand,
|
||||
HealthURL: cfg.HealthURL,
|
||||
}
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
// telegramReloader re-resolves the token and allowlist from this service's own
|
||||
// configuration on /restart. A reload that cannot produce a token is refused so
|
||||
// the running bot keeps the credential it is already authenticated with.
|
||||
func telegramReloader(o Options, log *slog.Logger) func(*telegram.Gateway) error {
|
||||
return func(g *telegram.Gateway) error {
|
||||
reloaded, err := Resolve(o, log)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reload config: %w", err)
|
||||
}
|
||||
if reloaded.TelegramToken == "" {
|
||||
return fmt.Errorf("reload config: chat.telegram token is empty")
|
||||
}
|
||||
g.Token = reloaded.TelegramToken
|
||||
g.AllowedUserIDs = reloaded.Telegram.AllowedUserIDs
|
||||
g.SetShowToolCalls(reloaded.ShowToolCalls)
|
||||
log.Info("telegram config reloaded",
|
||||
"allowed_user_ids", len(g.AllowedUserIDs),
|
||||
"show_tool_calls", g.ShowToolCalls())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// identityStatePath names a per-identity state file under workDir. The identity
|
||||
// is hashed so several identities sharing one work directory (see
|
||||
// docs/architecture/identity.md) never collide. The scheme is the daemon's,
|
||||
// unchanged: a different path would replay every release announcement the
|
||||
// operator has already been shown.
|
||||
func identityStatePath(workDir, kind, identity string) string {
|
||||
identityHash := sha256.Sum256([]byte(identity))
|
||||
return filepath.Join(workDir, fmt.Sprintf("%s-%x.json", kind, identityHash[:8]))
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type versionChatContract struct {
|
||||
messaging.ChatContract
|
||||
version string
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (c *versionChatContract) Snapshot(context.Context) (messaging.ChatSnapshot, error) {
|
||||
c.calls++
|
||||
return messaging.ChatSnapshot{Version: c.version}, c.err
|
||||
}
|
||||
|
||||
func telegramChannel(t *testing.T, srv *Service) *telegram.Gateway {
|
||||
t.Helper()
|
||||
for _, instance := range srv.channels {
|
||||
if instance.name == "telegram" {
|
||||
gateway, ok := instance.channel.(*telegram.Gateway)
|
||||
if !ok {
|
||||
t.Fatalf("telegram channel is %T, want *telegram.Gateway", instance.channel)
|
||||
}
|
||||
return gateway
|
||||
}
|
||||
}
|
||||
t.Fatal("no telegram channel was composed")
|
||||
return nil
|
||||
}
|
||||
|
||||
func telegramConfig(t *testing.T, cfg ResolvedConfig, chat messaging.ChatContract) *telegram.Gateway {
|
||||
t.Helper()
|
||||
cfg.TelegramToken = "token-123"
|
||||
cfg.Telegram.TokenEnv = "TEST_TG_TOKEN"
|
||||
cfg.Telegram.AllowedUserIDs = []int64{7}
|
||||
srv, err := compose(t.Context(), deps{Config: cfg, Log: slog.New(slog.DiscardHandler), Chat: chat})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
return telegramChannel(t, srv)
|
||||
}
|
||||
|
||||
// TestTelegramVersionComesFromTheGateway pins that /version renders the
|
||||
// Gateway's own build block. The Messaging Service takes no version ldflags
|
||||
// (see docs/architecture/migration-decisions.md), so anything it reported from
|
||||
// its own process would be a guess that hides a partial upgrade.
|
||||
func TestTelegramVersionComesFromTheGateway(t *testing.T) {
|
||||
chat := &versionChatContract{version: "Archie\nGateway: 1.2.3\nRuntime: 4.5.6"}
|
||||
gateway := telegramConfig(t, ResolvedConfig{}, chat)
|
||||
|
||||
if gateway.Version == nil {
|
||||
t.Fatal("telegram Version = nil, want a version function")
|
||||
}
|
||||
if got := gateway.Version(); got != chat.version {
|
||||
t.Fatalf("Version() = %q, want %q", got, chat.version)
|
||||
}
|
||||
if chat.calls != 1 {
|
||||
t.Fatalf("Snapshot calls = %d, want 1: the version is read per call, not cached at compose", chat.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramVersionReportsAnUnreachableGateway pins that a Gateway that
|
||||
// cannot be reached is said so rather than rendered as an empty version block,
|
||||
// which reads as "no components installed".
|
||||
func TestTelegramVersionReportsAnUnreachableGateway(t *testing.T) {
|
||||
chat := &versionChatContract{err: context.DeadlineExceeded}
|
||||
gateway := telegramConfig(t, ResolvedConfig{}, chat)
|
||||
|
||||
got := gateway.Version()
|
||||
if got == "" || !strings.Contains(strings.ToLower(got), "unavailable") {
|
||||
t.Fatalf("Version() = %q, want an unavailable message", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramRunningVersionsStaysUnwired pins the decision recorded in
|
||||
// docs/architecture/migration-decisions.md: RunningVersions turns an
|
||||
// installer's claim into a checked one, and only a component's own compiled-in
|
||||
// build can vouch for itself. This process knows neither archied's build nor
|
||||
// the observed archie-agent version, so reporting anything here would
|
||||
// manufacture the false success the check exists to catch.
|
||||
func TestTelegramRunningVersionsStaysUnwired(t *testing.T) {
|
||||
gateway := telegramConfig(t, ResolvedConfig{}, &versionChatContract{})
|
||||
|
||||
if gateway.RunningVersions != nil {
|
||||
t.Fatal("telegram RunningVersions is wired; update reports must stay unverified claims")
|
||||
}
|
||||
if gateway.Dangerous != nil {
|
||||
t.Fatal("telegram Dangerous is wired; no composition has ever supplied a command authority")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramUpdateServiceIsBuiltFromChannelConfig pins that /update survives
|
||||
// the extraction: the check and install commands are [chat.telegram] config,
|
||||
// which this service owns.
|
||||
func TestTelegramUpdateServiceIsBuiltFromChannelConfig(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
cfg := ResolvedConfig{
|
||||
WorkDir: workDir,
|
||||
Telegram: config.TelegramConfig{
|
||||
UpdateCheckCommand: []string{"archie-update", "check"},
|
||||
UpdateInstallCommand: []string{"archie-update", "install"},
|
||||
},
|
||||
}
|
||||
gateway := telegramConfig(t, cfg, &versionChatContract{})
|
||||
|
||||
if gateway.Updates == nil {
|
||||
t.Fatal("telegram Updates = nil, want the update service")
|
||||
}
|
||||
if !gateway.Updates.CanInstall() {
|
||||
t.Fatal("Updates.CanInstall() = false, want true: an install command is configured")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramUpdateServiceOmittedWithoutACheckCommand pins that an operator
|
||||
// who configured no update command gets the gateway's "not configured" reply
|
||||
// rather than a service that shells out to nothing.
|
||||
func TestTelegramUpdateServiceOmittedWithoutACheckCommand(t *testing.T) {
|
||||
gateway := telegramConfig(t, ResolvedConfig{WorkDir: t.TempDir()}, &versionChatContract{})
|
||||
|
||||
if gateway.Updates != nil {
|
||||
t.Fatalf("telegram Updates = %T, want nil without an update_check_command", gateway.Updates)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramStatePathsKeepTheDaemonHashScheme pins that the update-report
|
||||
// file is the same one the daemon wrote before the extraction. A different path
|
||||
// silently stops relaying the watchdog's verdict on the last update.
|
||||
//
|
||||
// ReleaseAnnouncements stays nil: see the decision table in
|
||||
// docs/architecture/migration-decisions.md.
|
||||
func TestTelegramStatePathsKeepTheDaemonHashScheme(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
cfg := ResolvedConfig{WorkDir: workDir, BotUser: "archie-bot"}
|
||||
gateway := telegramConfig(t, cfg, &versionChatContract{})
|
||||
|
||||
// sha256("archie-bot")[:8], the scheme internal/app/archied used.
|
||||
const wantSuffix = "update-report-95db552fa3a1e0be.json"
|
||||
if got := gateway.UpdateReportPath; got != filepath.Join(workDir, wantSuffix) {
|
||||
t.Fatalf("UpdateReportPath = %q, want %q", got, filepath.Join(workDir, wantSuffix))
|
||||
}
|
||||
if gateway.ReleaseAnnouncements != nil {
|
||||
t.Fatal("telegram ReleaseAnnouncements is wired; without trustworthy component versions the announcer is a no-op that reads as configured")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramShowToolCallsIsProjected pins that [chat].show_tool_calls reaches
|
||||
// the channel; it is read per reply, so an unset projection silently turns tool
|
||||
// visibility off for every deployment that asked for it.
|
||||
func TestTelegramShowToolCallsIsProjected(t *testing.T) {
|
||||
gateway := telegramConfig(t, ResolvedConfig{ShowToolCalls: true}, &versionChatContract{})
|
||||
|
||||
if !gateway.ShowToolCalls() {
|
||||
t.Fatal("ShowToolCalls() = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramReloadRereadsTokenAndAllowlist pins that /restart picks up a
|
||||
// changed allowlist from this service's own config file. Reload was never a
|
||||
// daemon fact: the file it re-reads is the one this process was started with.
|
||||
func TestTelegramReloadRereadsTokenAndAllowlist(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
write := func(userIDs string) {
|
||||
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = " + userIDs + "\n"
|
||||
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("[1]")
|
||||
t.Setenv("TEST_TG_TOKEN", "first-token")
|
||||
|
||||
resolved, err := Resolve(Options{Config: cfgPath}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
srv, err := compose(t.Context(), deps{Config: resolved, Log: slog.New(slog.DiscardHandler), Chat: &versionChatContract{}})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
gateway := telegramChannel(t, srv)
|
||||
if gateway.Reload == nil {
|
||||
t.Fatal("telegram Reload = nil, want a reload function")
|
||||
}
|
||||
|
||||
write("[1, 2]")
|
||||
t.Setenv("TEST_TG_TOKEN", "second-token")
|
||||
if err := gateway.Reload(gateway); err != nil {
|
||||
t.Fatalf("Reload: %v", err)
|
||||
}
|
||||
if len(gateway.AllowedUserIDs) != 2 {
|
||||
t.Fatalf("AllowedUserIDs = %v, want two entries after reload", gateway.AllowedUserIDs)
|
||||
}
|
||||
if gateway.Token != "second-token" {
|
||||
t.Fatalf("Token = %q, want second-token", gateway.Token)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTelegramReloadRefusesAnEmptyToken pins that a config edit which loses the
|
||||
// credential leaves the running bot on its working token rather than silently
|
||||
// authenticating as nobody.
|
||||
func TestTelegramReloadRefusesAnEmptyToken(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "config.toml")
|
||||
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = [1]\n"
|
||||
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("TEST_TG_TOKEN", "first-token")
|
||||
|
||||
resolved, err := Resolve(Options{Config: cfgPath}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
srv, err := compose(t.Context(), deps{Config: resolved, Log: slog.New(slog.DiscardHandler), Chat: &versionChatContract{}})
|
||||
if err != nil {
|
||||
t.Fatalf("compose: %v", err)
|
||||
}
|
||||
gateway := telegramChannel(t, srv)
|
||||
|
||||
t.Setenv("TEST_TG_TOKEN", "")
|
||||
if err := gateway.Reload(gateway); err == nil {
|
||||
t.Fatal("Reload error = nil, want an error when the token resolves empty")
|
||||
}
|
||||
if gateway.Token != "first-token" {
|
||||
t.Fatalf("Token = %q, want the pre-reload token to survive a refused reload", gateway.Token)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
type testSecretEngine struct{}
|
||||
|
||||
func (testSecretEngine) Name() string { return "bws" }
|
||||
func (testSecretEngine) Version() string { return "test" }
|
||||
func (testSecretEngine) Resolve(key string) (string, error) {
|
||||
if key == "telegram-token" {
|
||||
return "token-from-bws", nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenPrefersSecretRef(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(testSecretEngine{})
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
|
||||
}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got != "token-from-bws" {
|
||||
t.Fatalf("resolveTelegramToken = %q, want token-from-bws", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenFallsBackToTokenEnv(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
cfg := config.TelegramConfig{TokenEnv: "TELEGRAM_LEGACY_TOKEN"}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got != "token-from-env" {
|
||||
t.Fatalf("resolveTelegramToken = %q, want token-from-env", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenDoesNotUseTokenEnvWhenSecretRefIsSet(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(testSecretEngine{})
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
|
||||
}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got == "token-from-env" {
|
||||
t.Fatal("resolveTelegramToken used TokenEnv despite Token being configured")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveTelegramTokenAcceptsTokenRefWithoutTokenEnv is the regression
|
||||
// guard for channels-telegram-5: a deployment configured only via
|
||||
// chat.telegram.token must resolve, since Token takes precedence over
|
||||
// TokenEnv and requiring both would reject every secret-engine setup.
|
||||
func TestResolveTelegramTokenAcceptsTokenRefWithoutTokenEnv(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(testSecretEngine{})
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
// TokenEnv deliberately left empty.
|
||||
}
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got != "token-from-bws" {
|
||||
t.Fatalf("resolveTelegramToken = %q, want token-from-bws", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveTelegramTokenReportsUnresolvableRef is the companion negative
|
||||
// case: an unregistered engine must surface as an error rather than an
|
||||
// empty token that composes a channel nothing can authenticate.
|
||||
func TestResolveTelegramTokenReportsUnresolvableRef(t *testing.T) {
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "nosuch", Key: "telegram-token"},
|
||||
}
|
||||
|
||||
if _, err := resolveTelegramToken(cfg, secret.NewRegistry()); err == nil {
|
||||
t.Fatal("resolveTelegramToken error = nil, want an error: the engine is not registered")
|
||||
}
|
||||
}
|
||||
+8
-9
@@ -1,4 +1,4 @@
|
||||
package archied
|
||||
package archiemessaging
|
||||
|
||||
import (
|
||||
"testing"
|
||||
@@ -6,14 +6,13 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestWebhookRoutesAppliesConfiguredFields is the red case for
|
||||
// channels-platform-3: RouteConfig.Secret/Template/DeliverTo are
|
||||
// implemented and tested in internal/channels/webhook, but the only
|
||||
// production construction (setupWebhookGateway) built
|
||||
// []webhook.RouteConfig{{Path: "/webhook"}} literally, so no config value
|
||||
// could ever reach them and HMAC validation never ran. webhookRoutes is the
|
||||
// translation site; this pins that a configured [chat.webhook] route
|
||||
// actually reaches the gateway's RouteConfig.
|
||||
// TestWebhookRoutesAppliesConfiguredFields is the guard for
|
||||
// channels-platform-3: RouteConfig.Secret/Template/DeliverTo are implemented
|
||||
// and tested in internal/channels/webhook, but the original production
|
||||
// construction built []webhook.RouteConfig{{Path: "/webhook"}} literally, so
|
||||
// no config value could ever reach them and HMAC validation never ran.
|
||||
// webhookRoutes is the translation site; this pins that a configured
|
||||
// [chat.webhook] route actually reaches the gateway's RouteConfig.
|
||||
func TestWebhookRoutesAppliesConfiguredFields(t *testing.T) {
|
||||
route := config.WebhookRoute{
|
||||
Path: "/github",
|
||||
@@ -1,41 +1,27 @@
|
||||
// Package channels defines the interface every chat channel must satisfy
|
||||
// to integrate with archie-core's gateway router. Channels own their
|
||||
// persistent connection lifecycle; the gateway handles message dispatch.
|
||||
//
|
||||
// Each channel declares its required configuration via ConfigSchema so
|
||||
// the daemon can validate wiring at startup — catching missing tokens,
|
||||
// invalid ports, or misconfigured credentials before accepting connections.
|
||||
// to integrate with archie-core's messaging layer. Channels own their
|
||||
// persistent connection lifecycle; the Gateway handles message dispatch.
|
||||
package channels
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// Channel is the contract every chat platform must satisfy. It extends
|
||||
// gateway.Gateway with configuration introspection so the daemon can
|
||||
// validate and introspect channels at startup without knowing about
|
||||
// specific implementations.
|
||||
type Channel interface {
|
||||
gateway.Gateway
|
||||
// Lifecycle receives adapter-owned startup facts.
|
||||
type Lifecycle = messaging.Lifecycle
|
||||
|
||||
// ConfigSchema returns the JSON Schema for this channel's required
|
||||
// configuration. The daemon uses this at startup to validate that
|
||||
// the user's config file provides all required fields and to surface
|
||||
// clear errors when a channel is misconfigured.
|
||||
//
|
||||
// The schema must include:
|
||||
// - type: object
|
||||
// - required: [...] (fields that must be present)
|
||||
// - properties: {...} (field definitions with types and descriptions)
|
||||
// Channel is the contract every chat platform must satisfy.
|
||||
type Channel interface {
|
||||
Name() string
|
||||
Start(ctx context.Context, client messaging.ChatContract, lifecycle Lifecycle) error
|
||||
Stop(ctx context.Context) error
|
||||
|
||||
// ConfigSchema returns the JSON Schema for this channel's required configuration.
|
||||
ConfigSchema() json.RawMessage
|
||||
|
||||
// ValidateConfig checks that the provided configuration is valid for
|
||||
// this channel. Returns nil when the config is acceptable, or a
|
||||
// descriptive error when required fields are missing or invalid.
|
||||
//
|
||||
// The cfg argument is the channel-specific portion of the daemon
|
||||
// config (e.g. the [chat.telegram] block, not the full Config).
|
||||
// ValidateConfig checks that the provided configuration is valid for this channel.
|
||||
ValidateConfig(cfg map[string]any) error
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// Gateway is an email gateway that receives inbound messages via SMTP
|
||||
@@ -37,7 +36,7 @@ type Gateway struct {
|
||||
AllowedDomains []string
|
||||
|
||||
log *slog.Logger
|
||||
router *gateway.Router
|
||||
client messaging.ChatContract
|
||||
mu sync.Mutex
|
||||
ln net.Listener
|
||||
}
|
||||
@@ -58,10 +57,10 @@ func (g *Gateway) Name() string { return "email" }
|
||||
|
||||
// Start begins listening for SMTP connections. Blocks until ctx is
|
||||
// cancelled.
|
||||
func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) error {
|
||||
func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) error {
|
||||
lifecycle.ReportStarting()
|
||||
g.mu.Lock()
|
||||
g.router = router
|
||||
g.client = client
|
||||
g.mu.Unlock()
|
||||
|
||||
lc := net.ListenConfig{}
|
||||
@@ -187,13 +186,13 @@ func extractAddr(line string) string {
|
||||
}
|
||||
|
||||
// processMessage extracts text from the raw email and routes it through
|
||||
// the gateway router. Replies are sent back via SMTP.
|
||||
// the messaging chat contract. Replies are sent back via SMTP.
|
||||
func (g *Gateway) processMessage(ctx context.Context, from, to, raw string) {
|
||||
g.mu.Lock()
|
||||
router := g.router
|
||||
client := g.client
|
||||
g.mu.Unlock()
|
||||
|
||||
if router == nil {
|
||||
if client == nil {
|
||||
g.log.Warn("email received before gateway started")
|
||||
return
|
||||
}
|
||||
@@ -202,21 +201,21 @@ func (g *Gateway) processMessage(ctx context.Context, from, to, raw string) {
|
||||
// following Content-Type or headers.
|
||||
text := extractBody(raw)
|
||||
|
||||
msg := gateway.Inbound{Message: messaging.Message{
|
||||
msg := messaging.Inbound{Message: messaging.Message{
|
||||
ConversationID: messaging.ConversationID{ChannelID: to},
|
||||
Sender: from,
|
||||
SenderID: from,
|
||||
Role: messaging.RoleUser,
|
||||
Text: text,
|
||||
}}
|
||||
reply, err := router.Route(ctx, msg)
|
||||
reply, err := client.Route(ctx, msg)
|
||||
if err != nil {
|
||||
g.log.Error("email route", "err", err, "from", from)
|
||||
return
|
||||
}
|
||||
|
||||
if reply != "" && g.RelayAddr != "" {
|
||||
if err := g.sendReply(from, to, reply); err != nil {
|
||||
if reply.Text != "" && g.RelayAddr != "" {
|
||||
if err := g.sendReply(from, to, reply.Text); err != nil {
|
||||
g.log.Error("email reply", "err", err, "to", from)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,22 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type fakeChatContract struct {
|
||||
messaging.ChatContract
|
||||
routeFunc func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error)
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
||||
if f.routeFunc != nil {
|
||||
return f.routeFunc(ctx, in)
|
||||
}
|
||||
return messaging.ChatReply{Text: "ok"}, nil
|
||||
}
|
||||
|
||||
func TestName(t *testing.T) {
|
||||
g := New(":2525", "", slog.Default())
|
||||
if g.Name() != "email" {
|
||||
@@ -82,15 +95,17 @@ func TestSMTPReceiveAndRoute(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
g := New(":0", "", log)
|
||||
|
||||
router := gateway.NewRouter(nil, func(ctx context.Context, in gateway.Inbound) (string, error) {
|
||||
if in.Message.Sender != "sender@test.com" {
|
||||
return "", fmt.Errorf("unexpected sender: %s", in.Message.Sender)
|
||||
}
|
||||
if in.Message.SenderID != "sender@test.com" {
|
||||
return "", fmt.Errorf("unexpected SenderID: %s", in.Message.SenderID)
|
||||
}
|
||||
return "got it", nil
|
||||
}, "email")
|
||||
chat := &fakeChatContract{
|
||||
routeFunc: func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
||||
if in.Message.Sender != "sender@test.com" {
|
||||
return messaging.ChatReply{}, fmt.Errorf("unexpected sender: %s", in.Message.Sender)
|
||||
}
|
||||
if in.Message.SenderID != "sender@test.com" {
|
||||
return messaging.ChatReply{}, fmt.Errorf("unexpected SenderID: %s", in.Message.SenderID)
|
||||
}
|
||||
return messaging.ChatReply{Text: "got it"}, nil
|
||||
},
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
@@ -105,7 +120,7 @@ func TestSMTPReceiveAndRoute(t *testing.T) {
|
||||
_ = ln.Close()
|
||||
|
||||
g.ListenAddr = addr
|
||||
go func() { _ = g.Start(ctx, router, gateway.Lifecycle{}) }()
|
||||
go func() { _ = g.Start(ctx, chat, channels.Lifecycle{}) }()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
defer func() { _ = g.Stop(context.Background()) }()
|
||||
|
||||
@@ -169,6 +184,6 @@ func TestTruncateSubject(t *testing.T) {
|
||||
|
||||
// Compile-time guard.
|
||||
var (
|
||||
_ gateway.Gateway = (*Gateway)(nil)
|
||||
_ = smtp.PlainAuth
|
||||
_ channels.Channel = (*Gateway)(nil)
|
||||
_ = smtp.PlainAuth
|
||||
)
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// approvalCallbackPrefix separates tool-approval callbacks from other
|
||||
@@ -49,18 +49,18 @@ type pendingApproval struct {
|
||||
// approvalResult carries the human's decision back to the blocked
|
||||
// RequestApproval call.
|
||||
type approvalResult struct {
|
||||
decision gateway.ApprovalDecision
|
||||
decision messaging.ApprovalDecision
|
||||
err error
|
||||
}
|
||||
|
||||
// Compile-time guard.
|
||||
var _ gateway.ApprovalRequester = (*telegramApprover)(nil)
|
||||
var _ messaging.ApprovalRequester = (*telegramApprover)(nil)
|
||||
|
||||
// NewApprover returns an ApprovalRequester that renders prompts in the
|
||||
// given chat. recipient is the Telegram user who may approve; in a private
|
||||
// DM this is the same as chatID, in a group it is the sender of the turn
|
||||
// that triggered the gated tool call.
|
||||
func (g *Gateway) NewApprover(b *bot.Bot, chatID int64, threadID int, recipient int64) gateway.ApprovalRequester {
|
||||
func (g *Gateway) NewApprover(b *bot.Bot, chatID int64, threadID int, recipient int64) messaging.ApprovalRequester {
|
||||
return &telegramApprover{
|
||||
gw: g,
|
||||
bot: b,
|
||||
@@ -76,15 +76,15 @@ func (g *Gateway) NewApprover(b *bot.Bot, chatID int64, threadID int, recipient
|
||||
// returns ApprovalPermanentlyApproved. Otherwise the recipient is shown the
|
||||
// three-button inline keyboard and the call blocks until the human decides,
|
||||
// the context is cancelled, or the 2-minute approval window
|
||||
// (gateway.ToolApprovalTimeout) elapses.
|
||||
func (a *telegramApprover) RequestApproval(ctx context.Context, action, description string) (gateway.ApprovalDecision, error) {
|
||||
// (messaging.ToolApprovalTimeout) elapses.
|
||||
func (a *telegramApprover) RequestApproval(ctx context.Context, action, description string) (messaging.ApprovalDecision, error) {
|
||||
// Compose the lookup key so a permanent approval is scoped to
|
||||
// the specific resource: "Approve Permanently" on "delete session
|
||||
// abc123" only permanently approves that one session, not every
|
||||
// session_delete forever.
|
||||
permKey := action + "\x00" + description
|
||||
if a.gw.hasPermanentApprovalExact(a.recipient, permKey) {
|
||||
return gateway.ApprovalPermanentlyApproved, nil
|
||||
return messaging.ApprovalPermanentlyApproved, nil
|
||||
}
|
||||
|
||||
token := makeDangerousToken()
|
||||
@@ -94,7 +94,7 @@ func (a *telegramApprover) RequestApproval(ctx context.Context, action, descript
|
||||
action: action,
|
||||
description: description,
|
||||
recipient: a.recipient,
|
||||
expiresAt: time.Now().Add(gateway.ToolApprovalTimeout),
|
||||
expiresAt: time.Now().Add(messaging.ToolApprovalTimeout),
|
||||
resultCh: resultCh,
|
||||
})
|
||||
|
||||
@@ -107,16 +107,16 @@ func (a *telegramApprover) RequestApproval(ctx context.Context, action, descript
|
||||
params.MessageThreadID = a.threadID
|
||||
}
|
||||
|
||||
approvalCtx, cancel := context.WithTimeout(ctx, gateway.ToolApprovalTimeout)
|
||||
approvalCtx, cancel := context.WithTimeout(ctx, messaging.ToolApprovalTimeout)
|
||||
defer cancel()
|
||||
|
||||
if _, err := a.bot.SendMessage(approvalCtx, params); err != nil {
|
||||
a.gw.removePendingApproval(token)
|
||||
if approvalCtx.Err() != nil {
|
||||
return gateway.ApprovalDenied, approvalCtx.Err()
|
||||
return messaging.ApprovalDenied, approvalCtx.Err()
|
||||
}
|
||||
a.gw.log.Error("send approval prompt failed", "error", err)
|
||||
return gateway.ApprovalDenied, fmt.Errorf("send approval prompt: %w", err)
|
||||
return messaging.ApprovalDenied, fmt.Errorf("send approval prompt: %w", err)
|
||||
}
|
||||
|
||||
select {
|
||||
@@ -130,30 +130,30 @@ func (a *telegramApprover) RequestApproval(ctx context.Context, action, descript
|
||||
return a.applyApprovalDecision(action, description, result)
|
||||
default:
|
||||
a.gw.removePendingApproval(token)
|
||||
return gateway.ApprovalDenied, approvalCtx.Err()
|
||||
return messaging.ApprovalDenied, approvalCtx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// applyApprovalDecision maps a human decision to the gateway contract,
|
||||
// recording a permanent approval when the human asked for one.
|
||||
func (a *telegramApprover) applyApprovalDecision(action, description string, result approvalResult) (gateway.ApprovalDecision, error) {
|
||||
func (a *telegramApprover) applyApprovalDecision(action, description string, result approvalResult) (messaging.ApprovalDecision, error) {
|
||||
switch result.decision {
|
||||
case gateway.ApprovalApproved:
|
||||
return gateway.ApprovalApproved, nil
|
||||
case gateway.ApprovalPermanentlyApproved:
|
||||
case messaging.ApprovalApproved:
|
||||
return messaging.ApprovalApproved, nil
|
||||
case messaging.ApprovalPermanentlyApproved:
|
||||
// Scoped: permanently approving "delete session abc123" only
|
||||
// silences the prompt for that one resource, not every call to
|
||||
// the same tool.
|
||||
a.gw.recordPermanentApproval(a.recipient, action+"\x00"+description)
|
||||
return gateway.ApprovalPermanentlyApproved, nil
|
||||
case gateway.ApprovalDenied:
|
||||
return messaging.ApprovalPermanentlyApproved, nil
|
||||
case messaging.ApprovalDenied:
|
||||
if result.err != nil {
|
||||
return gateway.ApprovalDenied, result.err
|
||||
return messaging.ApprovalDenied, result.err
|
||||
}
|
||||
return gateway.ApprovalDenied, gateway.ErrApprovalDenied
|
||||
return messaging.ApprovalDenied, messaging.ErrApprovalDenied
|
||||
default:
|
||||
return gateway.ApprovalDenied, fmt.Errorf("unexpected approval decision %v", result.decision)
|
||||
return messaging.ApprovalDenied, fmt.Errorf("unexpected approval decision %v", result.decision)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,15 +255,15 @@ func (g *Gateway) handleApprovalCallback(ctx context.Context, b *bot.Bot, update
|
||||
|
||||
switch decision {
|
||||
case "approve":
|
||||
pa.resultCh <- approvalResult{decision: gateway.ApprovalApproved}
|
||||
pa.resultCh <- approvalResult{decision: messaging.ApprovalApproved}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Approved and executed.", false)
|
||||
g.editDangerousMessage(ctx, b, query, "✅ Approved: "+pa.description)
|
||||
case "permanent":
|
||||
pa.resultCh <- approvalResult{decision: gateway.ApprovalPermanentlyApproved}
|
||||
pa.resultCh <- approvalResult{decision: messaging.ApprovalPermanentlyApproved}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Permanently approved (valid 24h).", false)
|
||||
g.editDangerousMessage(ctx, b, query, "✅ Approved (permanent, 24h): "+pa.description)
|
||||
case "deny":
|
||||
pa.resultCh <- approvalResult{decision: gateway.ApprovalDenied, err: gateway.ErrApprovalDenied}
|
||||
pa.resultCh <- approvalResult{decision: messaging.ApprovalDenied, err: messaging.ErrApprovalDenied}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Action denied.", false)
|
||||
g.editDangerousMessage(ctx, b, query, "❌ Denied: "+pa.description)
|
||||
}
|
||||
@@ -284,7 +284,7 @@ func parseApprovalCallback(data string) (decision, token string) {
|
||||
// The expiry figure is derived from the shared constant so a change to the
|
||||
// approval window cannot leave the prompt out of date.
|
||||
func approvalPromptText(action, description string) string {
|
||||
minutes := int(gateway.ToolApprovalTimeout.Minutes())
|
||||
minutes := int(messaging.ToolApprovalTimeout.Minutes())
|
||||
return fmt.Sprintf(
|
||||
"⚠️ Approval required\n\n"+
|
||||
"Action: %s\n"+
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -26,7 +26,7 @@ func newApprovalTestGateway(t *testing.T) (*Gateway, *bot.Bot, *[]telegramReques
|
||||
return g, b, requests
|
||||
}
|
||||
|
||||
func newTestApprover(g *Gateway, b *bot.Bot) gateway.ApprovalRequester {
|
||||
func newTestApprover(g *Gateway, b *bot.Bot) messaging.ApprovalRequester {
|
||||
return g.NewApprover(b, approvalTestChatID, 0, approvalTestRecipient)
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ func TestApprovalRequestPermanentShortCircuits(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("RequestApproval error = %v", err)
|
||||
}
|
||||
if decision != gateway.ApprovalPermanentlyApproved {
|
||||
if decision != messaging.ApprovalPermanentlyApproved {
|
||||
t.Errorf("decision = %v, want ApprovalPermanentlyApproved", decision)
|
||||
}
|
||||
if len(*requests) != 0 {
|
||||
@@ -90,7 +90,7 @@ func TestApprovalRequestPermanentViaButton(t *testing.T) {
|
||||
approver := newTestApprover(g, b)
|
||||
|
||||
done := make(chan struct{})
|
||||
var decision gateway.ApprovalDecision
|
||||
var decision messaging.ApprovalDecision
|
||||
var err error
|
||||
go func() {
|
||||
decision, err = approver.RequestApproval(context.Background(), "session_delete", "Delete session")
|
||||
@@ -112,7 +112,7 @@ func TestApprovalRequestPermanentViaButton(t *testing.T) {
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("RequestApproval did not return after permanent button")
|
||||
}
|
||||
if decision != gateway.ApprovalPermanentlyApproved {
|
||||
if decision != messaging.ApprovalPermanentlyApproved {
|
||||
t.Errorf("decision = %v, want ApprovalPermanentlyApproved", decision)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -139,7 +139,7 @@ func TestApprovalRequestApprove(t *testing.T) {
|
||||
approver := newTestApprover(g, b)
|
||||
|
||||
done := make(chan struct{})
|
||||
var decision gateway.ApprovalDecision
|
||||
var decision messaging.ApprovalDecision
|
||||
var err error
|
||||
go func() {
|
||||
decision, err = approver.RequestApproval(context.Background(), "session_delete", "Delete session")
|
||||
@@ -161,7 +161,7 @@ func TestApprovalRequestApprove(t *testing.T) {
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("RequestApproval did not return after approve")
|
||||
}
|
||||
if decision != gateway.ApprovalApproved {
|
||||
if decision != messaging.ApprovalApproved {
|
||||
t.Errorf("decision = %v, want ApprovalApproved", decision)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -174,7 +174,7 @@ func TestApprovalRequestDenied(t *testing.T) {
|
||||
approver := newTestApprover(g, b)
|
||||
|
||||
done := make(chan struct{})
|
||||
var decision gateway.ApprovalDecision
|
||||
var decision messaging.ApprovalDecision
|
||||
var err error
|
||||
go func() {
|
||||
decision, err = approver.RequestApproval(context.Background(), "session_delete", "Delete session")
|
||||
@@ -196,10 +196,10 @@ func TestApprovalRequestDenied(t *testing.T) {
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("RequestApproval did not return after deny")
|
||||
}
|
||||
if decision != gateway.ApprovalDenied {
|
||||
if decision != messaging.ApprovalDenied {
|
||||
t.Errorf("decision = %v, want ApprovalDenied", decision)
|
||||
}
|
||||
if !errors.Is(err, gateway.ErrApprovalDenied) {
|
||||
if !errors.Is(err, messaging.ErrApprovalDenied) {
|
||||
t.Errorf("err = %v, want ErrApprovalDenied", err)
|
||||
}
|
||||
}
|
||||
@@ -214,13 +214,13 @@ func TestApprovalRequestTimeoutReturnsContextError(t *testing.T) {
|
||||
defer cancel()
|
||||
|
||||
decision, err := approver.RequestApproval(ctx, "session_delete", "Delete session")
|
||||
if decision != gateway.ApprovalDenied {
|
||||
if decision != messaging.ApprovalDenied {
|
||||
t.Errorf("decision = %v, want ApprovalDenied on timeout", decision)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("expected a context error on timeout")
|
||||
}
|
||||
if errors.Is(err, gateway.ErrApprovalDenied) {
|
||||
if errors.Is(err, messaging.ErrApprovalDenied) {
|
||||
t.Errorf("timeout must not be ErrApprovalDenied, got %v", err)
|
||||
}
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
@@ -319,7 +319,7 @@ func TestApprovalCallbackPrefixDistinctFromDangerous(t *testing.T) {
|
||||
|
||||
func TestDefaultHandlerDispatchesApprovalCallback(t *testing.T) {
|
||||
g, b, requests := newApprovalTestGateway(t)
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
chat := &fakeChatContract{}
|
||||
|
||||
token := makeDangerousToken()
|
||||
g.registerPendingApproval(pendingApproval{
|
||||
@@ -331,7 +331,7 @@ func TestDefaultHandlerDispatchesApprovalCallback(t *testing.T) {
|
||||
resultCh: make(chan approvalResult, 1),
|
||||
})
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(chat)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: approvalTestRecipient},
|
||||
|
||||
@@ -14,15 +14,14 @@ import (
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// These aliases keep Telegram's public configuration surface source
|
||||
// compatible while making the authority contract reusable by other
|
||||
// interactive adapters such as the Web UI.
|
||||
type (
|
||||
DangerousCommandAuthority = gateway.DangerousCommandAuthority
|
||||
CheckpointInfo = gateway.CheckpointInfo
|
||||
DangerousCommandAuthority = messaging.DangerousCommandAuthority
|
||||
CheckpointInfo = messaging.CheckpointInfo
|
||||
)
|
||||
|
||||
// ── dangerous command approval system ─────────────────────────────
|
||||
@@ -419,53 +418,26 @@ func rollbackApprovalText(num int) string {
|
||||
// with exec.CommandContext is killed with the turn, which is the case that
|
||||
// matters. Whatever the reply had already streamed stays on screen: it is
|
||||
// the record of what Archie did before being stopped.
|
||||
func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.Message, router *gateway.Router) {
|
||||
func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
|
||||
var cancelled bool
|
||||
var dropped int
|
||||
|
||||
// turns is only built by launch, so a gateway that has never started
|
||||
// simply has nothing to stop. Report that rather than failing.
|
||||
if g.turns != nil && router != nil {
|
||||
session, err := router.ResolveSessionKey(ctx, gateway.Inbound{Message: messaging.Message{
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
Text: msg.Text,
|
||||
}})
|
||||
if err != nil {
|
||||
g.log.Error("resolve session for stop", "error", err)
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "❌ Could not resolve this conversation's session.")
|
||||
return
|
||||
}
|
||||
session := conversationID(msg).String()
|
||||
if g.turns != nil {
|
||||
cancelled, dropped = g.turns.Stop(session)
|
||||
g.log.Info("stop requested", "session", session, "cancelled", cancelled, "dropped", dropped)
|
||||
}
|
||||
|
||||
// The brake covers agent tasks as well as the conversation. Someone
|
||||
// reaching for it wants everything to stop, and should not have to
|
||||
// know a task ID -- or which of the two is currently misbehaving.
|
||||
stoppedTasks := g.stopRunningTasks(ctx, router)
|
||||
if client != nil {
|
||||
if res, err := client.Cancel(ctx, session); err == nil {
|
||||
if res.Cancelled {
|
||||
cancelled = true
|
||||
}
|
||||
dropped += res.Dropped
|
||||
}
|
||||
}
|
||||
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
stopReport(cancelled, dropped, stoppedTasks))
|
||||
}
|
||||
|
||||
// stopRunningTasks interrupts the agent tasks currently executing and
|
||||
// returns their IDs. A failure here is logged and reported as none
|
||||
// stopped: /stop must still do whatever else it can.
|
||||
func (g *Gateway) stopRunningTasks(ctx context.Context, router *gateway.Router) []int64 {
|
||||
if router == nil || router.Controller == nil {
|
||||
return nil
|
||||
}
|
||||
stopped, err := router.Controller.StopRunning(ctx, router.Identity)
|
||||
if err != nil {
|
||||
g.log.Warn("stop running tasks failed", "error", err)
|
||||
return nil
|
||||
}
|
||||
if len(stopped) > 0 {
|
||||
g.log.Info("stopped running tasks", "tasks", stopped)
|
||||
}
|
||||
return stopped
|
||||
stopReport(cancelled, dropped, nil))
|
||||
}
|
||||
|
||||
// stopReport describes what a /stop actually stopped.
|
||||
@@ -516,7 +488,7 @@ func joinWithAnd(parts []string) string {
|
||||
//
|
||||
// /stop <process-name> keeps the original behaviour of terminating a named
|
||||
// background process, which is destructive and still requires approval.
|
||||
func (g *Gateway) stopHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
func (g *Gateway) stopHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
@@ -525,7 +497,7 @@ func (g *Gateway) stopHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
|
||||
rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/stop", ""))
|
||||
if rest == "" {
|
||||
g.stopCurrentTurn(ctx, b, msg, router)
|
||||
g.stopCurrentTurn(ctx, b, msg, client)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// ── DangerousCommandAuthority stub ─────────────────────────────
|
||||
@@ -407,7 +407,7 @@ func TestStopCancelsRunningChatTurn(t *testing.T) {
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
|
||||
ctx := t.Context()
|
||||
g.turns = gateway.NewTurns(slog.Default())
|
||||
g.turns = messaging.NewTurns(slog.Default())
|
||||
|
||||
// stopCurrentTurn resolves the session through the router; with none
|
||||
// wired, drive the lane directly and assert on the lane's state.
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
type fakeChatContract struct {
|
||||
snapshot messaging.ChatSnapshot
|
||||
snapshotErr error
|
||||
routeFunc func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error)
|
||||
streamFunc func(ctx context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error)
|
||||
cancelFunc func(ctx context.Context, id string) (messaging.ChatCancellation, error)
|
||||
setPersonaFunc func(ctx context.Context, id, name string) (bool, error)
|
||||
details map[string]messaging.ModelDetails
|
||||
}
|
||||
|
||||
var (
|
||||
_ messaging.ChatContract = (*fakeChatContract)(nil)
|
||||
_ messaging.DetailedModelManager = (*fakeChatContract)(nil)
|
||||
)
|
||||
|
||||
func (f *fakeChatContract) ModelDetails(ref string) (messaging.ModelDetails, bool) {
|
||||
if f.details == nil {
|
||||
return messaging.ModelDetails{}, false
|
||||
}
|
||||
d, ok := f.details[ref]
|
||||
return d, ok
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) Snapshot(ctx context.Context) (messaging.ChatSnapshot, error) {
|
||||
if f.snapshotErr != nil {
|
||||
return messaging.ChatSnapshot{}, f.snapshotErr
|
||||
}
|
||||
return f.snapshot, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) GetSession(ctx context.Context, id string) (messaging.SessionContext, bool, error) {
|
||||
return messaging.SessionContext{}, false, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) RecentMessages(ctx context.Context, id string, n int) ([]messaging.Message, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) RecentTurns(ctx context.Context, id string, n int) ([]messaging.TurnRecord, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
||||
if f.routeFunc != nil {
|
||||
return f.routeFunc(ctx, in)
|
||||
}
|
||||
return messaging.ChatReply{Text: "ok"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) Stream(ctx context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) {
|
||||
if f.streamFunc != nil {
|
||||
return f.streamFunc(ctx, in)
|
||||
}
|
||||
ch := make(chan messaging.ChatEvent, 2)
|
||||
ch <- messaging.ChatEvent{Kind: "started", SessionID: "s1"}
|
||||
ch <- messaging.ChatEvent{Kind: "done", Text: "done", SessionID: "s1"}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) Cancel(ctx context.Context, id string) (messaging.ChatCancellation, error) {
|
||||
if f.cancelFunc != nil {
|
||||
return f.cancelFunc(ctx, id)
|
||||
}
|
||||
return messaging.ChatCancellation{Cancelled: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) SetPersona(ctx context.Context, id, name string) (bool, error) {
|
||||
if f.setPersonaFunc != nil {
|
||||
return f.setPersonaFunc(ctx, id, name)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) {
|
||||
return messaging.TaskActionResult{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) ApplyOperatorTaskAction(ctx context.Context, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) {
|
||||
return messaging.TaskActionResult{}, nil
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -95,7 +95,7 @@ type liveReply struct {
|
||||
// with fixed Capabilities(), which the real Telegram one can't
|
||||
// express (it always reports Media: true) but a future channel or a
|
||||
// capability-limited deployment might.
|
||||
newMediaSender func(b *bot.Bot, chatID int64, threadID int) gateway.MediaSender
|
||||
newMediaSender func(b *bot.Bot, chatID int64, threadID int) messaging.MediaSender
|
||||
|
||||
cancelRender context.CancelFunc
|
||||
renderRequests chan chan struct{}
|
||||
@@ -337,15 +337,15 @@ func (l *liveReply) Delta(text string) {
|
||||
// joining the line because the tool line and the model's reply share one
|
||||
// Markdown body (finalText): an unbalanced marker in the tool line breaks
|
||||
// parsing for the whole message, including the reply's own formatting.
|
||||
func (l *liveReply) ToolCall(event gateway.ToolCallEvent) {
|
||||
func (l *liveReply) ToolCall(event messaging.ToolCallEvent) {
|
||||
if !l.showToolCalls || event.Name == "" {
|
||||
return
|
||||
}
|
||||
// Render the completed result as a compact fenced block. Do not append the
|
||||
// raw/JSON-shaped parameters: they are noisy, can expose secrets, and were
|
||||
// the source of unreadable schema placeholders in Telegram.
|
||||
line := gateway.RenderToolCall(event)
|
||||
key := gateway.FailureKey(event)
|
||||
line := messaging.RenderToolCall(event)
|
||||
key := messaging.FailureKey(event)
|
||||
|
||||
l.mu.Lock()
|
||||
if index, ok := l.failureLines[key]; key != "" && ok {
|
||||
@@ -396,7 +396,7 @@ const mediaSendTimeout = 30 * time.Second
|
||||
// This used to skip on a missing URL alone, which dropped every local
|
||||
// file before it reached the sender -- the guard, not just the sender,
|
||||
// was part of making a local path undeliverable.
|
||||
func (l *liveReply) Media(event gateway.MediaEvent) {
|
||||
func (l *liveReply) Media(ctx context.Context, event messaging.MediaEvent) {
|
||||
if event.Attachment.URL == "" && event.Attachment.Path == "" {
|
||||
return
|
||||
}
|
||||
@@ -408,18 +408,18 @@ func (l *liveReply) Media(event gateway.MediaEvent) {
|
||||
// the entire point of CapabilityReporter over attempt-then-catch
|
||||
// -- a sender that already knows it cannot deliver a given media
|
||||
// kind should never cost a doomed network round trip to find out.
|
||||
if !gateway.CapabilitiesOf(sender).Media {
|
||||
if !messaging.CapabilitiesOf(sender).Media {
|
||||
l.g.log.Debug("channel cannot deliver media inline, falling back to a link",
|
||||
"tool", event.ToolName, "type", event.Attachment.Type)
|
||||
l.appendFallbackLine(event.Attachment)
|
||||
l.appendFallbackLine(ctx, event.Attachment)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), mediaSendTimeout)
|
||||
sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), mediaSendTimeout)
|
||||
defer cancel()
|
||||
|
||||
_, err := sender.SendMedia(ctx, gateway.MessageEvent{
|
||||
Media: []gateway.MediaAttachment{event.Attachment},
|
||||
_, err := sender.SendMedia(sendCtx, messaging.MessageEvent{
|
||||
Media: []messaging.MediaAttachment{event.Attachment},
|
||||
})
|
||||
if err == nil {
|
||||
return
|
||||
@@ -427,14 +427,14 @@ func (l *liveReply) Media(event gateway.MediaEvent) {
|
||||
|
||||
l.g.log.Warn("media delivery failed, falling back to a link",
|
||||
"tool", event.ToolName, "type", event.Attachment.Type, "error", err)
|
||||
l.appendFallbackLine(event.Attachment)
|
||||
l.appendFallbackLine(ctx, event.Attachment)
|
||||
})
|
||||
}
|
||||
|
||||
// appendFallbackLine renders att as a visible link in the reply, for a
|
||||
// MediaEvent that could not be (or was not attempted to be) delivered
|
||||
// inline.
|
||||
func (l *liveReply) appendFallbackLine(att gateway.MediaAttachment) {
|
||||
func (l *liveReply) appendFallbackLine(ctx context.Context, att messaging.MediaAttachment) {
|
||||
// A local attachment has no URL to fall back to, and printing an empty
|
||||
// one reads as a delivered file. Say plainly that it was not sent:
|
||||
// the whole defect this path exists around is that non-delivery and
|
||||
@@ -455,9 +455,9 @@ func (l *liveReply) appendFallbackLine(att gateway.MediaAttachment) {
|
||||
// live message it would have edited is done being edited. Send
|
||||
// this as its own message instead of dropping it.
|
||||
l.mu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), mediaSendTimeout)
|
||||
sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), mediaSendTimeout)
|
||||
defer cancel()
|
||||
l.g.sendMessage(ctx, l.b, l.chatID, l.messageThreadID, line)
|
||||
l.g.sendMessage(sendCtx, l.b, l.chatID, l.messageThreadID, line)
|
||||
return
|
||||
}
|
||||
l.toolLines = append(l.toolLines, line)
|
||||
|
||||
@@ -987,7 +987,7 @@ func TestGatewayRegisterLiveAfterStopAbandonsImmediately(t *testing.T) {
|
||||
func TestLiveReplyMediaDeliversTheAttachment(t *testing.T) {
|
||||
live, calls := newTestLiveReply(t, false)
|
||||
|
||||
live.Media(gateway.MediaEvent{
|
||||
live.Media(t.Context(), gateway.MediaEvent{
|
||||
ToolName: "video_gen",
|
||||
Attachment: gateway.MediaAttachment{Type: "video", URL: "https://example.com/v.mp4"},
|
||||
})
|
||||
@@ -1006,7 +1006,7 @@ func TestLiveReplyMediaDeliversTheAttachment(t *testing.T) {
|
||||
func TestLiveReplyMediaWithNoURLIsANoop(t *testing.T) {
|
||||
live, calls := newTestLiveReply(t, false)
|
||||
|
||||
live.Media(gateway.MediaEvent{ToolName: "video_gen", Attachment: gateway.MediaAttachment{Type: "video"}})
|
||||
live.Media(t.Context(), gateway.MediaEvent{ToolName: "video_gen", Attachment: gateway.MediaAttachment{Type: "video"}})
|
||||
live.waitMedia()
|
||||
|
||||
if len(*calls) != 0 {
|
||||
@@ -1033,7 +1033,7 @@ func TestLiveReplyMediaFallsBackToALinkOnFailure(t *testing.T) {
|
||||
t.Cleanup(live.stopRendering)
|
||||
live.interval = 0
|
||||
|
||||
live.Media(gateway.MediaEvent{
|
||||
live.Media(t.Context(), gateway.MediaEvent{
|
||||
ToolName: "video_gen",
|
||||
Attachment: gateway.MediaAttachment{Type: "video", URL: "https://example.com/v.mp4"},
|
||||
})
|
||||
@@ -1079,7 +1079,7 @@ func TestLiveReplyMediaSkipsDeliveryWhenCapabilityReportsUnsupported(t *testing.
|
||||
sender := &capabilityLimitedSender{}
|
||||
live.newMediaSender = func(*bot.Bot, int64, int) gateway.MediaSender { return sender }
|
||||
|
||||
live.Media(gateway.MediaEvent{
|
||||
live.Media(t.Context(), gateway.MediaEvent{
|
||||
ToolName: "video_gen",
|
||||
Attachment: gateway.MediaAttachment{Type: "video", URL: "https://example.com/v.mp4"},
|
||||
})
|
||||
@@ -1120,7 +1120,7 @@ func TestLiveReplyMediaFallbackReportsUndeliveredLocalFile(t *testing.T) {
|
||||
live, _ := newTestLiveReply(t, false)
|
||||
live.newMediaSender = func(*bot.Bot, int64, int) gateway.MediaSender { return failingSender{} }
|
||||
|
||||
live.Media(gateway.MediaEvent{
|
||||
live.Media(t.Context(), gateway.MediaEvent{
|
||||
ToolName: "send_file",
|
||||
Attachment: gateway.MediaAttachment{
|
||||
Type: "document",
|
||||
@@ -1158,7 +1158,7 @@ func TestLiveReplyMediaFallbackAfterFinalizeSendsFollowUp(t *testing.T) {
|
||||
live.doFinalize(context.Background(), "done")
|
||||
before := len(*calls)
|
||||
|
||||
live.Media(gateway.MediaEvent{
|
||||
live.Media(t.Context(), gateway.MediaEvent{
|
||||
ToolName: "send_file",
|
||||
Attachment: gateway.MediaAttachment{Type: "document", Path: "/tmp/report.pdf", FileName: "report.pdf"},
|
||||
})
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// telegramMediaSender delivers a MessageEvent's attachment through the
|
||||
@@ -40,21 +40,21 @@ type telegramMediaSender struct {
|
||||
}
|
||||
|
||||
var (
|
||||
_ gateway.MediaSender = (*telegramMediaSender)(nil)
|
||||
_ gateway.CapabilityReporter = (*telegramMediaSender)(nil)
|
||||
_ messaging.MediaSender = (*telegramMediaSender)(nil)
|
||||
_ messaging.CapabilityReporter = (*telegramMediaSender)(nil)
|
||||
)
|
||||
|
||||
// NewMediaSender returns a MediaSender bound to one chat and to the bot
|
||||
// instance of the launch that created it. Construct it per launch, from
|
||||
// the same b that handled the update, never from a stored field.
|
||||
func (g *Gateway) NewMediaSender(b *bot.Bot, chatID int64, threadID int) gateway.MediaSender {
|
||||
func (g *Gateway) NewMediaSender(b *bot.Bot, chatID int64, threadID int) messaging.MediaSender {
|
||||
return &telegramMediaSender{bot: b, chatID: chatID, threadID: threadID}
|
||||
}
|
||||
|
||||
// Capabilities reports Media support. Telegram implements every media
|
||||
// kind MediaAttachment can describe, so this is unconditionally true.
|
||||
func (s *telegramMediaSender) Capabilities() gateway.AdapterCapabilities {
|
||||
return gateway.AdapterCapabilities{Media: true}
|
||||
func (s *telegramMediaSender) Capabilities() messaging.AdapterCapabilities {
|
||||
return messaging.AdapterCapabilities{Media: true}
|
||||
}
|
||||
|
||||
// errNoMedia and errNoSource are the two ways an event can be
|
||||
@@ -80,7 +80,7 @@ const (
|
||||
// event text. Only the first is sent: a caption belongs to one file, and
|
||||
// batching several into a media group is a distinct API with its own
|
||||
// caption semantics.
|
||||
func (s *telegramMediaSender) SendMedia(ctx context.Context, event gateway.MessageEvent) (gateway.SendResult, error) {
|
||||
func (s *telegramMediaSender) SendMedia(ctx context.Context, event messaging.MessageEvent) (messaging.SendResult, error) {
|
||||
if len(event.Media) == 0 {
|
||||
return invalidMedia(errNoMedia)
|
||||
}
|
||||
@@ -109,7 +109,7 @@ func (s *telegramMediaSender) SendMedia(ctx context.Context, event gateway.Messa
|
||||
if msg != nil {
|
||||
id = fmt.Sprintf("%d", msg.ID)
|
||||
}
|
||||
return gateway.SendResult{Success: true, MessageID: id}, nil
|
||||
return messaging.SendResult{Success: true, MessageID: id}, nil
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -131,7 +131,7 @@ var (
|
||||
// operator sees an attachment that never arrived. The returned error is
|
||||
// classified invalid_message by the caller, so it is not retried -- a
|
||||
// file does not get smaller on a second attempt.
|
||||
func (s *telegramMediaSender) source(att gateway.MediaAttachment) (models.InputFile, func(), error) {
|
||||
func (s *telegramMediaSender) source(att messaging.MediaAttachment) (models.InputFile, func(), error) {
|
||||
noop := func() {}
|
||||
if att.Path == "" {
|
||||
return &models.InputFileString{Data: att.URL}, noop, nil
|
||||
@@ -175,7 +175,7 @@ func uploadLimit(mediaType string) int64 {
|
||||
// media type, not the MessageEvent type, decides: the event type describes
|
||||
// the message while the attachment describes the file, and Telegram
|
||||
// rejects a video sent through sendPhoto.
|
||||
func (s *telegramMediaSender) dispatch(ctx context.Context, att gateway.MediaAttachment, file models.InputFile, caption string) (*models.Message, error) {
|
||||
func (s *telegramMediaSender) dispatch(ctx context.Context, att messaging.MediaAttachment, file models.InputFile, caption string) (*models.Message, error) {
|
||||
switch att.Type {
|
||||
case "video":
|
||||
p := &bot.SendVideoParams{ChatID: s.chatID, Video: file, Caption: caption}
|
||||
@@ -213,8 +213,8 @@ func (s *telegramMediaSender) dispatch(ctx context.Context, att gateway.MediaAtt
|
||||
// invalidMedia reports a failure that was detected before any request was
|
||||
// made. Never retryable: resending an event that carries nothing, or names
|
||||
// a type Telegram has no method for, fails identically every time.
|
||||
func invalidMedia(err error) (gateway.SendResult, error) {
|
||||
return gateway.SendResult{
|
||||
func invalidMedia(err error) (messaging.SendResult, error) {
|
||||
return messaging.SendResult{
|
||||
Success: false,
|
||||
Retryable: false,
|
||||
Error: err,
|
||||
@@ -231,8 +231,8 @@ func invalidMedia(err error) (gateway.SendResult, error) {
|
||||
// failure matching no sentinel is a transport error or a 5xx, both of
|
||||
// which may yet succeed -- hence retryable, rather than defaulting to
|
||||
// permanent and silently dropping a deliverable asset.
|
||||
func classifySendError(err error) gateway.SendResult {
|
||||
res := gateway.SendResult{Success: false, Error: err}
|
||||
func classifySendError(err error) messaging.SendResult {
|
||||
res := messaging.SendResult{Success: false, Error: err}
|
||||
|
||||
switch {
|
||||
case bot.IsTooManyRequestsError(err) || errors.Is(err, bot.ErrorTooManyRequests):
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/tools/sendfile"
|
||||
)
|
||||
|
||||
@@ -97,7 +97,7 @@ func (m *mediaAPI) called() (string, map[string]string) {
|
||||
return m.method, form
|
||||
}
|
||||
|
||||
func newTestMediaSender(t *testing.T, serverURL string, chatID int64, threadID int) gateway.MediaSender {
|
||||
func newTestMediaSender(t *testing.T, serverURL string, chatID int64, threadID int) messaging.MediaSender {
|
||||
t.Helper()
|
||||
b, err := bot.New("1:test", bot.WithServerURL(serverURL), bot.WithSkipGetMe())
|
||||
if err != nil {
|
||||
@@ -114,14 +114,14 @@ func TestSendMedia_RoutesByMediaType(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mediaType string
|
||||
msgType gateway.MessageType
|
||||
msgType messaging.MessageType
|
||||
wantMethod string
|
||||
wantField string
|
||||
}{
|
||||
{"video", "video", gateway.MsgVideo, "sendVideo", "video"},
|
||||
{"image", "image", gateway.MsgImage, "sendPhoto", "photo"},
|
||||
{"audio", "audio", gateway.MsgAudio, "sendAudio", "audio"},
|
||||
{"document", "document", gateway.MsgDocument, "sendDocument", "document"},
|
||||
{"video", "video", messaging.MsgVideo, "sendVideo", "video"},
|
||||
{"image", "image", messaging.MsgImage, "sendPhoto", "photo"},
|
||||
{"audio", "audio", messaging.MsgAudio, "sendAudio", "audio"},
|
||||
{"document", "document", messaging.MsgDocument, "sendDocument", "document"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -130,10 +130,10 @@ func TestSendMedia_RoutesByMediaType(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
res, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Type: tt.msgType,
|
||||
Text: "a caption",
|
||||
Media: []gateway.MediaAttachment{{
|
||||
Media: []messaging.MediaAttachment{{
|
||||
Type: tt.mediaType,
|
||||
URL: "https://example.com/asset",
|
||||
}},
|
||||
@@ -169,9 +169,9 @@ func TestSendMedia_UsesBoundThread(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 99)
|
||||
if _, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
Type: gateway.MsgVideo,
|
||||
Media: []gateway.MediaAttachment{{Type: "video", URL: "https://example.com/v.mp4"}},
|
||||
if _, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Type: messaging.MsgVideo,
|
||||
Media: []messaging.MediaAttachment{{Type: "video", URL: "https://example.com/v.mp4"}},
|
||||
}); err != nil {
|
||||
t.Fatalf("SendMedia: %v", err)
|
||||
}
|
||||
@@ -190,7 +190,7 @@ func TestSendMedia_NoAttachmentIsAnError(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{Type: gateway.MsgVideo})
|
||||
res, err := sender.SendMedia(context.Background(), messaging.MessageEvent{Type: messaging.MsgVideo})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for an event carrying no media")
|
||||
}
|
||||
@@ -216,9 +216,9 @@ func TestSendMedia_MissingSourceIsAnError(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
Type: gateway.MsgVideo,
|
||||
Media: []gateway.MediaAttachment{{Type: "video"}},
|
||||
res, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Type: messaging.MsgVideo,
|
||||
Media: []messaging.MediaAttachment{{Type: "video"}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for an attachment with no URL")
|
||||
@@ -234,9 +234,9 @@ func TestSendMedia_UnknownTypeIsAnError(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
Type: gateway.MsgVideo,
|
||||
Media: []gateway.MediaAttachment{{Type: "hologram", URL: "https://example.com/h"}},
|
||||
res, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Type: messaging.MsgVideo,
|
||||
Media: []messaging.MediaAttachment{{Type: "hologram", URL: "https://example.com/h"}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for an unsupported media type")
|
||||
@@ -274,9 +274,9 @@ func TestSendMedia_ClassifiesAPIFailures(t *testing.T) {
|
||||
api.mu.Unlock()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
Type: gateway.MsgVideo,
|
||||
Media: []gateway.MediaAttachment{{Type: "video", URL: "https://example.com/v.mp4"}},
|
||||
res, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Type: messaging.MsgVideo,
|
||||
Media: []messaging.MediaAttachment{{Type: "video", URL: "https://example.com/v.mp4"}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
@@ -301,7 +301,7 @@ func TestMediaSender_ReportsMediaCapability(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
if caps := gateway.CapabilitiesOf(sender); !caps.Media {
|
||||
if caps := messaging.CapabilitiesOf(sender); !caps.Media {
|
||||
t.Error("telegram media sender does not report the Media capability")
|
||||
}
|
||||
}
|
||||
@@ -341,9 +341,9 @@ func TestSendMedia_UploadsLocalPath(t *testing.T) {
|
||||
path := writeTempFile(t, tt.file, "file bytes")
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
res, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Text: "a caption",
|
||||
Media: []gateway.MediaAttachment{{Type: tt.mediaType, Path: path}},
|
||||
Media: []messaging.MediaAttachment{{Type: tt.mediaType, Path: path}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SendMedia: %v", err)
|
||||
@@ -381,8 +381,8 @@ func TestSendMedia_UploadUsesAttachmentFileName(t *testing.T) {
|
||||
path := writeTempFile(t, "tmp-8342.bin", "x")
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
if _, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
Media: []gateway.MediaAttachment{{Type: "document", Path: path, FileName: "session.log"}},
|
||||
if _, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Media: []messaging.MediaAttachment{{Type: "document", Path: path, FileName: "session.log"}},
|
||||
}); err != nil {
|
||||
t.Fatalf("SendMedia: %v", err)
|
||||
}
|
||||
@@ -426,8 +426,8 @@ func TestSendMedia_LocalPathFailures(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
res, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
Media: []gateway.MediaAttachment{{Type: tt.mediaType, Path: tt.path}},
|
||||
res, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Media: []messaging.MediaAttachment{{Type: tt.mediaType, Path: tt.path}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
@@ -475,8 +475,8 @@ func TestSendMedia_PhotoUnderLimitIsSent(t *testing.T) {
|
||||
path := writeTempFile(t, "ok.png", "small")
|
||||
|
||||
sender := newTestMediaSender(t, srv.URL, 555, 0)
|
||||
if _, err := sender.SendMedia(context.Background(), gateway.MessageEvent{
|
||||
Media: []gateway.MediaAttachment{{Type: "image", Path: path}},
|
||||
if _, err := sender.SendMedia(context.Background(), messaging.MessageEvent{
|
||||
Media: []messaging.MediaAttachment{{Type: "image", Path: path}},
|
||||
}); err != nil {
|
||||
t.Fatalf("SendMedia: %v", err)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -71,12 +70,7 @@ func parseModelRest(rest string) (model, provider string, global, session, refre
|
||||
}
|
||||
|
||||
// splitProviderFlag extracts --provider=<value> or --provider <value> and
|
||||
// returns the provider along with the fields that remain. It is the only place
|
||||
// the surviving fields are accumulated: an earlier version handed a shared
|
||||
// slice to the helper and appended to it again in the caller's loop, so every
|
||||
// model name was doubled ("/model gpt-4o" asked for "gpt-4o gpt-4o"). A
|
||||
// space-separated provider value is removed with its flag rather than left in
|
||||
// the remainder, where it would be joined into the model name.
|
||||
// returns the provider along with the fields that remain.
|
||||
func splitProviderFlag(fields []string) (provider string, remaining []string) {
|
||||
for i := 0; i < len(fields); i++ {
|
||||
f := fields[i]
|
||||
@@ -103,21 +97,18 @@ func (g *Gateway) handleModelCommand(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
if router.Models == nil {
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || len(snap.Models) == 0 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Model switching is not configured.")
|
||||
return
|
||||
}
|
||||
|
||||
text := strings.TrimSpace(msg.Text)
|
||||
fields := strings.Fields(text)
|
||||
// fields[0] is "/model" (possibly with @bot mention); rest is everything
|
||||
// after it.
|
||||
rest := ""
|
||||
if len(fields) > 1 {
|
||||
// Reconstruct rest by joining everything after the command token.
|
||||
// We can't use strings.Join because fields splits by whitespace.
|
||||
cmdToken := fields[0]
|
||||
if _, after, ok := strings.Cut(text, cmdToken); ok {
|
||||
rest = strings.TrimSpace(after)
|
||||
@@ -128,28 +119,19 @@ func (g *Gateway) handleModelCommand(
|
||||
|
||||
// --refresh: no-op for now (catalog is loaded at startup). Show current.
|
||||
if refresh {
|
||||
active := router.Models.ActiveModel()
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
fmt.Sprintf("Active model: %s.", modelDisplayName(active, "")))
|
||||
fmt.Sprintf("Active model: %s.", modelDisplayName(snap.ActiveModel, "")))
|
||||
return
|
||||
}
|
||||
|
||||
// --provider without a specific model: switch provider only.
|
||||
if provider != "" && model == "" {
|
||||
manager, ok := router.Models.(gateway.ProviderModelManager)
|
||||
if !ok {
|
||||
models := snap.ModelsByProvider[provider]
|
||||
if len(models) == 0 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Provider switching is not configured.")
|
||||
return
|
||||
}
|
||||
if err := manager.SetActiveProvider(ctx, provider); err != nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
fmt.Sprintf("Cannot switch provider: %v", err))
|
||||
return
|
||||
}
|
||||
active := router.Models.ActiveModel()
|
||||
p, _, _ := strings.Cut(active, "/")
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
fmt.Sprintf("Provider changed to %s.", providerDisplayName(p)))
|
||||
g.switchModel(ctx, b, msg, client, models[0], global)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -162,12 +144,12 @@ func (g *Gateway) handleModelCommand(
|
||||
|
||||
// Switch model.
|
||||
if model != "" {
|
||||
g.switchModel(ctx, b, msg, router, model, global)
|
||||
g.switchModel(ctx, b, msg, client, model, global)
|
||||
return
|
||||
}
|
||||
|
||||
// Neither model nor provider: delegate to inline selector.
|
||||
g.sendModelSelector(ctx, b, msg, router)
|
||||
g.sendModelSelector(ctx, b, msg, client)
|
||||
}
|
||||
|
||||
// switchModel activates a model and sends confirmation. When global is true
|
||||
@@ -176,31 +158,31 @@ func (g *Gateway) switchModel(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
model string,
|
||||
global bool,
|
||||
) {
|
||||
if err := router.Models.SetActiveModel(ctx, model); err != nil {
|
||||
reply, err := client.Route(ctx, messaging.Inbound{
|
||||
Message: messaging.Message{
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
Text: "/model " + model,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
fmt.Sprintf("Cannot switch: %v", err))
|
||||
return
|
||||
}
|
||||
active := router.Models.ActiveModel()
|
||||
p, _, _ := strings.Cut(active, "/")
|
||||
result := fmt.Sprintf("Model changed to %s.", modelDisplayName(active, p))
|
||||
|
||||
if strings.HasPrefix(reply.Text, "Cannot switch") {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text)
|
||||
return
|
||||
}
|
||||
provider, _, _ := strings.Cut(model, "/")
|
||||
result := fmt.Sprintf("Model changed to %s.", modelDisplayName(model, provider))
|
||||
if global {
|
||||
if router.ModelPersist != nil {
|
||||
if err := router.ModelPersist(ctx, active); err != nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
fmt.Sprintf("Model switched to %s but persistence failed: %v",
|
||||
modelDisplayName(active, p), err))
|
||||
return
|
||||
}
|
||||
result += " (persisted globally)"
|
||||
} else {
|
||||
result += " (global persistence is not configured)"
|
||||
}
|
||||
result += " (global persistence is not configured)"
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, result)
|
||||
}
|
||||
@@ -209,24 +191,25 @@ func (g *Gateway) sendModelSelector(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
if router.Models == nil || len(router.Models.Models()) == 0 {
|
||||
reply, err := router.Route(ctx, gateway.Inbound{
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || len(snap.Models) == 0 {
|
||||
reply, err := client.Route(ctx, messaging.Inbound{
|
||||
Message: messaging.Message{Role: messaging.RoleUser, Text: "/model"},
|
||||
})
|
||||
if err != nil {
|
||||
g.log.Error("model selector fallback failed", "error", err)
|
||||
return
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text)
|
||||
return
|
||||
}
|
||||
|
||||
params := &bot.SendMessageParams{
|
||||
ChatID: msg.Chat.ID,
|
||||
Text: modelSelectorText(router.Models.ActiveModel()),
|
||||
ReplyMarkup: g.modelSelectorKeyboard(router.Models),
|
||||
Text: modelSelectorText(snap.ActiveModel),
|
||||
ReplyMarkup: g.modelSelectorKeyboard(snap.ActiveModel, snap.Models, snap.ActiveProvider, snap.ModelsByProvider),
|
||||
}
|
||||
if msg.MessageThreadID != 0 {
|
||||
params.MessageThreadID = msg.MessageThreadID
|
||||
@@ -254,24 +237,16 @@ func modelSelectorTextForProvider(provider string, page, count int) string {
|
||||
providerDisplayName(provider), start+1, end, count)
|
||||
}
|
||||
|
||||
func (g *Gateway) modelSelectorKeyboard(manager gateway.ModelManager) *models.InlineKeyboardMarkup {
|
||||
provider := ""
|
||||
if providerManager, ok := manager.(gateway.ProviderModelManager); ok {
|
||||
provider = providerManager.ActiveProvider()
|
||||
func (g *Gateway) modelSelectorKeyboard(active string, models []string, activeProvider string, modelsByProvider map[string][]string) *models.InlineKeyboardMarkup {
|
||||
provider := activeProvider
|
||||
available := models
|
||||
if provider != "" && len(modelsByProvider[provider]) > 0 {
|
||||
available = modelsByProvider[provider]
|
||||
}
|
||||
return g.modelSelectorKeyboardForProvider(manager, provider)
|
||||
return g.modelSelectorKeyboardPage(active, available, provider, 0)
|
||||
}
|
||||
|
||||
func (g *Gateway) modelSelectorKeyboardForProvider(manager gateway.ModelManager, provider string) *models.InlineKeyboardMarkup {
|
||||
return g.modelSelectorKeyboardPage(manager, provider, 0)
|
||||
}
|
||||
|
||||
func (g *Gateway) modelSelectorKeyboardPage(manager gateway.ModelManager, provider string, page int) *models.InlineKeyboardMarkup {
|
||||
active := manager.ActiveModel()
|
||||
available := manager.Models()
|
||||
if providerManager, ok := manager.(gateway.ProviderModelManager); ok {
|
||||
available = providerManager.ModelsForProvider(provider)
|
||||
}
|
||||
func (g *Gateway) modelSelectorKeyboardPage(active string, available []string, provider string, page int) *models.InlineKeyboardMarkup {
|
||||
start, end := pageBounds(page, len(available))
|
||||
buttons := make([]models.InlineKeyboardButton, 0, end-start)
|
||||
for _, model := range available[start:end] {
|
||||
@@ -336,13 +311,8 @@ func (g *Gateway) modelPageForCallback(token string) (modelPage, bool) {
|
||||
return page, ok
|
||||
}
|
||||
|
||||
// modelCallbackToken records a stable model identity for an inline button.
|
||||
// A positional index is unsafe: provider changes can reorder the selectable
|
||||
// list after Telegram has rendered the keyboard.
|
||||
func (g *Gateway) modelCallbackToken(model string) string {
|
||||
sum := sha256.Sum256([]byte(model))
|
||||
// 192 bits keeps the callback well below Telegram's 64-byte limit while
|
||||
// making a collision infeasible for a configured model catalog.
|
||||
token := fmt.Sprintf("%s%x", modelCallbackPrefix, sum[:24])
|
||||
g.modelMu.Lock()
|
||||
g.modelCallbacks[token] = model
|
||||
@@ -357,9 +327,6 @@ func (g *Gateway) modelForCallback(token string) (string, bool) {
|
||||
return model, ok
|
||||
}
|
||||
|
||||
// modelDisplayName removes routing/provider prefixes from a model reference.
|
||||
// The selected provider is already shown in the selector heading; repeating it
|
||||
// in every button makes provider-aware selection needlessly noisy.
|
||||
func modelDisplayName(ref, provider string) string {
|
||||
name := strings.TrimPrefix(ref, provider+"/")
|
||||
if slash := strings.LastIndexByte(name, '/'); slash >= 0 {
|
||||
@@ -372,7 +339,7 @@ func (g *Gateway) handleModelCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
update *models.Update,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
@@ -383,33 +350,39 @@ func (g *Gateway) handleModelCallback(
|
||||
g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
if router.Models == nil {
|
||||
g.answerModelCallback(ctx, b, query.ID, "Model switching is not configured.", true)
|
||||
return
|
||||
}
|
||||
|
||||
selected, ok := g.modelForCallback(query.Data)
|
||||
if !ok {
|
||||
g.answerModelCallback(ctx, b, query.ID, "That model selection is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
if err := router.Models.SetActiveModel(ctx, selected); err != nil {
|
||||
|
||||
reply, err := client.Route(ctx, messaging.Inbound{
|
||||
Message: messaging.Message{
|
||||
Role: messaging.RoleUser,
|
||||
Text: "/model " + selected,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
g.answerModelCallback(ctx, b, query.ID, fmt.Sprintf("Cannot switch: %v", err), true)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(reply.Text, "Cannot switch") {
|
||||
g.answerModelCallback(ctx, b, query.ID, reply.Text, true)
|
||||
return
|
||||
}
|
||||
|
||||
provider, _, _ := strings.Cut(selected, "/")
|
||||
g.answerModelCallback(ctx, b, query.ID,
|
||||
"The model has been changed to: "+modelDisplayName(selected, provider), false)
|
||||
g.editModelPicker(ctx, b, query, modelSelectionConfirmation(router.Models, selected), nil)
|
||||
g.editModelPicker(ctx, b, query, modelSelectionConfirmation(client, selected), nil)
|
||||
}
|
||||
|
||||
func modelSelectionConfirmation(manager gateway.ModelManager, ref string) string {
|
||||
func modelSelectionConfirmation(manager any, ref string) string {
|
||||
provider, _, _ := strings.Cut(ref, "/")
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "Model switched to %s\nProvider: %s",
|
||||
modelDisplayName(ref, provider), providerDisplayName(provider))
|
||||
detailed, ok := manager.(gateway.DetailedModelManager)
|
||||
detailed, ok := manager.(messaging.DetailedModelManager)
|
||||
if !ok {
|
||||
b.WriteString("\n\n_(active for this daemon process; resets on restart)_")
|
||||
return b.String()
|
||||
@@ -454,7 +427,7 @@ func (g *Gateway) handleModelPageCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
update *models.Update,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
@@ -464,8 +437,8 @@ func (g *Gateway) handleModelPageCallback(
|
||||
g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
manager, ok := router.Models.(gateway.ProviderModelManager)
|
||||
if !ok {
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || len(snap.Models) == 0 {
|
||||
g.answerModelCallback(ctx, b, query.ID, "Model switching is not configured.", true)
|
||||
return
|
||||
}
|
||||
@@ -474,22 +447,22 @@ func (g *Gateway) handleModelPageCallback(
|
||||
g.answerModelCallback(ctx, b, query.ID, "That model page is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
models := manager.ModelsForProvider(page.Provider)
|
||||
models := snap.ModelsByProvider[page.Provider]
|
||||
if page.Page < 0 || page.Page*modelPageSize >= len(models) {
|
||||
g.answerModelCallback(ctx, b, query.ID, "That model page is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
g.answerModelCallback(ctx, b, query.ID, "", false)
|
||||
g.editModelPicker(ctx, b, query,
|
||||
modelSelectorTextForProvider(page.Provider, page.Page, len(manager.ModelsForProvider(page.Provider))),
|
||||
g.modelSelectorKeyboardPage(manager, page.Provider, page.Page))
|
||||
modelSelectorTextForProvider(page.Provider, page.Page, len(models)),
|
||||
g.modelSelectorKeyboardPage(snap.ActiveModel, models, page.Provider, page.Page))
|
||||
}
|
||||
|
||||
func (g *Gateway) handleModelBackCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
update *models.Update,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
@@ -499,15 +472,15 @@ func (g *Gateway) handleModelBackCallback(
|
||||
g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
manager, ok := router.Models.(gateway.ProviderModelManager)
|
||||
if !ok {
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || len(snap.Providers) == 0 {
|
||||
g.answerModelCallback(ctx, b, query.ID, "Model switching is not configured.", true)
|
||||
return
|
||||
}
|
||||
g.answerModelCallback(ctx, b, query.ID, "", false)
|
||||
g.editModelPicker(ctx, b, query,
|
||||
providerSelectorText(manager.ActiveModel(), manager.ActiveProvider()),
|
||||
g.providerSelectorKeyboard(manager))
|
||||
providerSelectorText(snap.ActiveModel, snap.ActiveProvider),
|
||||
g.providerSelectorKeyboard(snap.ActiveProvider, snap.Providers, snap.ModelsByProvider))
|
||||
}
|
||||
|
||||
func (g *Gateway) handleModelCancelCallback(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
@@ -520,7 +493,21 @@ func (g *Gateway) handleModelCancelCallback(ctx context.Context, b *bot.Bot, upd
|
||||
return
|
||||
}
|
||||
g.answerModelCallback(ctx, b, query.ID, "", false)
|
||||
g.editModelPicker(ctx, b, query, "Model selection cancelled.", nil)
|
||||
params := &bot.EditMessageTextParams{
|
||||
Text: "Model selection cancelled.",
|
||||
}
|
||||
switch {
|
||||
case query.Message.Message != nil:
|
||||
params.ChatID = query.Message.Message.Chat.ID
|
||||
params.MessageID = query.Message.Message.ID
|
||||
case query.InlineMessageID != "":
|
||||
params.InlineMessageID = query.InlineMessageID
|
||||
default:
|
||||
return
|
||||
}
|
||||
if _, err := b.EditMessageText(ctx, params); err != nil {
|
||||
g.log.Warn("cancel model selector failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) handleModelNoopCallback(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
@@ -528,13 +515,20 @@ func (g *Gateway) handleModelNoopCallback(ctx context.Context, b *bot.Bot, updat
|
||||
if query == nil {
|
||||
return
|
||||
}
|
||||
if !g.isSenderAllowed(query.From.ID) {
|
||||
g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
g.answerModelCallback(ctx, b, query.ID, "", false)
|
||||
}
|
||||
|
||||
func (g *Gateway) answerModelCallback(ctx context.Context, b *bot.Bot, queryID, text string, alert bool) {
|
||||
params := &bot.AnswerCallbackQueryParams{
|
||||
CallbackQueryID: queryID,
|
||||
Text: text,
|
||||
ShowAlert: alert,
|
||||
}
|
||||
if _, err := b.AnswerCallbackQuery(ctx, params); err != nil {
|
||||
g.log.Warn("answer model callback query failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) editModelPicker(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
@@ -542,7 +536,9 @@ func (g *Gateway) editModelPicker(
|
||||
text string,
|
||||
markup *models.InlineKeyboardMarkup,
|
||||
) {
|
||||
params := &bot.EditMessageTextParams{Text: text}
|
||||
params := &bot.EditMessageTextParams{
|
||||
Text: text,
|
||||
}
|
||||
if markup != nil {
|
||||
params.ReplyMarkup = markup
|
||||
}
|
||||
@@ -556,22 +552,6 @@ func (g *Gateway) editModelPicker(
|
||||
return
|
||||
}
|
||||
if _, err := b.EditMessageText(ctx, params); err != nil {
|
||||
g.log.Warn("update model picker failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) answerModelCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
queryID string,
|
||||
text string,
|
||||
alert bool,
|
||||
) {
|
||||
if _, err := b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
|
||||
CallbackQueryID: queryID,
|
||||
Text: text,
|
||||
ShowAlert: alert,
|
||||
}); err != nil {
|
||||
g.log.Warn("answer model callback failed", "error", err)
|
||||
g.log.Warn("edit model picker failed", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type modelManagerStub struct {
|
||||
@@ -24,14 +24,50 @@ type modelManagerStub struct {
|
||||
|
||||
type detailedModelManagerStub struct {
|
||||
*modelManagerStub
|
||||
details map[string]gateway.ModelDetails
|
||||
details map[string]messaging.ModelDetails
|
||||
}
|
||||
|
||||
func (m *detailedModelManagerStub) ModelDetails(ref string) (gateway.ModelDetails, bool) {
|
||||
func (m *detailedModelManagerStub) ModelDetails(ref string) (messaging.ModelDetails, bool) {
|
||||
details, ok := m.details[ref]
|
||||
return details, ok
|
||||
}
|
||||
|
||||
func newTestChatFromManager(m *modelManagerStub) *fakeChatContract {
|
||||
if m == nil {
|
||||
return &fakeChatContract{}
|
||||
}
|
||||
modelsByProvider := make(map[string][]string)
|
||||
for _, p := range m.Providers() {
|
||||
modelsByProvider[p] = m.ModelsForProvider(p)
|
||||
}
|
||||
return &fakeChatContract{
|
||||
snapshot: messaging.ChatSnapshot{
|
||||
Models: m.Models(),
|
||||
ActiveModel: m.ActiveModel(),
|
||||
Providers: m.Providers(),
|
||||
ActiveProvider: m.ActiveProvider(),
|
||||
ModelsByProvider: modelsByProvider,
|
||||
},
|
||||
routeFunc: func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
||||
text := in.Message.Text
|
||||
if after, ok := strings.CutPrefix(text, "/model "); ok {
|
||||
ref := after
|
||||
if err := m.SetActiveModel(ctx, ref); err != nil {
|
||||
return messaging.ChatReply{Text: fmt.Sprintf("Cannot switch: %v", err)}, nil
|
||||
}
|
||||
return messaging.ChatReply{Text: fmt.Sprintf("Active model set to %s.", ref)}, nil
|
||||
}
|
||||
return messaging.ChatReply{Text: "ok"}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newTestChatFromDetailed(m *detailedModelManagerStub) *fakeChatContract {
|
||||
chat := newTestChatFromManager(m.modelManagerStub)
|
||||
chat.details = m.details
|
||||
return chat
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) Models() []string {
|
||||
return append([]string(nil), m.models...)
|
||||
}
|
||||
@@ -137,12 +173,11 @@ func TestModelCommandShowsInlineSelector(t *testing.T) {
|
||||
models: []string{"provider/alpha", "provider/beta", "other/gamma"},
|
||||
active: "provider/beta",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(chat)(context.Background(), b, &models.Update{
|
||||
Message: &models.Message{
|
||||
From: &models.User{ID: allowedUserID},
|
||||
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
|
||||
@@ -192,12 +227,11 @@ func TestModelCommandDrillsFromProviderIntoFilteredModels(t *testing.T) {
|
||||
},
|
||||
active: "openrouter/openai/gpt-5.6",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(chat)(context.Background(), b, &models.Update{
|
||||
Message: &models.Message{
|
||||
From: &models.User{ID: allowedUserID},
|
||||
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
|
||||
@@ -214,7 +248,7 @@ func TestModelCommandDrillsFromProviderIntoFilteredModels(t *testing.T) {
|
||||
|
||||
*requests = nil
|
||||
providerCallback := providerMarkup.InlineKeyboard[0][1].CallbackData
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(chat)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "provider-callback",
|
||||
From: models.User{ID: allowedUserID},
|
||||
@@ -276,7 +310,7 @@ func TestModelSelectorKeyboardPageAcrossModelCounts(t *testing.T) {
|
||||
}
|
||||
g := New("1:test", []int64{42}, slog.Default())
|
||||
|
||||
page := g.modelSelectorKeyboardPage(manager, "provider", 0)
|
||||
page := g.modelSelectorKeyboardPage(manager.ActiveModel(), manager.ModelsForProvider("provider"), "provider", 0)
|
||||
rows := page.InlineKeyboard
|
||||
if len(rows) == 0 {
|
||||
t.Fatalf("no rows returned for %d models", tt.count)
|
||||
@@ -327,14 +361,14 @@ func TestModelSelectorPageCallbackAdvancesToNextPage(t *testing.T) {
|
||||
}
|
||||
g := New("1:test", []int64{42}, slog.Default())
|
||||
|
||||
first := g.modelSelectorKeyboardPage(manager, "provider", 0)
|
||||
first := g.modelSelectorKeyboardPage(manager.ActiveModel(), manager.ModelsForProvider("provider"), "provider", 0)
|
||||
nav := first.InlineKeyboard[4]
|
||||
next, ok := g.modelPageForCallback(nav[1].CallbackData)
|
||||
if !ok {
|
||||
t.Fatal("next page callback was not recorded")
|
||||
}
|
||||
|
||||
second := g.modelSelectorKeyboardPage(manager, next.Provider, next.Page)
|
||||
second := g.modelSelectorKeyboardPage(manager.ActiveModel(), manager.ModelsForProvider(next.Provider), next.Provider, next.Page)
|
||||
if got := len(second.InlineKeyboard[0]); got != 1 {
|
||||
t.Fatalf("second page model row = %d buttons, want 1 (nine models, page size eight)", got)
|
||||
}
|
||||
@@ -347,7 +381,7 @@ func TestModelSelectionConfirmationIncludesCatalogMetadata(t *testing.T) {
|
||||
const ref = "google/gemini-3.6-flash"
|
||||
manager := &detailedModelManagerStub{
|
||||
modelManagerStub: &modelManagerStub{models: []string{ref}, active: ref},
|
||||
details: map[string]gateway.ModelDetails{
|
||||
details: map[string]messaging.ModelDetails{
|
||||
ref: {
|
||||
Ref: ref, ContextWindow: 1_048_576, MaxOutputTokens: 65_536,
|
||||
Reasoning: true, Tools: true, Structured: true,
|
||||
@@ -356,7 +390,7 @@ func TestModelSelectionConfirmationIncludesCatalogMetadata(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
got := modelSelectionConfirmation(manager, ref)
|
||||
got := modelSelectionConfirmation(newTestChatFromDetailed(manager), ref)
|
||||
for _, want := range []string{
|
||||
"Model switched to gemini-3.6-flash",
|
||||
"Provider: Google",
|
||||
@@ -377,12 +411,11 @@ func TestProviderCallbackHonoursTheProviderRenderedInTheSelector(t *testing.T) {
|
||||
models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"},
|
||||
active: "openai/gpt-5.6",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, _ := newTelegramTestBot(t)
|
||||
|
||||
markup := g.providerSelectorKeyboard(manager)
|
||||
markup := g.providerSelectorKeyboard(chat.snapshot.ActiveProvider, chat.snapshot.Providers, chat.snapshot.ModelsByProvider)
|
||||
renderedCallback := markup.InlineKeyboard[0][0].CallbackData
|
||||
manager.models = []string{"deepseek/deepseek-v4-pro", "openai/gpt-5.6", "openrouter/openai/gpt-5.6"}
|
||||
|
||||
@@ -390,7 +423,7 @@ func TestProviderCallbackHonoursTheProviderRenderedInTheSelector(t *testing.T) {
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: allowedUserID},
|
||||
Data: renderedCallback,
|
||||
}}, router)
|
||||
}}, chat)
|
||||
|
||||
if got := manager.ActiveProvider(); got != "openai" {
|
||||
t.Errorf("opening a provider page changed active provider to %q", got)
|
||||
@@ -403,12 +436,11 @@ func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) {
|
||||
models: []string{"provider/alpha", "provider/beta"},
|
||||
active: "provider/alpha",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(chat)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: allowedUserID},
|
||||
@@ -449,8 +481,7 @@ func TestDirectModelSelectionWithProviderIsAtomicOnFailure(t *testing.T) {
|
||||
models: []string{"openai/gpt-5.6", "anthropic/claude"},
|
||||
active: "openai/gpt-5.6",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, _ := newTelegramTestBot(t)
|
||||
|
||||
@@ -458,7 +489,7 @@ func TestDirectModelSelectionWithProviderIsAtomicOnFailure(t *testing.T) {
|
||||
From: &models.User{ID: allowedUserID},
|
||||
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
|
||||
Text: "/model missing --provider anthropic",
|
||||
}, router)
|
||||
}, chat)
|
||||
|
||||
if manager.active != "openai/gpt-5.6" {
|
||||
t.Fatalf("failed selection changed active model to %q", manager.active)
|
||||
@@ -470,7 +501,7 @@ func TestModelPageIndicatorCallbackIsAnswered(t *testing.T) {
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(gateway.NewRouter(nil, nil, "telegram"))(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(&fakeChatContract{})(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "noop-id", From: models.User{ID: allowedUserID}, Data: modelNoopCallback,
|
||||
},
|
||||
@@ -487,12 +518,11 @@ func TestModelCallbackHonoursTheModelRenderedInTheSelector(t *testing.T) {
|
||||
models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"},
|
||||
active: "openai/gpt-5.6",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, _ := newTelegramTestBot(t)
|
||||
|
||||
markup := g.modelSelectorKeyboard(manager)
|
||||
markup := g.modelSelectorKeyboard(chat.snapshot.ActiveModel, chat.snapshot.Models, chat.snapshot.ActiveProvider, chat.snapshot.ModelsByProvider)
|
||||
renderedCallback := markup.InlineKeyboard[0][0].CallbackData
|
||||
if err := manager.SetActiveProvider(context.Background(), "openrouter"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -502,7 +532,7 @@ func TestModelCallbackHonoursTheModelRenderedInTheSelector(t *testing.T) {
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: allowedUserID},
|
||||
Data: renderedCallback,
|
||||
}}, router)
|
||||
}}, chat)
|
||||
|
||||
if got := manager.ActiveModel(); got != "openai/gpt-5.6" {
|
||||
t.Errorf("stale selector chose %q, want the originally rendered model", got)
|
||||
@@ -526,12 +556,11 @@ func TestModelCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) {
|
||||
models: []string{"provider/alpha", "provider/beta"},
|
||||
active: "provider/alpha",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(chat)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: tt.userID},
|
||||
@@ -572,12 +601,11 @@ func TestProviderCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T)
|
||||
models: []string{"openrouter/openai/gpt-5.6", "openai/gpt-5.6"},
|
||||
active: "openrouter/openai/gpt-5.6",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
chat := newTestChatFromManager(manager)
|
||||
g := New("1:test", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
g.defaultHandler(chat)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: tt.userID},
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
const personalityCallbackPrefix = "personality:"
|
||||
@@ -26,9 +26,10 @@ func (g *Gateway) handlePersonalityCommand(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
if router.Personas == nil {
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || !snap.PersonasAvailable {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
"Personality switching is not configured.")
|
||||
return
|
||||
@@ -38,13 +39,14 @@ func (g *Gateway) handlePersonalityCommand(
|
||||
fields := strings.Fields(text)
|
||||
if len(fields) == 1 {
|
||||
// No args: show inline keyboard.
|
||||
g.sendPersonalitySelector(ctx, b, msg, router)
|
||||
g.sendPersonalitySelector(ctx, b, msg, snap.Personas)
|
||||
return
|
||||
}
|
||||
|
||||
// Direct switch by name.
|
||||
name := strings.ToLower(fields[1])
|
||||
if !router.Personas.SetActive("", name) {
|
||||
ok, err := client.SetPersona(ctx, "", name)
|
||||
if err != nil || !ok {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
fmt.Sprintf("Unknown personality %q. Use /personality to browse.", name))
|
||||
return
|
||||
@@ -57,10 +59,9 @@ func (g *Gateway) sendPersonalitySelector(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
personas []string,
|
||||
) {
|
||||
names := router.Personas.List()
|
||||
if len(names) == 0 {
|
||||
if len(personas) == 0 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
"No personalities configured.")
|
||||
return
|
||||
@@ -69,7 +70,7 @@ func (g *Gateway) sendPersonalitySelector(
|
||||
params := &bot.SendMessageParams{
|
||||
ChatID: msg.Chat.ID,
|
||||
Text: "Choose a personality:",
|
||||
ReplyMarkup: g.personalityKeyboard(router.Personas),
|
||||
ReplyMarkup: g.personalityKeyboard(personas),
|
||||
}
|
||||
if msg.MessageThreadID != 0 {
|
||||
params.MessageThreadID = msg.MessageThreadID
|
||||
@@ -79,10 +80,9 @@ func (g *Gateway) sendPersonalitySelector(
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) personalityKeyboard(registry *gateway.PersonaRegistry) *models.InlineKeyboardMarkup {
|
||||
names := registry.List()
|
||||
rows := make([][]models.InlineKeyboardButton, 0, len(names))
|
||||
for _, name := range names {
|
||||
func (g *Gateway) personalityKeyboard(personas []string) *models.InlineKeyboardMarkup {
|
||||
rows := make([][]models.InlineKeyboardButton, 0, len(personas))
|
||||
for _, name := range personas {
|
||||
rows = append(rows, []models.InlineKeyboardButton{{
|
||||
Text: name,
|
||||
CallbackData: personalityCallbackPrefix + name,
|
||||
@@ -95,7 +95,7 @@ func (g *Gateway) handlePersonalityCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
update *models.Update,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
@@ -108,14 +108,16 @@ func (g *Gateway) handlePersonalityCallback(
|
||||
"You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
if router.Personas == nil {
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || !snap.PersonasAvailable {
|
||||
g.answerModelCallback(ctx, b, query.ID,
|
||||
"Personality switching is not configured.", true)
|
||||
return
|
||||
}
|
||||
|
||||
name := strings.TrimPrefix(query.Data, personalityCallbackPrefix)
|
||||
if !router.Personas.SetActive("", name) {
|
||||
ok, err := client.SetPersona(ctx, "", name)
|
||||
if err != nil || !ok {
|
||||
g.answerModelCallback(ctx, b, query.ID,
|
||||
fmt.Sprintf("Unknown personality %q.", name), true)
|
||||
return
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
const providerCallbackPrefix = "provider:"
|
||||
@@ -18,17 +18,17 @@ func (g *Gateway) sendProviderSelector(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
manager, ok := router.Models.(gateway.ProviderModelManager)
|
||||
if !ok || len(manager.Providers()) == 0 {
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || len(snap.Providers) == 0 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Provider switching is not configured.")
|
||||
return
|
||||
}
|
||||
params := &bot.SendMessageParams{
|
||||
ChatID: msg.Chat.ID,
|
||||
Text: providerSelectorText(manager.ActiveModel(), manager.ActiveProvider()),
|
||||
ReplyMarkup: g.providerSelectorKeyboard(manager),
|
||||
Text: providerSelectorText(snap.ActiveModel, snap.ActiveProvider),
|
||||
ReplyMarkup: g.providerSelectorKeyboard(snap.ActiveProvider, snap.Providers, snap.ModelsByProvider),
|
||||
}
|
||||
if msg.MessageThreadID != 0 {
|
||||
params.MessageThreadID = msg.MessageThreadID
|
||||
@@ -45,12 +45,11 @@ func providerSelectorText(activeModel, activeProvider string) string {
|
||||
"\n\nSelect a provider:"
|
||||
}
|
||||
|
||||
func (g *Gateway) providerSelectorKeyboard(manager gateway.ProviderModelManager) *models.InlineKeyboardMarkup {
|
||||
active := manager.ActiveProvider()
|
||||
providers := manager.Providers()
|
||||
func (g *Gateway) providerSelectorKeyboard(active string, providers []string, modelsByProvider map[string][]string) *models.InlineKeyboardMarkup {
|
||||
buttons := make([]models.InlineKeyboardButton, 0, len(providers))
|
||||
for _, provider := range providers {
|
||||
label := fmt.Sprintf("%s (%d)", providerName(manager, provider), len(manager.ModelsForProvider(provider)))
|
||||
count := len(modelsByProvider[provider])
|
||||
label := fmt.Sprintf("%s (%d)", providerDisplayName(provider), count)
|
||||
if provider == active {
|
||||
label = "✓ " + label
|
||||
}
|
||||
@@ -70,15 +69,6 @@ func (g *Gateway) providerSelectorKeyboard(manager gateway.ProviderModelManager)
|
||||
return &models.InlineKeyboardMarkup{InlineKeyboard: rows}
|
||||
}
|
||||
|
||||
func providerName(manager gateway.ModelManager, provider string) string {
|
||||
if namer, ok := manager.(gateway.ProviderDisplayNamer); ok {
|
||||
if name := strings.TrimSpace(namer.ProviderDisplayName(provider)); name != "" {
|
||||
return name
|
||||
}
|
||||
}
|
||||
return providerDisplayName(provider)
|
||||
}
|
||||
|
||||
func (g *Gateway) providerCallbackToken(provider string) string {
|
||||
sum := sha256.Sum256([]byte(provider))
|
||||
token := fmt.Sprintf("%s%x", providerCallbackPrefix, sum[:24])
|
||||
@@ -118,7 +108,7 @@ func (g *Gateway) handleProviderCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
update *models.Update,
|
||||
router *gateway.Router,
|
||||
client messaging.ChatContract,
|
||||
) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
@@ -129,8 +119,8 @@ func (g *Gateway) handleProviderCallback(
|
||||
g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
manager, ok := router.Models.(gateway.ProviderModelManager)
|
||||
if !ok {
|
||||
snap, err := client.Snapshot(ctx)
|
||||
if err != nil || len(snap.Providers) == 0 {
|
||||
g.answerModelCallback(ctx, b, query.ID, "Provider switching is not configured.", true)
|
||||
return
|
||||
}
|
||||
@@ -139,24 +129,26 @@ func (g *Gateway) handleProviderCallback(
|
||||
g.answerModelCallback(ctx, b, query.ID, "That provider selection is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
if len(manager.ModelsForProvider(selected)) == 0 {
|
||||
providerModels := snap.ModelsByProvider[selected]
|
||||
if len(providerModels) == 0 {
|
||||
g.answerModelCallback(ctx, b, query.ID, "That provider has no selectable models.", true)
|
||||
return
|
||||
}
|
||||
g.answerModelCallback(ctx, b, query.ID, "", false)
|
||||
g.updateModelSelectorForProvider(ctx, b, query, manager, selected)
|
||||
g.updateModelSelectorForProvider(ctx, b, query, snap.ActiveModel, providerModels, selected)
|
||||
}
|
||||
|
||||
func (g *Gateway) updateModelSelectorForProvider(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
query *models.CallbackQuery,
|
||||
manager gateway.ProviderModelManager,
|
||||
activeModel string,
|
||||
providerModels []string,
|
||||
provider string,
|
||||
) {
|
||||
params := &bot.EditMessageTextParams{
|
||||
Text: modelSelectorTextForProvider(provider, 0, len(manager.ModelsForProvider(provider))),
|
||||
ReplyMarkup: g.modelSelectorKeyboardForProvider(manager, provider),
|
||||
Text: modelSelectorTextForProvider(provider, 0, len(providerModels)),
|
||||
ReplyMarkup: g.modelSelectorKeyboardPage(activeModel, providerModels, provider, 0),
|
||||
}
|
||||
switch {
|
||||
case query.Message.Message != nil:
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
@@ -106,7 +105,7 @@ type Gateway struct {
|
||||
// turns serialises chat turns per session off the update worker and
|
||||
// makes the running one cancellable by /stop. Rebuilt on every launch
|
||||
// so a restart abandons in-flight turns with the old bot instance.
|
||||
turns *gateway.Turns
|
||||
turns *messaging.Turns
|
||||
|
||||
// liveMu guards liveReplies and liveStopped.
|
||||
liveMu sync.Mutex
|
||||
@@ -202,7 +201,7 @@ func (g *Gateway) RequestRestart() error {
|
||||
// Restarts are scoped to this gateway. The daemon keeps running, so
|
||||
// in-flight agent tasks are untouched -- the whole point of the escape
|
||||
// hatch is to recover chat without disturbing work in progress.
|
||||
func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) error {
|
||||
func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) error {
|
||||
if g.Token == "" {
|
||||
return fmt.Errorf("telegram bot token is required")
|
||||
}
|
||||
@@ -211,7 +210,7 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle g
|
||||
for {
|
||||
lifecycle.ReportStarting()
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
b, err := g.launch(runCtx, router, lifecycle)
|
||||
b, err := g.launch(runCtx, client, lifecycle)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return err
|
||||
@@ -246,25 +245,25 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle g
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) registerCommandHandlers(b *bot.Bot, router *gateway.Router) {
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypeExact, g.statusHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/whoami", bot.MatchTypeExact, g.whoamiHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/profile", bot.MatchTypeExact, g.profileHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/sessions", bot.MatchTypeExact, g.sessionsHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/resume", bot.MatchTypeExact, g.resumeHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/agents", bot.MatchTypeExact, g.agentsHandler(router))
|
||||
func (g *Gateway) registerCommandHandlers(b *bot.Bot, client messaging.ChatContract) {
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypeExact, g.statusHandler(client))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/whoami", bot.MatchTypeExact, g.whoamiHandler(client))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/profile", bot.MatchTypeExact, g.profileHandler(client))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/sessions", bot.MatchTypeExact, g.sessionsHandler(client))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/resume", bot.MatchTypeExact, g.resumeHandler(client))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/agents", bot.MatchTypeExact, g.agentsHandler(client))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/version", bot.MatchTypeExact, g.versionHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/update", bot.MatchTypeExact, g.updateHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, g.helpHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypeExact, g.restartHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/rollback", bot.MatchTypePrefix, g.rollbackHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/stop", bot.MatchTypePrefix, g.stopHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/stop", bot.MatchTypePrefix, g.stopHandler(client))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/approve", bot.MatchTypeExact, g.approveHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/deny", bot.MatchTypeExact, g.denyHandler())
|
||||
}
|
||||
|
||||
func (g *Gateway) startListening(ctx context.Context, b *bot.Bot, _ gateway.Lifecycle) error {
|
||||
func (g *Gateway) startListening(ctx context.Context, b *bot.Bot, _ channels.Lifecycle) error {
|
||||
g.dropPendingUpdates(ctx, b)
|
||||
g.running = true
|
||||
go b.Start(ctx)
|
||||
@@ -274,11 +273,11 @@ func (g *Gateway) startListening(ctx context.Context, b *bot.Bot, _ gateway.Life
|
||||
// launch builds one bot instance, registers handlers and starts its
|
||||
// long-poll delivery worker. Readiness is reported by pollReadinessClient
|
||||
// after the first successful getUpdates response.
|
||||
func (g *Gateway) launch(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) (*bot.Bot, error) {
|
||||
func (g *Gateway) launch(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) (*bot.Bot, error) {
|
||||
// Turns are per-launch. Each queued turn carries the update handler's
|
||||
// context, which is this launch's, so a /restart cancels everything
|
||||
// still running under the outgoing bot instance.
|
||||
g.turns = gateway.NewTurns(g.log)
|
||||
g.turns = messaging.NewTurns(g.log)
|
||||
g.resetLiveRegistry()
|
||||
|
||||
opts := []bot.Option{
|
||||
@@ -286,7 +285,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router, lifecycle
|
||||
bot.WithDebugHandler(func(format string, args ...any) {
|
||||
g.log.Debug("telegram debug", "message", fmt.Sprintf(format, args...))
|
||||
}),
|
||||
bot.WithDefaultHandler(g.defaultHandler(router)),
|
||||
bot.WithDefaultHandler(g.defaultHandler(client)),
|
||||
bot.WithMiddlewares(g.panicRecoveryMiddleware(), g.updateLoggingMiddleware()),
|
||||
bot.WithHTTPClient(telegramPollTimeout, &pollReadinessClient{
|
||||
client: &http.Client{Timeout: telegramPollTimeout},
|
||||
@@ -303,7 +302,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router, lifecycle
|
||||
}
|
||||
g.bot = b
|
||||
|
||||
g.registerCommandHandlers(b, router)
|
||||
g.registerCommandHandlers(b, client)
|
||||
|
||||
// Publish the command list so Telegram renders a menu. Without this
|
||||
// the commands are undiscoverable and the LLM, having no idea they
|
||||
@@ -381,33 +380,33 @@ func (g *Gateway) Stop(ctx context.Context) error {
|
||||
|
||||
// ── command handlers (gateway-local -- no LLM) ────────────────
|
||||
|
||||
func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(router, "/status")
|
||||
func (g *Gateway) statusHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(client, "/status")
|
||||
}
|
||||
|
||||
func (g *Gateway) whoamiHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(router, "/whoami")
|
||||
func (g *Gateway) whoamiHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(client, "/whoami")
|
||||
}
|
||||
|
||||
func (g *Gateway) profileHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(router, "/profile")
|
||||
func (g *Gateway) profileHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(client, "/profile")
|
||||
}
|
||||
|
||||
func (g *Gateway) sessionsHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(router, "/sessions")
|
||||
func (g *Gateway) sessionsHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(client, "/sessions")
|
||||
}
|
||||
|
||||
func (g *Gateway) agentsHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(router, "/agents")
|
||||
func (g *Gateway) agentsHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return g.routeCmdHandler(client, "/agents")
|
||||
}
|
||||
|
||||
func (g *Gateway) resumeHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
func (g *Gateway) resumeHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reply, err := router.Route(ctx, gateway.Inbound{Message: messaging.Message{
|
||||
reply, err := client.Route(ctx, messaging.Inbound{Message: messaging.Message{
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
@@ -417,19 +416,19 @@ func (g *Gateway) resumeHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
g.log.Error("resume handler failed", "error", err)
|
||||
return
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text)
|
||||
}
|
||||
}
|
||||
|
||||
// routeCmdHandler builds a handler that routes a fixed command through the
|
||||
// gateway.Router and sends the reply.
|
||||
func (g *Gateway) routeCmdHandler(router *gateway.Router, cmd string) bot.HandlerFunc {
|
||||
// messaging.ChatContract and sends the reply.
|
||||
func (g *Gateway) routeCmdHandler(client messaging.ChatContract, cmd string) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reply, err := router.Route(ctx, gateway.Inbound{Message: messaging.Message{
|
||||
reply, err := client.Route(ctx, messaging.Inbound{Message: messaging.Message{
|
||||
ConversationID: conversationID(msg),
|
||||
Sender: msg.From.Username,
|
||||
Role: messaging.RoleUser,
|
||||
@@ -439,7 +438,7 @@ func (g *Gateway) routeCmdHandler(router *gateway.Router, cmd string) bot.Handle
|
||||
g.log.Error("command handler failed", "command", cmd, "error", err)
|
||||
return
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,10 +479,10 @@ func (g *Gateway) startHandler() bot.HandlerFunc {
|
||||
|
||||
// ── default handler (non-command text → router) ─────────────
|
||||
|
||||
func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
func (g *Gateway) defaultHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
if update.CallbackQuery != nil {
|
||||
g.handleCallback(ctx, b, update, router)
|
||||
g.handleCallback(ctx, b, update, client)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -492,44 +491,44 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return
|
||||
}
|
||||
if isModelSelectorRequest(msg.Text) {
|
||||
g.sendProviderSelector(ctx, b, msg, router)
|
||||
g.sendProviderSelector(ctx, b, msg, client)
|
||||
return
|
||||
}
|
||||
if isModelCommand(msg.Text) {
|
||||
g.handleModelCommand(ctx, b, msg, router)
|
||||
g.handleModelCommand(ctx, b, msg, client)
|
||||
return
|
||||
}
|
||||
if isPersonalityRequest(msg.Text) {
|
||||
g.handlePersonalityCommand(ctx, b, msg, router)
|
||||
g.handlePersonalityCommand(ctx, b, msg, client)
|
||||
return
|
||||
}
|
||||
g.submitTurn(ctx, b, msg, router)
|
||||
g.submitTurn(ctx, b, msg, client)
|
||||
}
|
||||
}
|
||||
|
||||
// handleCallback dispatches an inline-button callback query to the handler
|
||||
// for its prefix. Callback prefixes are mutually exclusive; an unknown
|
||||
// callback is ignored.
|
||||
func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models.Update, router *gateway.Router) {
|
||||
func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models.Update, client messaging.ChatContract) {
|
||||
switch {
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, approvalCallbackPrefix):
|
||||
g.handleApprovalCallback(ctx, b, update)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, dangerousCmdPrefix):
|
||||
g.handleDangerousCallback(ctx, b, update)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix):
|
||||
g.handleProviderCallback(ctx, b, update, router)
|
||||
g.handleProviderCallback(ctx, b, update, client)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix):
|
||||
g.handleModelCallback(ctx, b, update, router)
|
||||
g.handleModelCallback(ctx, b, update, client)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, modelPageCallbackPrefix):
|
||||
g.handleModelPageCallback(ctx, b, update, router)
|
||||
g.handleModelPageCallback(ctx, b, update, client)
|
||||
case update.CallbackQuery.Data == modelBackCallback:
|
||||
g.handleModelBackCallback(ctx, b, update, router)
|
||||
g.handleModelBackCallback(ctx, b, update, client)
|
||||
case update.CallbackQuery.Data == modelCancelCallback:
|
||||
g.handleModelCancelCallback(ctx, b, update)
|
||||
case update.CallbackQuery.Data == modelNoopCallback:
|
||||
g.handleModelNoopCallback(ctx, b, update)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, personalityCallbackPrefix):
|
||||
g.handlePersonalityCallback(ctx, b, update, router)
|
||||
g.handlePersonalityCallback(ctx, b, update, client)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix):
|
||||
g.handleUpdateCallback(ctx, b, update)
|
||||
}
|
||||
@@ -543,8 +542,8 @@ func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models
|
||||
// running here would block delivery of every later update -- including the
|
||||
// /stop meant to cancel it, which would sit unread until the turn it was
|
||||
// aimed at had already finished.
|
||||
func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, router *gateway.Router) {
|
||||
gm := gateway.Inbound{Message: messaging.Message{
|
||||
func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
|
||||
gm := messaging.Inbound{Message: messaging.Message{
|
||||
// Telegram's message ID makes persistence idempotent: the store
|
||||
// derives a canonical ID from it, so a redelivered update is a
|
||||
// no-op rather than appending a duplicate or overwriting the
|
||||
@@ -561,30 +560,49 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag
|
||||
|
||||
// The lane key must be the session, so that /stop -- which resolves
|
||||
// the same key -- reaches the turn the sender is actually watching.
|
||||
session, err := router.ResolveSessionKey(ctx, gm)
|
||||
if err != nil {
|
||||
g.log.Error("resolve session for turn", "error", err)
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "❌ Could not resolve this conversation's session.")
|
||||
return
|
||||
}
|
||||
|
||||
session := conversationID(msg).String()
|
||||
chatID, threadID := msg.Chat.ID, msg.MessageThreadID
|
||||
g.turns.Submit(ctx, session, func(turnCtx context.Context) {
|
||||
// If the turn invokes a tool that requires human approval,
|
||||
// the dispatch layer blocks on this approver. Nil is fine
|
||||
// — most turns need no gating.
|
||||
approver := g.NewApprover(b, chatID, threadID, msg.From.ID)
|
||||
turnCtx = gateway.WithApprovalRequester(turnCtx, approver)
|
||||
turnCtx = messaging.WithApprovalRequester(turnCtx, approver)
|
||||
|
||||
// reply appears as it is written; the typing indicator covers the
|
||||
// gap before the first token and any non-streaming path.
|
||||
stopTyping := g.startTyping(turnCtx, b, chatID, threadID)
|
||||
live := g.newLiveReply(turnCtx, b, chatID, threadID, g.ShowToolCalls())
|
||||
|
||||
// If it starts with / but wasn't matched by a registered
|
||||
// handler, it's unknown -- let the router handle it (which
|
||||
// will say "unrecognized").
|
||||
reply, err := router.RouteStream(turnCtx, gm, live)
|
||||
events, err := client.Stream(turnCtx, gm)
|
||||
if err != nil {
|
||||
stopTyping()
|
||||
if errors.Is(err, context.Canceled) || errors.Is(turnCtx.Err(), context.Canceled) {
|
||||
g.log.Info("chat turn stopped", "session", session)
|
||||
live.abandon(turnCtx)
|
||||
} else {
|
||||
g.log.Error("stream failed", "error", err)
|
||||
live.abandonFailed(turnCtx)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var reply string
|
||||
var streamErr error
|
||||
for ev := range events {
|
||||
switch ev.Kind {
|
||||
case "delta":
|
||||
live.Delta(ev.Text)
|
||||
case "tool":
|
||||
live.ToolCall(ev.Tool)
|
||||
case "media":
|
||||
live.Media(turnCtx, ev.Media)
|
||||
case "done":
|
||||
reply = ev.Text
|
||||
case "error":
|
||||
streamErr = errors.New(ev.Text)
|
||||
}
|
||||
}
|
||||
stopTyping()
|
||||
|
||||
// A cancelled turn is a /stop, not a fault. The stop handler has
|
||||
@@ -601,12 +619,12 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag
|
||||
// partial: /stop is an acknowledged interruption, a provider error
|
||||
// is not, and an unmarked partial reads as a finished answer either
|
||||
// way.
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
if streamErr != nil || turnCtx.Err() != nil {
|
||||
if errors.Is(turnCtx.Err(), context.Canceled) || (streamErr != nil && errors.Is(streamErr, context.Canceled)) {
|
||||
g.log.Info("chat turn stopped", "session", session)
|
||||
live.abandon(turnCtx)
|
||||
} else {
|
||||
g.log.Error("route failed", "error", err)
|
||||
g.log.Error("stream turn failed", "error", streamErr)
|
||||
live.abandonFailed(turnCtx)
|
||||
}
|
||||
return
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
)
|
||||
|
||||
func TestName(t *testing.T) {
|
||||
@@ -228,11 +228,11 @@ func TestSenderAllowlistFailsClosed(t *testing.T) {
|
||||
|
||||
func TestStartWithoutToken(t *testing.T) {
|
||||
g := New("", nil, slog.Default())
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
chat := &fakeChatContract{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
called := false
|
||||
if err := g.Start(ctx, router, gateway.Lifecycle{Running: func() { called = true }}); err == nil {
|
||||
if err := g.Start(ctx, chat, channels.Lifecycle{Running: func() { called = true }}); err == nil {
|
||||
t.Error("expected error when starting without token")
|
||||
}
|
||||
if called {
|
||||
@@ -266,7 +266,7 @@ func TestStartReportsRunningAfterLaunch(t *testing.T) {
|
||||
started := make(chan bool, 1)
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- g.Start(ctx, gateway.NewRouter(nil, nil, "telegram"), gateway.Lifecycle{
|
||||
errCh <- g.Start(ctx, &fakeChatContract{}, channels.Lifecycle{
|
||||
Running: func() { started <- g.running },
|
||||
})
|
||||
}()
|
||||
@@ -313,7 +313,7 @@ func TestStartReportsStartingOnRestart(t *testing.T) {
|
||||
events := make(chan string, 4)
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- g.Start(ctx, gateway.NewRouter(nil, nil, "telegram"), gateway.Lifecycle{
|
||||
errCh <- g.Start(ctx, &fakeChatContract{}, channels.Lifecycle{
|
||||
Starting: func() { events <- "starting" },
|
||||
Running: func() { events <- "running" },
|
||||
})
|
||||
@@ -363,7 +363,7 @@ func TestStartAndStopLifecycle(t *testing.T) {
|
||||
// we test what we can: ensure Start fails predictably when the API
|
||||
// rejects us, rather than trying to mock the full Bot API wire
|
||||
// protocol.
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
chat := &fakeChatContract{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
@@ -372,7 +372,7 @@ func TestStartAndStopLifecycle(t *testing.T) {
|
||||
// and our test server doesn't return a valid User object.
|
||||
// The point: we exercise the Start/Stop path; accept either
|
||||
// success or failure.
|
||||
_ = g.Start(ctx, router, gateway.Lifecycle{})
|
||||
_ = g.Start(ctx, chat, channels.Lifecycle{})
|
||||
// Best-effort stop -- don't assert on Start result since we can't
|
||||
// fully mock the Bot API without the library supporting a base URL
|
||||
// override.
|
||||
@@ -383,11 +383,11 @@ func TestStartAndStopLifecycle(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Compile-time guard: Gateway implements gateway.Gateway.
|
||||
// Compile-time guard: Gateway implements channels.Channel.
|
||||
var (
|
||||
_ gateway.Gateway = (*Gateway)(nil)
|
||||
_ = (*bot.Bot)(nil)
|
||||
_ = models.Update{}
|
||||
_ channels.Channel = (*Gateway)(nil)
|
||||
_ = (*bot.Bot)(nil)
|
||||
_ = models.Update{}
|
||||
)
|
||||
|
||||
// ── Regression tests for previously untested paths ────────────────────
|
||||
@@ -618,7 +618,7 @@ func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) {
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
if _, err := g.launch(ctx, nil, gateway.Lifecycle{}); err != nil {
|
||||
if _, err := g.launch(ctx, &fakeChatContract{}, channels.Lifecycle{}); err != nil {
|
||||
t.Fatalf("launch() error = %v", err)
|
||||
}
|
||||
cancel()
|
||||
|
||||
@@ -18,13 +18,12 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
// Gateway is a deliver-only webhook gateway. It listens for HTTP POST
|
||||
// requests, validates their HMAC signatures, and routes the extracted
|
||||
// text through the gateway.Router for LLM processing.
|
||||
// text through the messaging ChatContract for LLM processing.
|
||||
type Gateway struct {
|
||||
Host string
|
||||
Port int
|
||||
@@ -32,7 +31,7 @@ type Gateway struct {
|
||||
log *slog.Logger
|
||||
|
||||
server *http.Server
|
||||
router *gateway.Router
|
||||
client messaging.ChatContract
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
@@ -68,10 +67,10 @@ func (g *Gateway) Name() string { return "webhook" }
|
||||
|
||||
// Start begins listening on the configured host:port. Blocks until ctx
|
||||
// is cancelled.
|
||||
func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) error {
|
||||
func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) error {
|
||||
lifecycle.ReportStarting()
|
||||
g.mu.Lock()
|
||||
g.router = router
|
||||
g.client = client
|
||||
|
||||
mux := http.NewServeMux()
|
||||
for i := range g.Routes {
|
||||
@@ -108,12 +107,12 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router, lifecycle g
|
||||
// Stop gracefully shuts down the HTTP server.
|
||||
func (g *Gateway) Stop(ctx context.Context) error {
|
||||
g.mu.Lock()
|
||||
srv := g.server
|
||||
server := g.server
|
||||
g.mu.Unlock()
|
||||
if srv == nil {
|
||||
if server == nil {
|
||||
return nil
|
||||
}
|
||||
return srv.Shutdown(ctx)
|
||||
return server.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// WebhookHandler returns the HTTP handler for testing.
|
||||
@@ -126,6 +125,7 @@ func (g *Gateway) WebhookHandler() http.Handler {
|
||||
return mux
|
||||
}
|
||||
|
||||
// handleWebhook returns an http.HandlerFunc for one route.
|
||||
func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
@@ -160,17 +160,17 @@ func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// Route through the gateway.
|
||||
// Route through the chat contract.
|
||||
g.mu.Lock()
|
||||
router := g.router
|
||||
client := g.client
|
||||
g.mu.Unlock()
|
||||
|
||||
if router == nil {
|
||||
if client == nil {
|
||||
http.Error(w, "not started", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
msg := gateway.Inbound{Message: messaging.Message{
|
||||
msg := messaging.Inbound{Message: messaging.Message{
|
||||
ConversationID: messaging.ConversationID{ChannelID: route.Path},
|
||||
Sender: "webhook",
|
||||
// Webhooks have no per-caller identity; the configured route
|
||||
@@ -180,16 +180,16 @@ func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc {
|
||||
Role: messaging.RoleUser,
|
||||
Text: text,
|
||||
}}
|
||||
reply, err := router.Route(r.Context(), msg)
|
||||
reply, err := client.Route(r.Context(), msg)
|
||||
if err != nil {
|
||||
g.log.Error("webhook route", "err", err, "path", route.Path)
|
||||
http.Error(w, "route error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if route.DeliverTo == "origin" && reply != "" {
|
||||
if route.DeliverTo == "origin" && reply.Text != "" {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
_, _ = w.Write([]byte(reply))
|
||||
_, _ = w.Write([]byte(reply.Text))
|
||||
} else {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
|
||||
@@ -13,9 +13,22 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type fakeChatContract struct {
|
||||
messaging.ChatContract
|
||||
routeFunc func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error)
|
||||
}
|
||||
|
||||
func (f *fakeChatContract) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
||||
if f.routeFunc != nil {
|
||||
return f.routeFunc(ctx, in)
|
||||
}
|
||||
return messaging.ChatReply{Text: "ok"}, nil
|
||||
}
|
||||
|
||||
func TestName(t *testing.T) {
|
||||
g := New("", 0, nil, slog.Default())
|
||||
if g.Name() != "webhook" {
|
||||
@@ -23,12 +36,6 @@ func TestName(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// HMAC signature verification itself is now internal/webhookguard.VerifyHMAC
|
||||
// and tested there; TestWebhookHandlerValidSignature and
|
||||
// TestWebhookHandlerInvalidSignature below cover this package's own
|
||||
// responsibility -- that the handler actually calls it and reacts correctly
|
||||
// to the result.
|
||||
|
||||
func TestExtractText(t *testing.T) {
|
||||
body := []byte(`{"issue":{"title":"fix bug","body":"details"}}`)
|
||||
|
||||
@@ -81,10 +88,12 @@ func TestWebhookHandlerRoute(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
g := New("", 0, []RouteConfig{{Path: "/hook"}}, log)
|
||||
var gotSenderID string
|
||||
g.router = gateway.NewRouter(nil, func(ctx context.Context, in gateway.Inbound) (string, error) {
|
||||
gotSenderID = in.Message.SenderID
|
||||
return "ok", nil
|
||||
}, "webhook")
|
||||
g.client = &fakeChatContract{
|
||||
routeFunc: func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
||||
gotSenderID = in.Message.SenderID
|
||||
return messaging.ChatReply{Text: "ok"}, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := g.WebhookHandler()
|
||||
payload := `{"text":"hello from webhook"}`
|
||||
@@ -102,7 +111,7 @@ func TestWebhookHandlerRoute(t *testing.T) {
|
||||
|
||||
func TestWebhookHandlerInvalidSignature(t *testing.T) {
|
||||
g := New("", 0, []RouteConfig{{Path: "/hook", Secret: "secret"}}, slog.Default())
|
||||
g.router = gateway.NewRouter(nil, nil, "webhook")
|
||||
g.client = &fakeChatContract{}
|
||||
|
||||
handler := g.WebhookHandler()
|
||||
rec := httptest.NewRecorder()
|
||||
@@ -120,7 +129,7 @@ func TestWebhookHandlerValidSignature(t *testing.T) {
|
||||
sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))
|
||||
|
||||
g := New("", 0, []RouteConfig{{Path: "/hook", Secret: secret}}, slog.Default())
|
||||
g.router = gateway.NewRouter(nil, nil, "webhook")
|
||||
g.client = &fakeChatContract{}
|
||||
|
||||
handler := g.WebhookHandler()
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/hook", strings.NewReader(string(body)))
|
||||
@@ -140,8 +149,8 @@ func TestWebhookStartStop(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
router := gateway.NewRouter(nil, nil, "webhook")
|
||||
go func() { _ = g.Start(ctx, router, gateway.Lifecycle{}) }()
|
||||
client := &fakeChatContract{}
|
||||
go func() { _ = g.Start(ctx, client, channels.Lifecycle{}) }()
|
||||
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
_ = g.Stop(context.Background())
|
||||
@@ -159,4 +168,4 @@ func TestExtractTextJSONRoundTrip(t *testing.T) {
|
||||
}
|
||||
|
||||
// Compile-time guard.
|
||||
var _ gateway.Gateway = (*Gateway)(nil)
|
||||
var _ channels.Channel = (*Gateway)(nil)
|
||||
@@ -679,6 +679,7 @@ type SnapshotResponse struct {
|
||||
RestartAvailable bool `protobuf:"varint,9,opt,name=restart_available,json=restartAvailable,proto3" json:"restart_available,omitempty"`
|
||||
CancellationAvailable bool `protobuf:"varint,10,opt,name=cancellation_available,json=cancellationAvailable,proto3" json:"cancellation_available,omitempty"`
|
||||
PersonasAvailable bool `protobuf:"varint,11,opt,name=personas_available,json=personasAvailable,proto3" json:"personas_available,omitempty"`
|
||||
Version string `protobuf:"bytes,12,opt,name=version,proto3" json:"version,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -790,6 +791,13 @@ func (x *SnapshotResponse) GetPersonasAvailable() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *SnapshotResponse) GetVersion() string {
|
||||
if x != nil {
|
||||
return x.Version
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type GetSessionRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
|
||||
@@ -2811,7 +2819,7 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"StringList\x12\x16\n" +
|
||||
"\x06values\x18\x01 \x03(\tR\x06values\"\x11\n" +
|
||||
"\x0fSnapshotRequest\"\xd1\x05\n" +
|
||||
"\x0fSnapshotRequest\"\xeb\x05\n" +
|
||||
"\x10SnapshotResponse\x12/\n" +
|
||||
"\bsessions\x18\x01 \x03(\v2\x13.gateway.v1.SessionR\bsessions\x12\x16\n" +
|
||||
"\x06models\x18\x02 \x03(\tR\x06models\x12`\n" +
|
||||
@@ -2824,7 +2832,8 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
|
||||
"\x11restart_available\x18\t \x01(\bR\x10restartAvailable\x125\n" +
|
||||
"\x16cancellation_available\x18\n" +
|
||||
" \x01(\bR\x15cancellationAvailable\x12-\n" +
|
||||
"\x12personas_available\x18\v \x01(\bR\x11personasAvailable\x1a[\n" +
|
||||
"\x12personas_available\x18\v \x01(\bR\x11personasAvailable\x12\x18\n" +
|
||||
"\aversion\x18\f \x01(\tR\aversion\x1a[\n" +
|
||||
"\x15ModelsByProviderEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12,\n" +
|
||||
"\x05value\x18\x02 \x01(\v2\x16.gateway.v1.StringListR\x05value:\x028\x01\x1aA\n" +
|
||||
|
||||
@@ -228,8 +228,11 @@ type Task struct {
|
||||
BindingVersion int64 `protobuf:"varint,24,opt,name=binding_version,json=bindingVersion,proto3" json:"binding_version,omitempty"`
|
||||
CreatedAt *timestamppb.Timestamp `protobuf:"bytes,25,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"`
|
||||
UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,26,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
// review_payload is the JSON-encoded review unit the remediate workflow's
|
||||
// current run must address (docs/prds/pr-review-remediation.md decision 4).
|
||||
ReviewPayload string `protobuf:"bytes,27,opt,name=review_payload,json=reviewPayload,proto3" json:"review_payload,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Task) Reset() {
|
||||
@@ -444,6 +447,13 @@ func (x *Task) GetUpdatedAt() *timestamppb.Timestamp {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Task) GetReviewPayload() string {
|
||||
if x != nil {
|
||||
return x.ReviewPayload
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Event mirrors internal/events.Event. Data is carried as a JSON object
|
||||
// string (matching the store's own on-disk representation) rather than
|
||||
// google.protobuf.Struct, to stay a direct mirror of the existing column.
|
||||
@@ -5819,7 +5829,7 @@ const file_state_v1_state_proto_rawDesc = "" +
|
||||
"\x19RegisterTaskGrantResponse\".\n" +
|
||||
"\x16RevokeTaskGrantRequest\x12\x14\n" +
|
||||
"\x05token\x18\x01 \x01(\tR\x05token\"\x19\n" +
|
||||
"\x17RevokeTaskGrantResponse\"\x87\x06\n" +
|
||||
"\x17RevokeTaskGrantResponse\"\xae\x06\n" +
|
||||
"\x04Task\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" +
|
||||
"\x05owner\x18\x02 \x01(\tR\x05owner\x12\x12\n" +
|
||||
@@ -5855,7 +5865,8 @@ const file_state_v1_state_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"created_at\x18\x19 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x129\n" +
|
||||
"\n" +
|
||||
"updated_at\x18\x1a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\x9b\x02\n" +
|
||||
"updated_at\x18\x1a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\x12%\n" +
|
||||
"\x0ereview_payload\x18\x1b \x01(\tR\rreviewPayload\"\x9b\x02\n" +
|
||||
"\x05Event\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x12*\n" +
|
||||
"\x02at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x12\n" +
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ApprovalRequester asks a human to approve or deny a named action.
|
||||
type ApprovalRequester interface {
|
||||
RequestApproval(ctx context.Context, action, description string) (ApprovalDecision, error)
|
||||
}
|
||||
|
||||
// ApprovalDecision is the outcome of a human consent request.
|
||||
type ApprovalDecision int
|
||||
|
||||
const (
|
||||
// ApprovalApproved means the human approved this one execution.
|
||||
ApprovalApproved ApprovalDecision = iota
|
||||
|
||||
// ApprovalPermanentlyApproved means the human approved this action
|
||||
// for the lifetime of the session.
|
||||
ApprovalPermanentlyApproved
|
||||
|
||||
// ApprovalDenied means the human explicitly refused.
|
||||
ApprovalDenied
|
||||
)
|
||||
|
||||
// ErrApprovalDenied is returned when the human refuses the action.
|
||||
var ErrApprovalDenied = errors.New("approval denied")
|
||||
|
||||
// ErrApprovalNotConfigured is returned when a tool requires approval but no
|
||||
// ApprovalRequester is wired.
|
||||
var ErrApprovalNotConfigured = errors.New("approval is not configured")
|
||||
|
||||
// ToolApprovalTimeout bounds how long dispatch waits for a human to act.
|
||||
const ToolApprovalTimeout = 2 * time.Minute
|
||||
|
||||
type approvalCtxKey struct{}
|
||||
|
||||
// WithApprovalRequester stores an ApprovalRequester on ctx.
|
||||
func WithApprovalRequester(ctx context.Context, a ApprovalRequester) context.Context {
|
||||
return context.WithValue(ctx, approvalCtxKey{}, a)
|
||||
}
|
||||
|
||||
// ApprovalFromContext returns the ApprovalRequester stored on ctx.
|
||||
func ApprovalFromContext(ctx context.Context) ApprovalRequester {
|
||||
a, _ := ctx.Value(approvalCtxKey{}).(ApprovalRequester)
|
||||
return a
|
||||
}
|
||||
@@ -3,14 +3,18 @@ package messaging
|
||||
// ChatSnapshot is what Snapshot returns: the full chat state a dashboard
|
||||
// renders in one read.
|
||||
type ChatSnapshot struct {
|
||||
Sessions []SessionContext
|
||||
Models []string
|
||||
ModelsByProvider map[string][]string
|
||||
Providers []string
|
||||
ActiveModel string
|
||||
ActiveProvider string
|
||||
Personas []string
|
||||
ActivePersonas map[string]string
|
||||
Sessions []SessionContext
|
||||
Models []string
|
||||
ModelsByProvider map[string][]string
|
||||
Providers []string
|
||||
ActiveModel string
|
||||
ActiveProvider string
|
||||
Personas []string
|
||||
ActivePersonas map[string]string
|
||||
// Version is the Gateway's rendered component-version block. Channel
|
||||
// frontends display it rather than stamping their own build, so a
|
||||
// partially upgraded deployment cannot report itself as matched.
|
||||
Version string
|
||||
RestartAvailable bool
|
||||
CancellationAvailable bool
|
||||
PersonasAvailable bool
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package messaging
|
||||
|
||||
// Lifecycle receives adapter-owned startup facts. Callbacks are optional.
|
||||
// Starting is reported before each launch attempt; Running is reported only
|
||||
// after the adapter's external delivery boundary is ready.
|
||||
type Lifecycle struct {
|
||||
Starting func()
|
||||
Running func()
|
||||
}
|
||||
|
||||
func (l Lifecycle) ReportStarting() {
|
||||
if l.Starting != nil {
|
||||
l.Starting()
|
||||
}
|
||||
}
|
||||
|
||||
func (l Lifecycle) ReportRunning() {
|
||||
if l.Running != nil {
|
||||
l.Running()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package messaging
|
||||
|
||||
import "context"
|
||||
|
||||
// SendResult captures the outcome of a platform media delivery.
|
||||
type SendResult struct {
|
||||
MessageID string
|
||||
Success bool
|
||||
Retryable bool
|
||||
Error error
|
||||
ErrorCode string
|
||||
}
|
||||
|
||||
// AdapterCapabilities reports which optional delivery behaviors a sender
|
||||
// implements.
|
||||
type AdapterCapabilities struct {
|
||||
Media bool
|
||||
}
|
||||
|
||||
// MediaSender delivers a MessageEvent carrying MediaAttachments through a
|
||||
// platform-specific media API.
|
||||
type MediaSender interface {
|
||||
SendMedia(ctx context.Context, event MessageEvent) (SendResult, error)
|
||||
}
|
||||
|
||||
// CapabilityReporter is the optional interface a sender implements to
|
||||
// self-report which optional behaviors it supports.
|
||||
type CapabilityReporter interface {
|
||||
Capabilities() AdapterCapabilities
|
||||
}
|
||||
|
||||
// CapabilitiesOf reports which optional behaviors sender supports.
|
||||
func CapabilitiesOf(sender any) AdapterCapabilities {
|
||||
if reporter, ok := sender.(CapabilityReporter); ok {
|
||||
return reporter.Capabilities()
|
||||
}
|
||||
return AdapterCapabilities{}
|
||||
}
|
||||
@@ -21,6 +21,13 @@ type ConversationID struct {
|
||||
ThreadID string
|
||||
}
|
||||
|
||||
func (c ConversationID) String() string {
|
||||
if c.ThreadID == "" {
|
||||
return c.ChannelID
|
||||
}
|
||||
return c.ChannelID + "/" + c.ThreadID
|
||||
}
|
||||
|
||||
// MessageID is the canonical, immutable identifier for a Message. Once
|
||||
// assigned it never changes, including across branch and fork operations —
|
||||
// a forked transcript references the original MessageID it branched from
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package messaging
|
||||
|
||||
// MessageType discriminates inbound gateway messages.
|
||||
type MessageType string
|
||||
|
||||
const (
|
||||
MsgText MessageType = "text"
|
||||
MsgImage MessageType = "image"
|
||||
MsgAudio MessageType = "audio"
|
||||
MsgVideo MessageType = "video"
|
||||
MsgDocument MessageType = "document"
|
||||
MsgLocation MessageType = "location"
|
||||
MsgContact MessageType = "contact"
|
||||
MsgSticker MessageType = "sticker"
|
||||
MsgReaction MessageType = "reaction"
|
||||
MsgCallback MessageType = "callback"
|
||||
MsgEdited MessageType = "edited"
|
||||
MsgDeleted MessageType = "deleted"
|
||||
MsgSystem MessageType = "system"
|
||||
)
|
||||
|
||||
// IsMedia reports whether the type carries a media attachment.
|
||||
func (t MessageType) IsMedia() bool {
|
||||
switch t {
|
||||
case MsgImage, MsgVideo, MsgAudio, MsgDocument, MsgSticker:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsEphemeral reports whether the type is a transient signal.
|
||||
func (t MessageType) IsEphemeral() bool {
|
||||
switch t {
|
||||
case MsgReaction, MsgDeleted:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsRich reports whether the type requires a MessageEvent with
|
||||
// structured fields rather than a plain text fallback.
|
||||
func (t MessageType) IsRich() bool {
|
||||
switch t {
|
||||
case MsgText:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// MessageEvent is the rich message model for gateway channels.
|
||||
type MessageEvent struct {
|
||||
Type MessageType `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
ChannelID string `json:"channel_id"`
|
||||
Platform string `json:"platform"`
|
||||
SenderID string `json:"sender_id"`
|
||||
SenderName string `json:"sender_name,omitempty"`
|
||||
ReplyToID string `json:"reply_to_id,omitempty"`
|
||||
ThreadID string `json:"thread_id,omitempty"`
|
||||
Media []MediaAttachment `json:"media,omitempty"`
|
||||
EditedFrom string `json:"edited_from,omitempty"`
|
||||
Reaction string `json:"reaction,omitempty"`
|
||||
ReactedToID string `json:"reacted_to_id,omitempty"`
|
||||
CallbackData string `json:"callback_data,omitempty"`
|
||||
Timestamp int64 `json:"timestamp,omitempty"`
|
||||
Raw map[string]any `json:"raw,omitempty"`
|
||||
}
|
||||
|
||||
// FromID returns the sender identifier.
|
||||
func (e MessageEvent) FromID() string { return e.SenderID }
|
||||
@@ -0,0 +1,20 @@
|
||||
package messaging
|
||||
|
||||
// ModelDetails carries read-only catalog metadata for one model reference.
|
||||
type ModelDetails struct {
|
||||
Ref string `json:"ref"`
|
||||
Name string `json:"name,omitempty"`
|
||||
ContextWindow int `json:"context_window,omitempty"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
Reasoning bool `json:"reasoning,omitempty"`
|
||||
Tools bool `json:"tools,omitempty"`
|
||||
Structured bool `json:"structured,omitempty"`
|
||||
InputModalities []string `json:"input_modalities,omitempty"`
|
||||
Attachment bool `json:"attachment,omitempty"`
|
||||
}
|
||||
|
||||
// DetailedModelManager optionally enriches model selection confirmation with
|
||||
// catalog metadata such as context window and modalities.
|
||||
type DetailedModelManager interface {
|
||||
ModelDetails(ref string) (ModelDetails, bool)
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
const (
|
||||
toolParametersMaxRunes = 120
|
||||
redactedParameterValue = "[redacted]"
|
||||
)
|
||||
|
||||
// RenderToolCall returns the channel-neutral compact representation used by
|
||||
// chat surfaces. Parameters are intentionally omitted: JSON/schema-shaped
|
||||
// inputs are noisy, often contain secrets, and are not useful progress text.
|
||||
func RenderToolCall(e ToolCallEvent) string {
|
||||
if limit, ok := legacyTurnBudgetLimit(e.Err); ok {
|
||||
return toolProgressBlock("tools", "stopped", fmt.Sprintf("tool-output limit reached (%s chars); further results suppressed", limit))
|
||||
}
|
||||
if line := cleanToolError(e.Name, e.Err); line != "" {
|
||||
return toolProgressBlock(e.Name, "failed", line)
|
||||
}
|
||||
return toolProgressBlock(e.Name, "done", toolPreview(e.Name, e.Output))
|
||||
}
|
||||
|
||||
// FailureKey identifies equivalent tool calls for channel adapters that
|
||||
// collapse repeated activity.
|
||||
func FailureKey(e ToolCallEvent) string {
|
||||
if _, ok := legacyTurnBudgetLimit(e.Err); ok {
|
||||
return "legacy-turn-output-limit"
|
||||
}
|
||||
if line := cleanToolError(e.Name, e.Err); line != "" {
|
||||
return strings.TrimSpace(e.Name) + "\x00" + line
|
||||
}
|
||||
return "success\x00" + strings.TrimSpace(e.Name) + "\x00" + toolPreview(e.Name, e.Output)
|
||||
}
|
||||
|
||||
func toolProgressBlock(name, status, preview string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
name = "tool"
|
||||
}
|
||||
preview = strings.ReplaceAll(strings.TrimSpace(preview), "```", "''' ")
|
||||
if preview == "" {
|
||||
preview = "completed"
|
||||
}
|
||||
return "🔧 " + name + " — " + status + "\n```text\n" + truncateRunes(preview, 180) + "\n```"
|
||||
}
|
||||
|
||||
func toolPreview(name, output string) string {
|
||||
content, _ := unwrapToolContent(output)
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return "completed"
|
||||
}
|
||||
if summary, ok := toolNoticeSummary(content); ok {
|
||||
return summary
|
||||
}
|
||||
if isSearchTool(name) {
|
||||
if summary, ok := searchResultSummary(content); ok {
|
||||
return summary
|
||||
}
|
||||
}
|
||||
preview := firstInformativeLine(content)
|
||||
if preview == "" {
|
||||
return "completed with no printable preview"
|
||||
}
|
||||
return preview
|
||||
}
|
||||
|
||||
var searchToolNames = map[string]bool{
|
||||
"grep": true,
|
||||
"rg": true,
|
||||
"search": true,
|
||||
"toolsearch": true,
|
||||
}
|
||||
|
||||
func isSearchTool(name string) bool {
|
||||
return searchToolNames[strings.ToLower(strings.TrimSpace(name))]
|
||||
}
|
||||
|
||||
func toolNoticeSummary(content string) (string, bool) {
|
||||
for line := range strings.SplitSeq(content, "\n") {
|
||||
notice, ok := parseTruncationNotice(strings.TrimSpace(line))
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if notice.total <= notice.shown {
|
||||
continue
|
||||
}
|
||||
if notice.truncatedHead {
|
||||
return fmt.Sprintf("%d lines total; showing last %d", notice.total, notice.shown), true
|
||||
}
|
||||
return fmt.Sprintf("%d lines total; showing %d", notice.total, notice.shown), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
type truncationNotice struct {
|
||||
shown int
|
||||
total int
|
||||
truncatedHead bool
|
||||
}
|
||||
|
||||
func parseTruncationNotice(line string) (truncationNotice, bool) {
|
||||
_, rest, found := strings.Cut(line, "[truncated: ")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
_, rest, found = strings.Cut(rest, "showing ")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
truncatedHead := false
|
||||
if after, ok := strings.CutPrefix(rest, "last "); ok {
|
||||
rest, truncatedHead = after, true
|
||||
}
|
||||
counts, _, found := strings.Cut(rest, " lines")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
left, right, found := strings.Cut(counts, "/")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
shown, errShown := strconv.Atoi(strings.TrimSpace(left))
|
||||
total, errTotal := strconv.Atoi(strings.TrimSpace(right))
|
||||
if errShown != nil || errTotal != nil {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
return truncationNotice{shown: shown, total: total, truncatedHead: truncatedHead}, true
|
||||
}
|
||||
|
||||
func searchResultSummary(content string) (string, bool) {
|
||||
matches := countSearchMatches(content)
|
||||
if matches == 0 {
|
||||
return "", false
|
||||
}
|
||||
return fmt.Sprintf("%d %s", matches, pluralize(matches, "match", "matches")), true
|
||||
}
|
||||
|
||||
func countSearchMatches(content string) int {
|
||||
matches := 0
|
||||
for line := range strings.SplitSeq(content, "\n") {
|
||||
if isSearchMatchLine(strings.TrimSpace(line)) {
|
||||
matches++
|
||||
}
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
func isSearchMatchLine(line string) bool {
|
||||
if line == "" || strings.HasPrefix(line, "[") {
|
||||
return false
|
||||
}
|
||||
if strings.Trim(line, "-") == "" {
|
||||
return false
|
||||
}
|
||||
for i := len(line) - 1; i > 0; i-- {
|
||||
if line[i] != ':' {
|
||||
continue
|
||||
}
|
||||
digits := line[i+1:]
|
||||
end := 0
|
||||
for end < len(digits) && digits[end] >= '0' && digits[end] <= '9' {
|
||||
end++
|
||||
}
|
||||
if end > 0 && end < len(digits) && digits[end] == ':' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func firstInformativeLine(content string) string {
|
||||
for line := range strings.SplitSeq(content, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(line, "/pkg/mod/") {
|
||||
continue
|
||||
}
|
||||
if _, ok := parseTruncationNotice(line); ok {
|
||||
continue
|
||||
}
|
||||
return truncateRunes(line, 120)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func pluralize(n int, one, many string) string {
|
||||
if n == 1 {
|
||||
return one
|
||||
}
|
||||
return many
|
||||
}
|
||||
|
||||
func unwrapToolContent(output string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(output)
|
||||
if trimmed == "" {
|
||||
return "", false
|
||||
}
|
||||
var envelope struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if json.Unmarshal([]byte(trimmed), &envelope) == nil && envelope.Content != "" {
|
||||
return envelope.Content, true
|
||||
}
|
||||
var quoted string
|
||||
if json.Unmarshal([]byte(trimmed), "ed) == nil {
|
||||
return quoted, true
|
||||
}
|
||||
return output, false
|
||||
}
|
||||
|
||||
func cleanToolError(name, raw string) string {
|
||||
line := firstNonEmptyLine(raw)
|
||||
prefix := "tool " + strings.TrimSpace(name) + ": "
|
||||
line = strings.TrimPrefix(line, prefix)
|
||||
return truncateRunes(strings.TrimSpace(line), toolSummaryMaxRunes)
|
||||
}
|
||||
|
||||
func legacyTurnBudgetLimit(raw string) (string, bool) {
|
||||
const marker = "turn budget exceeded ("
|
||||
_, after, ok := strings.Cut(raw, marker)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
rest := after
|
||||
end := strings.Index(rest, " chars)")
|
||||
if end < 1 {
|
||||
return "", false
|
||||
}
|
||||
return rest[:end], true
|
||||
}
|
||||
|
||||
// SummarizeToolParameters returns a bounded JSON shape of tool input.
|
||||
func SummarizeToolParameters(input string) string {
|
||||
if strings.TrimSpace(input) == "" {
|
||||
return ""
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(input))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return "[unavailable]"
|
||||
}
|
||||
value = redactToolParameters(value, false)
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "[unavailable]"
|
||||
}
|
||||
return truncateRunesWithinLimit(string(encoded), toolParametersMaxRunes)
|
||||
}
|
||||
|
||||
func redactToolParameters(value any, sensitive bool) any {
|
||||
if sensitive {
|
||||
return redactedParameterValue
|
||||
}
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range typed {
|
||||
typed[key] = redactToolParameters(child, sensitiveParameterKey(key))
|
||||
}
|
||||
return typed
|
||||
case []any:
|
||||
for i, child := range typed {
|
||||
typed[i] = redactToolParameters(child, sensitive)
|
||||
}
|
||||
return typed
|
||||
case string:
|
||||
return "[string]"
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
func sensitiveParameterKey(key string) bool {
|
||||
normalized := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(key))
|
||||
for _, marker := range webhookguard.SensitiveKeyMarkers {
|
||||
if strings.Contains(normalized, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func truncateRunesWithinLimit(s string, limit int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= limit {
|
||||
return s
|
||||
}
|
||||
if limit <= 1 {
|
||||
return "…"
|
||||
}
|
||||
return string(runes[:limit-1]) + "…"
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
func TestRedactionConsumersShareMarkerSet(t *testing.T) {
|
||||
if len(webhookguard.SensitiveKeyMarkers) == 0 {
|
||||
t.Fatal("webhookguard.SensitiveKeyMarkers is empty, want a non-empty shared set")
|
||||
}
|
||||
for _, marker := range webhookguard.SensitiveKeyMarkers {
|
||||
if !sensitiveParameterKey(marker) {
|
||||
t.Errorf("sensitiveParameterKey(%q) = false, want true (shared marker set)", marker)
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{marker: "secret"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := webhookguard.RedactPayload(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("RedactPayload(%q): %v", marker, err)
|
||||
}
|
||||
if string(got) == string(payload) {
|
||||
t.Errorf("webhookguard did not redact shared marker key %q", marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeToolParameters(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{name: "empty", input: "", want: ""},
|
||||
{name: "compact object", input: `{ "path": "/tmp/file", "line": 2 }`, want: `{"line":2,"path":"[string]"}`},
|
||||
{name: "nested secrets", input: `{"headers":{"Authorization":"Bearer secret"},"api-token":"secret","safe":"visible"}`, want: `{"api-token":"[redacted]","headers":{"Authorization":"[redacted]"},"safe":"[string]"}`},
|
||||
{name: "secret embedded in ordinary value", input: `{"command":"curl -H 'Authorization: Bearer secret'"}`, want: `{"command":"[string]"}`},
|
||||
{name: "secret in array", input: `[{"password":"secret"}]`, want: `[{"password":"[redacted]"}]`},
|
||||
{name: "non-string secret", input: `{"password":123456,"token":true}`, want: `{"password":"[redacted]","token":"[redacted]"}`},
|
||||
{name: "nested value under sensitive key", input: `{"credentials":{"user":"archie","password":"secret"}}`, want: `{"credentials":"[redacted]"}`},
|
||||
{name: "invalid JSON", input: `token=secret`, want: "[unavailable]"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := SummarizeToolParameters(tc.input); got != tc.want {
|
||||
t.Fatalf("SummarizeToolParameters() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
got := SummarizeToolParameters(`{"value":[` + strings.Repeat("0,", toolParametersMaxRunes) + `0]}`)
|
||||
if len([]rune(got)) != toolParametersMaxRunes {
|
||||
t.Fatalf("bounded summary is %d runes, want %d", len([]rune(got)), toolParametersMaxRunes)
|
||||
}
|
||||
if !strings.HasSuffix(got, "…") {
|
||||
t.Fatalf("bounded summary = %q, want ellipsis", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolCallEventSummary(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
event ToolCallEvent
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "single line output is the summary",
|
||||
event: ToolCallEvent{Name: "memory_edit", Output: "added entry"},
|
||||
want: "added entry",
|
||||
},
|
||||
{
|
||||
name: "only the first non-empty line is kept",
|
||||
event: ToolCallEvent{Name: "read", Output: "\n\nfirst line\nsecond line"},
|
||||
want: "first line",
|
||||
},
|
||||
{
|
||||
name: "surrounding whitespace is trimmed",
|
||||
event: ToolCallEvent{Name: "shell", Output: " exit 0 \n"},
|
||||
want: "exit 0",
|
||||
},
|
||||
{
|
||||
name: "an error replaces the output",
|
||||
event: ToolCallEvent{Name: "shell", Output: "partial", Err: "exit status 2"},
|
||||
want: "failed: exit status 2",
|
||||
},
|
||||
{
|
||||
name: "a multi-line error is reduced the same way",
|
||||
event: ToolCallEvent{Name: "shell", Err: "exit status 2\nstack trace"},
|
||||
want: "failed: exit status 2",
|
||||
},
|
||||
{
|
||||
name: "no output at all still reads as a completed call",
|
||||
event: ToolCallEvent{Name: "write"},
|
||||
want: "done",
|
||||
},
|
||||
{
|
||||
name: "whitespace-only output reads as a completed call",
|
||||
event: ToolCallEvent{Name: "write", Output: " \n "},
|
||||
want: "done",
|
||||
},
|
||||
{
|
||||
name: "a long line is truncated with an ellipsis",
|
||||
event: ToolCallEvent{Name: "grep", Output: strings.Repeat("x", toolSummaryMaxRunes+10)},
|
||||
want: strings.Repeat("x", toolSummaryMaxRunes) + "…",
|
||||
},
|
||||
{
|
||||
name: "truncation counts runes, not bytes",
|
||||
event: ToolCallEvent{Name: "grep", Output: strings.Repeat("é", toolSummaryMaxRunes+10)},
|
||||
want: strings.Repeat("é", toolSummaryMaxRunes) + "…",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := tc.event.Summary(); got != tc.want {
|
||||
t.Fatalf("Summary() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Turns serialises chat turns per session and keeps the running turn
|
||||
// cancellable.
|
||||
//
|
||||
// Channel event loops are typically single-threaded -- go-telegram/bot,
|
||||
// for one, runs a single worker that calls handlers synchronously. Running
|
||||
// a turn on that goroutine blocks delivery of every subsequent update,
|
||||
// including the command meant to stop it: /stop would sit unread in the
|
||||
// update channel until the turn it was meant to kill had already finished.
|
||||
//
|
||||
// Submitting to Turns hands the work to a per-session goroutine and returns
|
||||
// immediately, so the event loop stays free and control commands are always
|
||||
// serviceable. Ordering is preserved by the lane being serial, not by the
|
||||
// event loop being blocked.
|
||||
//
|
||||
// Queues are unbounded and never shed. A dropped message is a silent
|
||||
// failure that surfaces much later as an agent that ignored something,
|
||||
// which costs far more to diagnose than the memory a backlog occupies.
|
||||
// [Turns.Stop] is the way a backlog is cleared -- deliberately, by the
|
||||
// person who created it.
|
||||
type Turns struct {
|
||||
log *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
lanes map[string]*lane
|
||||
}
|
||||
|
||||
// queued is one pending turn: the work, already bound to its own
|
||||
// cancellable context, and the cancel that releases it.
|
||||
//
|
||||
// The context is derived when the turn is submitted rather than when it
|
||||
// starts running, which means a turn has a live cancel handle for its whole
|
||||
// time in the backlog. Stop can therefore cancel queued turns rather than
|
||||
// merely dropping them, and each turn stays tied to the caller that asked
|
||||
// for it -- it dies when that caller's context does.
|
||||
type queued struct {
|
||||
run func()
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// lane is one session's serial worker.
|
||||
//
|
||||
// A single mutex guards the backlog, the running turn's cancel, and whether
|
||||
// a worker is live, so that Stop observes them together. Splitting them
|
||||
// would leave a window where a turn finishes between the backlog being
|
||||
// cleared and the cancel being called, letting a queued turn start after a
|
||||
// stop.
|
||||
type lane struct {
|
||||
mu sync.Mutex
|
||||
pending []queued
|
||||
// cancel stops the turn currently running in this lane. It is nil
|
||||
// whenever the lane is idle.
|
||||
cancel context.CancelFunc
|
||||
// working reports whether a worker goroutine is draining this lane.
|
||||
// The worker exits when the backlog empties, so this is what tells
|
||||
// Submit whether to start a new one.
|
||||
working bool
|
||||
}
|
||||
|
||||
// NewTurns returns an idle dispatcher.
|
||||
func NewTurns(log *slog.Logger) *Turns {
|
||||
return &Turns{log: log, lanes: make(map[string]*lane)}
|
||||
}
|
||||
|
||||
// Submit schedules run for the given session and returns without waiting
|
||||
// for it. run receives a context derived from ctx that [Turns.Stop] can
|
||||
// cancel.
|
||||
//
|
||||
// Submit never blocks and never rejects: messages queue.
|
||||
func (t *Turns) Submit(ctx context.Context, session string, run func(context.Context)) {
|
||||
turnCtx, cancel := context.WithCancel(ctx)
|
||||
|
||||
t.mu.Lock()
|
||||
l, ok := t.lanes[session]
|
||||
if !ok {
|
||||
l = &lane{}
|
||||
t.lanes[session] = l
|
||||
}
|
||||
l.mu.Lock()
|
||||
l.pending = append(l.pending, queued{run: func() { run(turnCtx) }, cancel: cancel})
|
||||
depth := len(l.pending)
|
||||
start := !l.working
|
||||
if start {
|
||||
l.working = true
|
||||
}
|
||||
l.mu.Unlock()
|
||||
t.mu.Unlock()
|
||||
|
||||
if start {
|
||||
go t.serve(session, l)
|
||||
}
|
||||
if depth > 1 {
|
||||
t.log.Info("chat turn queued", "session", session, "queue_depth", depth)
|
||||
}
|
||||
}
|
||||
|
||||
// Stop cancels the session's running turn and discards everything queued
|
||||
// behind it. It reports whether a turn was actually cancelled and how many
|
||||
// queued turns were dropped.
|
||||
//
|
||||
// Dropping the queue is intentional. "Stop" means stop, not "stop this one
|
||||
// and immediately begin the next thing I said" -- starting the queued turn
|
||||
// would look to the sender exactly like the stop had failed.
|
||||
func (t *Turns) Stop(session string) (cancelled bool, dropped int) {
|
||||
l := t.lane(session)
|
||||
if l == nil {
|
||||
return false, 0
|
||||
}
|
||||
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
dropped = len(l.pending)
|
||||
for i, q := range l.pending {
|
||||
q.cancel()
|
||||
l.pending[i] = queued{}
|
||||
}
|
||||
l.pending = nil
|
||||
if l.cancel != nil {
|
||||
l.cancel()
|
||||
cancelled = true
|
||||
}
|
||||
return cancelled, dropped
|
||||
}
|
||||
|
||||
// Running reports whether the session currently has a turn in flight.
|
||||
func (t *Turns) Running(session string) bool {
|
||||
l := t.lane(session)
|
||||
if l == nil {
|
||||
return false
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.cancel != nil
|
||||
}
|
||||
|
||||
// Queued reports how many turns are waiting behind the running one.
|
||||
func (t *Turns) Queued(session string) int {
|
||||
l := t.lane(session)
|
||||
if l == nil {
|
||||
return 0
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return len(l.pending)
|
||||
}
|
||||
|
||||
// lane returns the session's active lane, or nil if it has never been used or
|
||||
// its completed lane has already retired.
|
||||
func (t *Turns) lane(session string) *lane {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.lanes[session]
|
||||
}
|
||||
|
||||
// serve drains the lane's backlog one turn at a time and exits once it is
|
||||
// empty. Submit starts a fresh worker when more arrives, so an idle session
|
||||
// costs no goroutine.
|
||||
func (t *Turns) serve(session string, l *lane) {
|
||||
log := t.log.With("session", session)
|
||||
for {
|
||||
next, ok := l.begin()
|
||||
if !ok {
|
||||
if t.retire(session, l) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
l.runOne(next, log)
|
||||
}
|
||||
}
|
||||
|
||||
// retire removes an idle lane while holding the same two locks Submit uses to
|
||||
// find and append to it. Without that joint critical section, Submit could find
|
||||
// the old lane immediately before cleanup deleted it and strand the new turn on
|
||||
// a worker that had already exited.
|
||||
func (t *Turns) retire(session string, l *lane) bool {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
current, ok := t.lanes[session]
|
||||
if !ok || current != l {
|
||||
return true
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if len(l.pending) != 0 {
|
||||
return false
|
||||
}
|
||||
l.working = false
|
||||
delete(t.lanes, session)
|
||||
return true
|
||||
}
|
||||
|
||||
// begin pops the oldest queued turn and publishes its cancel in the same
|
||||
// critical section. It reports false when the backlog is empty; the owning
|
||||
// Turns then retires the worker and map entry under both locks.
|
||||
//
|
||||
// The pop and the publish must happen together. Were the turn popped first
|
||||
// and its cancel published after, a Stop landing in between would see an
|
||||
// empty backlog and no running turn, report that nothing was happening, and
|
||||
// let the turn it should have killed start regardless.
|
||||
func (l *lane) begin() (queued, bool) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if len(l.pending) == 0 {
|
||||
// The owning Turns retires the lane under both the map and lane
|
||||
// locks. Changing working here would race a concurrent Submit.
|
||||
return queued{}, false
|
||||
}
|
||||
|
||||
next := l.pending[0]
|
||||
// Clear the vacated slot so a completed turn's closure -- and whatever
|
||||
// it captured -- does not stay reachable through the backing array.
|
||||
l.pending[0] = queued{}
|
||||
l.pending = l.pending[1:]
|
||||
|
||||
l.cancel = next.cancel
|
||||
return next, true
|
||||
}
|
||||
|
||||
// runOne executes one turn, always retracting its cancel afterwards so a
|
||||
// later Stop cannot cancel an already-finished turn.
|
||||
//
|
||||
// Panics are contained here rather than by the channel's own recovery
|
||||
// middleware: that middleware wraps the event-loop goroutine, and the turn
|
||||
// no longer runs on it. Without this, one bad turn would take the lane's
|
||||
// goroutine down and the session would silently stop answering forever.
|
||||
func (l *lane) runOne(next queued, log *slog.Logger) {
|
||||
defer next.cancel()
|
||||
|
||||
defer func() {
|
||||
l.mu.Lock()
|
||||
l.cancel = nil
|
||||
l.mu.Unlock()
|
||||
|
||||
if r := recover(); r != nil {
|
||||
log.Error("chat turn panicked", "panic", r, "stack", string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
|
||||
next.run()
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package gateway
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -424,6 +424,42 @@ func TestOpenPRCapturesThePullRequestNumber(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenPRRecordsTheReviewedRevision is the producer half of the q9au
|
||||
// head-drift guard. Line numbers in a review finding describe one revision of
|
||||
// the worktree, and OpenPR is the last point at which the worktree is still
|
||||
// there to name it -- StageReview reads that same worktree and commits
|
||||
// nothing, so the head OpenPR measures is the head the review read. Without
|
||||
// the revision recorded here the posting stage has nothing to check the pull
|
||||
// request's head against.
|
||||
func TestOpenPRRecordsTheReviewedRevision(t *testing.T) {
|
||||
trees := &capturingTrees{stats: sampleStats()}
|
||||
tc := captureTaskContext(t, trees, &recordingStore{})
|
||||
tc.Forge = &fakeForge{}
|
||||
|
||||
if err := OpenPR(context.Background(), tc, "body"); err != nil {
|
||||
t.Fatalf("OpenPR() = %v, want nil", err)
|
||||
}
|
||||
if tc.ReviewedHeadSHA != trees.stats.HeadSHA {
|
||||
t.Errorf("ReviewedHeadSHA = %q, want the measured worktree head %q", tc.ReviewedHeadSHA, trees.stats.HeadSHA)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenPRLeavesTheReviewedRevisionUnsetWithoutAMeasurement pins the degrade
|
||||
// path: a worktree implementation that cannot report a diffstat leaves the
|
||||
// revision empty, which the forge reads as "not measured" and posts without the
|
||||
// check. Inventing a revision here would refuse every posting instead.
|
||||
func TestOpenPRLeavesTheReviewedRevisionUnsetWithoutAMeasurement(t *testing.T) {
|
||||
tc := captureTaskContext(t, &fakeTrees{}, &recordingStore{})
|
||||
tc.Forge = &fakeForge{}
|
||||
|
||||
if err := OpenPR(context.Background(), tc, "body"); err != nil {
|
||||
t.Fatalf("OpenPR() = %v, want nil", err)
|
||||
}
|
||||
if tc.ReviewedHeadSHA != "" {
|
||||
t.Errorf("ReviewedHeadSHA = %q, want empty when nothing measured the worktree", tc.ReviewedHeadSHA)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChangeCaptureTruncatesTheFileListButNotTheTotals: one large refactor
|
||||
// must not write an unbounded payload, and a capture that dropped entries must
|
||||
// still report how much the attempt actually changed.
|
||||
|
||||
@@ -192,6 +192,7 @@ func Implement() Workflow {
|
||||
StageDiffCap(),
|
||||
StageReview(),
|
||||
StageOpenPR(implementPRBody),
|
||||
StagePostReviewComments(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,6 +284,18 @@ type fakeForge struct {
|
||||
calls []string
|
||||
linkErr error
|
||||
prNumber int
|
||||
|
||||
reviewCalls int
|
||||
reviewComments []ReviewComment
|
||||
reviewOwner string
|
||||
reviewRepo string
|
||||
reviewNumber int
|
||||
reviewHeadSHA string
|
||||
reviewErr error
|
||||
|
||||
replyCommentID int64
|
||||
replyBody string
|
||||
replyErr error
|
||||
}
|
||||
|
||||
func (f *fakeForge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
@@ -296,6 +308,11 @@ func (f *fakeForge) Comment(ctx context.Context, owner, repo string, number int,
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error {
|
||||
f.replyCommentID, f.replyBody = commentID, body
|
||||
return f.replyErr
|
||||
}
|
||||
|
||||
// Remaining forge.Forge stubs -- only CloseIssue and Comment are used by StageCommitPush.
|
||||
func (f *fakeForge) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
|
||||
return 0, nil
|
||||
@@ -333,6 +350,14 @@ func (f *fakeForge) LinkBranch(ctx context.Context, owner, repo string, number i
|
||||
f.calls = append(f.calls, "link:"+branch)
|
||||
return f.linkErr
|
||||
}
|
||||
|
||||
func (f *fakeForge) CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []ReviewComment) error {
|
||||
f.reviewCalls++
|
||||
f.reviewOwner, f.reviewRepo, f.reviewNumber = owner, repo, number
|
||||
f.reviewHeadSHA = reviewedHeadSHA
|
||||
f.reviewComments = append(f.reviewComments, comments...)
|
||||
return f.reviewErr
|
||||
}
|
||||
func (f *fakeForge) VerifyPush(ctx context.Context, owner, repo string) error { return nil }
|
||||
|
||||
// TestStageCommitPushClosesIssueWhenBuildNoChanges verifies that
|
||||
@@ -430,6 +455,13 @@ type fakeTrees struct {
|
||||
pushed bool
|
||||
pushBranch string
|
||||
pushErr error
|
||||
|
||||
dir string
|
||||
|
||||
resumed bool
|
||||
resumeDir string
|
||||
resumeBranch string
|
||||
resumeErr error
|
||||
}
|
||||
|
||||
func (f *fakeTrees) Prepare(context.Context, string, string, string, int, string, string, string) (string, string, error) {
|
||||
@@ -457,6 +489,13 @@ func (f *fakeTrees) ChangedLines(context.Context, string, string) (int, error) {
|
||||
|
||||
func (f *fakeTrees) Snapshot(context.Context, string, string) error { return nil }
|
||||
|
||||
func (f *fakeTrees) Resume(_ context.Context, dir, branch string) error {
|
||||
f.resumed, f.resumeDir, f.resumeBranch = true, dir, branch
|
||||
return f.resumeErr
|
||||
}
|
||||
|
||||
func (f *fakeTrees) Dir(string, string, int) string { return f.dir }
|
||||
|
||||
// TestStageCommitPushPushesBaselineFixEvenWithNothingNewToCommit is the
|
||||
// regression case for archie-core-95dj: StageBaselineGate already
|
||||
// committed a real, gate-verified fix for a pre-existing failure, and the
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
)
|
||||
|
||||
// ErrNoReviewPayload is returned when a remediate run starts on a task that
|
||||
// carries no review unit to address. The daemon reaction consumer is the
|
||||
// only producer of Task.ReviewPayload; a remediate task without one is a
|
||||
// dispatch bug upstream, not a recoverable condition here.
|
||||
var ErrNoReviewPayload = errors.New("remediate: task carries no review payload")
|
||||
|
||||
// ReviewUnitComment is one actionable review comment the builder must
|
||||
// address, carried inside a ReviewUnit.
|
||||
type ReviewUnitComment struct {
|
||||
CommentID int64 `json:"comment_id"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Line int `json:"line,omitempty"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// ReviewUnit is the remediate workflow's input contract: one review (or one
|
||||
// standalone comment with no parent review) and every actionable comment
|
||||
// grouped under it, per docs/prds/pr-review-remediation.md decision 5 ("a
|
||||
// review is the unit of remediation, never an individual comment"). The
|
||||
// daemon's reaction consumer builds and JSON-encodes this into
|
||||
// Task.ReviewPayload before dispatch; this package only decodes and acts
|
||||
// on it.
|
||||
type ReviewUnit struct {
|
||||
ReviewID int64 `json:"review_id,omitempty"`
|
||||
Author string `json:"author,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
// Body is the review's own top-level summary (e.g. a "requested_changes"
|
||||
// review's message), separate from any inline comment bodies.
|
||||
Body string `json:"body,omitempty"`
|
||||
Comments []ReviewUnitComment `json:"comments,omitempty"`
|
||||
}
|
||||
|
||||
// DecodeReviewUnit parses a task's ReviewPayload. An empty payload is
|
||||
// ErrNoReviewPayload, not a zero-value unit: a remediate task with nothing
|
||||
// to address should never have been dispatched.
|
||||
func DecodeReviewUnit(payload string) (ReviewUnit, error) {
|
||||
if payload == "" {
|
||||
return ReviewUnit{}, ErrNoReviewPayload
|
||||
}
|
||||
var u ReviewUnit
|
||||
if err := json.Unmarshal([]byte(payload), &u); err != nil {
|
||||
return ReviewUnit{}, fmt.Errorf("decode review payload: %w", err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// EncodeReviewUnit renders a review unit for storage in Task.ReviewPayload.
|
||||
func EncodeReviewUnit(u ReviewUnit) (string, error) {
|
||||
data, err := json.Marshal(u)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encode review payload: %w", err)
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// replyTarget is the one comment ID a remediation run's reply threads onto,
|
||||
// and whether one exists at all. A standalone review with no inline
|
||||
// comments (a plain "requested changes" message) has nothing to thread a
|
||||
// reply onto, so the reply falls back to a plain PR comment.
|
||||
func (u ReviewUnit) replyTarget() (int64, bool) {
|
||||
for _, c := range u.Comments {
|
||||
if c.CommentID > 0 {
|
||||
return c.CommentID, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// renderReviewUnitMission formats a review unit as the builder's mission
|
||||
// input: the review's own message, if any, followed by every actionable
|
||||
// comment with its location.
|
||||
func renderReviewUnitMission(u ReviewUnit) string {
|
||||
var b strings.Builder
|
||||
if u.Body != "" {
|
||||
fmt.Fprintf(&b, "Review summary (%s): %s\n\n", orUnknown(u.State), u.Body)
|
||||
}
|
||||
if len(u.Comments) == 0 {
|
||||
b.WriteString("No inline comments were attached; address the review summary above.")
|
||||
return b.String()
|
||||
}
|
||||
b.WriteString("Comments:\n")
|
||||
for _, c := range u.Comments {
|
||||
loc := "(general)"
|
||||
if c.Path != "" {
|
||||
loc = c.Path
|
||||
if c.Line > 0 {
|
||||
loc = fmt.Sprintf("%s:%d", c.Path, c.Line)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, "- %s: %s\n", loc, c.Body)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func orUnknown(s string) string {
|
||||
if s == "" {
|
||||
return "unspecified"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// remediationRoundCapBytes bounds the round-cap park detail, matching the
|
||||
// other clipped park reasons in this package.
|
||||
const remediationRoundCapBytes = 2000
|
||||
|
||||
// resumableTrees is the optional capability a Trees implementation offers
|
||||
// for continuing work on an already-open PR branch instead of starting a
|
||||
// fresh worktree. Deliberately NOT part of the exported Trees interface,
|
||||
// for two reasons: Trees is projected into the Yaegi symbol table
|
||||
// (wfextract) for repository-authored .archie/stages/*.go, and this
|
||||
// capability must not become callable from there (mirrors changeStatsReader
|
||||
// in steps.go); and Trees is already at golangci-lint's interfacebloat cap
|
||||
// of 8 methods, which CLAUDE.md reserves for proto/gRPC surfaces, not
|
||||
// growing Go interfaces further.
|
||||
//
|
||||
// *worktree.Manager (real git access) and the container-mode hybrid
|
||||
// implementation both already satisfy this structurally; a Trees
|
||||
// implementation that doesn't (a narrower test fake, say) simply cannot run
|
||||
// the remediate workflow, which StageResumeWorktree reports plainly.
|
||||
type resumableTrees interface {
|
||||
Dir(owner, repo string, issue int) string
|
||||
Resume(ctx context.Context, dir, branch string) error
|
||||
}
|
||||
|
||||
// StageResumeWorktree re-syncs the task's already-prepared worktree onto
|
||||
// its PR branch's remote tip, so the remediate workflow continues on the
|
||||
// branch the implement run pushed instead of resetting to base the way
|
||||
// StagePrepareWorktree's refresh would (docs/prds/pr-review-remediation.md
|
||||
// decision 4). A remediate task always has a branch: it only ever runs
|
||||
// against a PR archie itself opened.
|
||||
func StageResumeWorktree() Stage {
|
||||
return Stage{Name: "resume", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.Task.Branch == "" {
|
||||
return fmt.Errorf("remediate: task has no branch to resume")
|
||||
}
|
||||
rt, ok := tc.Trees.(resumableTrees)
|
||||
if !ok {
|
||||
return fmt.Errorf("remediate: this worktree implementation cannot resume a PR branch")
|
||||
}
|
||||
dir := rt.Dir(tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber)
|
||||
if err := rt.Resume(ctx, dir, tc.Task.Branch); err != nil {
|
||||
return fmt.Errorf("resume worktree onto %s: %w", tc.Task.Branch, err)
|
||||
}
|
||||
tc.Dir, tc.Branch = dir, tc.Task.Branch
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// StageRemediationRoundCap enforces the hard stop on an unbounded
|
||||
// remediate/re-review exchange (decision 5, "bounding the exchange").
|
||||
// Task.RetryCount doubles as the remediation round counter here: on the
|
||||
// cap it parks the task and posts one comment explaining why, without
|
||||
// running the builder; under the cap it counts this round and proceeds.
|
||||
func StageRemediationRoundCap() Stage {
|
||||
return Stage{Name: "round-cap", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
maxRounds := tc.Repo.EffectiveMaxRetries(tc.Cfg.MaxRetries)
|
||||
if maxRounds > 0 && tc.Task.RetryCount >= maxRounds {
|
||||
detail := fmt.Sprintf("remediation round cap reached (%d/%d); stopping and parking for an operator", tc.Task.RetryCount, maxRounds)
|
||||
postRemediationComment(ctx, tc, "Archie has stopped remediating this review: "+detail+".")
|
||||
tc.Outcome = Outcome{Status: StatusParked, Detail: clip(detail, remediationRoundCapBytes)}
|
||||
return nil
|
||||
}
|
||||
tc.Task.RetryCount++
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// postRemediationComment posts a plain PR comment, best-effort: a park or a
|
||||
// reply failure on the messaging side must never mask the round-cap
|
||||
// decision or the remediation outcome that already happened.
|
||||
func postRemediationComment(ctx context.Context, tc *TaskContext, body string) {
|
||||
if tc.Task.PRNumber <= 0 {
|
||||
return
|
||||
}
|
||||
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, body); err != nil {
|
||||
tc.Log.Warn("remediation comment not posted", "pr", tc.Task.PRNumber, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// remediateMission builds the builder agent's mission from the task's
|
||||
// decoded review unit, stashing it on tc.reviewUnit so later stages
|
||||
// (commit-push, reply) don't re-decode the payload. StageCheckReviewPayload
|
||||
// already guarantees the payload decodes before this stage runs.
|
||||
func remediateMission(tc *TaskContext) string {
|
||||
unit, _ := DecodeReviewUnit(tc.Task.ReviewPayload)
|
||||
tc.reviewUnit = unit
|
||||
return fmt.Sprintf(
|
||||
"Address the review comments below on pull request #%d for %s with the smallest change that "+
|
||||
"satisfies them, then run the gate.\n\n%s\n\n"+
|
||||
"Do not run git -- the orchestrator commits and pushes for you. When done, call finish with "+
|
||||
"status \"passed\" and a summary written for the human who will read your reply: what changed and "+
|
||||
"why. If nothing here actually requires a code change, call finish with status \"passed\" and say "+
|
||||
"so in the summary.",
|
||||
tc.Task.PRNumber, tc.Repo.FullName(), renderReviewUnitMission(unit),
|
||||
)
|
||||
}
|
||||
|
||||
// remediateBuildStage runs the builder agent against the task's review
|
||||
// unit. StageCheckReviewPayload runs first, so a decode failure parks the
|
||||
// run before the builder ever sees an empty mission.
|
||||
func remediateBuildStage() Stage {
|
||||
return AgentStage{
|
||||
Name: "remediate-build",
|
||||
Role: "builder",
|
||||
Gate: func(tc *TaskContext) agentexec.Gate {
|
||||
return GateFromRepo(tc.Repo, tc.Cfg.Budgets)
|
||||
},
|
||||
Mission: remediateMission,
|
||||
OnResult: func(tc *TaskContext, res agentexec.Result) error {
|
||||
tc.BuildSummary = res.Summary
|
||||
if res.Status == agentexec.StatusPassed && len(res.Changes) == 0 {
|
||||
tc.BuildNoChanges = true
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}.Stage()
|
||||
}
|
||||
|
||||
// StageCheckReviewPayload fails the run before any worktree or agent work
|
||||
// starts if the task's review payload cannot be decoded -- a dispatch bug
|
||||
// upstream, not something a builder run can recover from.
|
||||
func StageCheckReviewPayload() Stage {
|
||||
return Stage{Name: "check-review-payload", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
_, err := DecodeReviewUnit(tc.Task.ReviewPayload)
|
||||
return err
|
||||
}}
|
||||
}
|
||||
|
||||
// StageRemediationCommitPush commits and pushes the remediation to the
|
||||
// existing PR branch. Unlike StageCommitPush, no changes is a normal
|
||||
// outcome, not an empty-tree error: a review can be satisfied by
|
||||
// explanation alone, and there is no issue to close either way -- the PR
|
||||
// this task owns stays open regardless.
|
||||
func StageRemediationCommitPush() Stage {
|
||||
return Stage{Name: "remediate-commit-push", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.BuildNoChanges {
|
||||
return nil
|
||||
}
|
||||
changed, err := tc.Trees.CommitAll(ctx, tc.Dir, remediationCommitMessage(tc))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
if err := tc.Trees.Push(ctx, tc.Dir, tc.Branch); err != nil {
|
||||
return err
|
||||
}
|
||||
tc.captureChanges(ctx, capturedAfterCommitPush)
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
func remediationCommitMessage(tc *TaskContext) string {
|
||||
return fmt.Sprintf("fix: address review feedback (archie)%s", commitIssueReference("Refs", tc.Task))
|
||||
}
|
||||
|
||||
// StageRemediationReply replies to the review this run addressed, then
|
||||
// returns the task to pr_open and clears the consumed review payload so a
|
||||
// later crash-and-resume cannot reprocess it. It is the workflow's only
|
||||
// terminal stage: it always sets Outcome, so it always ends the run.
|
||||
func StageRemediationReply() Stage {
|
||||
return Stage{Name: "remediate-reply", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
summary := tc.BuildSummary
|
||||
if tc.BuildNoChanges {
|
||||
summary = "Reviewed -- no code change was required."
|
||||
}
|
||||
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", summary, tc.Task.RetryCount)
|
||||
|
||||
if id, ok := tc.reviewUnit.replyTarget(); ok {
|
||||
if err := tc.Forge.ReplyToReview(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, id, reply); err != nil {
|
||||
tc.Log.Warn("remediation reply not posted", "pr", tc.Task.PRNumber, "comment", id, "err", err)
|
||||
}
|
||||
} else {
|
||||
postRemediationComment(ctx, tc, reply)
|
||||
}
|
||||
|
||||
tc.Task.ReviewPayload = ""
|
||||
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RetryCount)}
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// Remediate runs one remediation round against an archie-owned, still-open
|
||||
// pull request in response to a forge review reaction
|
||||
// (docs/prds/pr-review-remediation.md decision 4). It reuses the task's
|
||||
// existing worktree and branch rather than opening a new PR.
|
||||
func Remediate() Workflow {
|
||||
return Workflow{
|
||||
Name: "remediate",
|
||||
Stages: []Stage{
|
||||
StageCheckReviewPayload(),
|
||||
StageRemediationRoundCap(),
|
||||
StageResumeWorktree(),
|
||||
remediateBuildStage(),
|
||||
StageRemediationCommitPush(),
|
||||
StageRemediationReply(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestDecodeReviewUnitRejectsEmptyPayload(t *testing.T) {
|
||||
if _, err := DecodeReviewUnit(""); !errors.Is(err, ErrNoReviewPayload) {
|
||||
t.Fatalf("DecodeReviewUnit(\"\") error = %v, want ErrNoReviewPayload", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeDecodeReviewUnitRoundTrips(t *testing.T) {
|
||||
want := ReviewUnit{
|
||||
ReviewID: 42, Author: "reviewer-bot", State: "requested_changes", Body: "please fix",
|
||||
Comments: []ReviewUnitComment{{CommentID: 7, Path: "a.go", Line: 3, Body: "nil check missing"}},
|
||||
}
|
||||
payload, err := EncodeReviewUnit(want)
|
||||
if err != nil {
|
||||
t.Fatalf("EncodeReviewUnit: %v", err)
|
||||
}
|
||||
got, err := DecodeReviewUnit(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("DecodeReviewUnit: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("round-tripped unit = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageCheckReviewPayloadFailsOnEmptyPayload(t *testing.T) {
|
||||
tc := &TaskContext{Task: &Task{ID: 1}}
|
||||
if err := StageCheckReviewPayload().Run(t.Context(), tc); !errors.Is(err, ErrNoReviewPayload) {
|
||||
t.Fatalf("StageCheckReviewPayload error = %v, want ErrNoReviewPayload", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageResumeWorktreeRequiresABranch(t *testing.T) {
|
||||
tc := &TaskContext{Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 5}, Trees: &fakeTrees{}}
|
||||
if err := StageResumeWorktree().Run(t.Context(), tc); err == nil {
|
||||
t.Fatal("StageResumeWorktree with no branch = nil error, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageResumeWorktreeResumesOntoTheTaskBranch(t *testing.T) {
|
||||
trees := &fakeTrees{dir: "/worktrees/o-r-5"}
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 5, Branch: "archie/issue-5"},
|
||||
Trees: trees,
|
||||
}
|
||||
if err := StageResumeWorktree().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageResumeWorktree: %v", err)
|
||||
}
|
||||
if !trees.resumed || trees.resumeDir != "/worktrees/o-r-5" || trees.resumeBranch != "archie/issue-5" {
|
||||
t.Fatalf("Resume call = resumed=%v dir=%q branch=%q, want true /worktrees/o-r-5 archie/issue-5",
|
||||
trees.resumed, trees.resumeDir, trees.resumeBranch)
|
||||
}
|
||||
if tc.Dir != "/worktrees/o-r-5" || tc.Branch != "archie/issue-5" {
|
||||
t.Fatalf("tc.Dir/Branch = %q/%q, want /worktrees/o-r-5/archie/issue-5", tc.Dir, tc.Branch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRemediationRoundCapCountsARoundUnderTheCap(t *testing.T) {
|
||||
forge := &fakeForge{}
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, RetryCount: 1}, Repo: config.Repo{MaxRetries: 3}, Forge: forge,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := StageRemediationRoundCap().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageRemediationRoundCap: %v", err)
|
||||
}
|
||||
if tc.Task.RetryCount != 2 {
|
||||
t.Fatalf("RetryCount = %d, want 2", tc.Task.RetryCount)
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
t.Fatalf("Outcome = %+v, want zero value (workflow continues)", tc.Outcome)
|
||||
}
|
||||
if len(forge.commented) != 0 {
|
||||
t.Fatalf("commented = %v, want no comment posted under the cap", forge.commented)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRemediationRoundCapParksAtTheCapAndPostsOneComment(t *testing.T) {
|
||||
forge := &fakeForge{}
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, RetryCount: 3, PRNumber: 9}, Repo: config.Repo{MaxRetries: 3}, Forge: forge,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := StageRemediationRoundCap().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageRemediationRoundCap: %v", err)
|
||||
}
|
||||
if tc.Task.RetryCount != 3 {
|
||||
t.Fatalf("RetryCount = %d, want unchanged at 3", tc.Task.RetryCount)
|
||||
}
|
||||
if tc.Outcome.Status != StatusParked {
|
||||
t.Fatalf("Outcome.Status = %q, want parked", tc.Outcome.Status)
|
||||
}
|
||||
if len(forge.commented) != 1 {
|
||||
t.Fatalf("commented = %v, want exactly one comment", forge.commented)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRemediationRoundCapZeroMeansUnlimited(t *testing.T) {
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, RetryCount: 50}, Repo: config.Repo{}, Cfg: config.Config{MaxRetries: 0},
|
||||
Forge: &fakeForge{}, Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := StageRemediationRoundCap().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageRemediationRoundCap: %v", err)
|
||||
}
|
||||
if tc.Outcome.Status == StatusParked {
|
||||
t.Fatal("Outcome = parked, want no cap enforced when max_retries is unset")
|
||||
}
|
||||
if tc.Task.RetryCount != 51 {
|
||||
t.Fatalf("RetryCount = %d, want 51", tc.Task.RetryCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRemediationCommitPushSkipsAnEmptyTreeWithoutError(t *testing.T) {
|
||||
trees := &fakeTrees{commitAllChanged: false}
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 1}, Trees: trees,
|
||||
Dir: "/tmp/x", Branch: "archie/issue-1",
|
||||
}
|
||||
if err := StageRemediationCommitPush().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageRemediationCommitPush: %v", err)
|
||||
}
|
||||
if trees.pushed {
|
||||
t.Fatal("Push called with nothing committed, want no push")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRemediationCommitPushCommitsAndPushesAChange(t *testing.T) {
|
||||
trees := &fakeTrees{commitAllChanged: true}
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 1}, Trees: trees,
|
||||
Dir: "/tmp/x", Branch: "archie/issue-1", Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := StageRemediationCommitPush().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageRemediationCommitPush: %v", err)
|
||||
}
|
||||
if !trees.pushed || trees.pushBranch != "archie/issue-1" {
|
||||
t.Fatalf("pushed=%v pushBranch=%q, want true archie/issue-1", trees.pushed, trees.pushBranch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRemediationReplyThreadsOntoTheFirstComment(t *testing.T) {
|
||||
forge := &fakeForge{}
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, Owner: "o", Repo: "r", PRNumber: 9, ReviewPayload: "stale"},
|
||||
Forge: forge,
|
||||
BuildSummary: "fixed the nil check",
|
||||
reviewUnit: ReviewUnit{Comments: []ReviewUnitComment{{CommentID: 55, Body: "fix this"}}},
|
||||
}
|
||||
if err := StageRemediationReply().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageRemediationReply: %v", err)
|
||||
}
|
||||
if forge.replyCommentID != 55 {
|
||||
t.Fatalf("replyCommentID = %d, want 55", forge.replyCommentID)
|
||||
}
|
||||
if len(forge.commented) != 0 {
|
||||
t.Fatalf("commented = %v, want the plain-comment fallback unused", forge.commented)
|
||||
}
|
||||
if tc.Task.ReviewPayload != "" {
|
||||
t.Fatalf("ReviewPayload = %q, want cleared after the run consumed it", tc.Task.ReviewPayload)
|
||||
}
|
||||
if tc.Outcome.Status != StatusPROpen {
|
||||
t.Fatalf("Outcome.Status = %q, want pr_open", tc.Outcome.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRemediationReplyFallsBackToAPlainCommentForABareReview(t *testing.T) {
|
||||
forge := &fakeForge{}
|
||||
tc := &TaskContext{
|
||||
Task: &Task{ID: 1, Owner: "o", Repo: "r", PRNumber: 9},
|
||||
Forge: forge,
|
||||
BuildSummary: "no change needed",
|
||||
reviewUnit: ReviewUnit{Body: "looks fine overall"},
|
||||
}
|
||||
if err := StageRemediationReply().Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("StageRemediationReply: %v", err)
|
||||
}
|
||||
if forge.replyCommentID != 0 {
|
||||
t.Fatalf("replyCommentID = %d, want 0 (no threaded reply)", forge.replyCommentID)
|
||||
}
|
||||
if len(forge.commented) != 1 {
|
||||
t.Fatalf("commented = %v, want exactly one plain comment", forge.commented)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemediateEndToEndAddressesCommentsAndReplies(t *testing.T) {
|
||||
trees := &fakeTrees{dir: "/worktrees/o-r-1", commitAllChanged: true}
|
||||
forge := &fakeForge{}
|
||||
payload, err := EncodeReviewUnit(ReviewUnit{
|
||||
ReviewID: 1, State: "requested_changes",
|
||||
Comments: []ReviewUnitComment{{CommentID: 10, Path: "a.go", Line: 4, Body: "nil check missing"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("EncodeReviewUnit: %v", err)
|
||||
}
|
||||
task := &Task{
|
||||
ID: 1, Owner: "o", Repo: "r", IssueNumber: 1, PRNumber: 9,
|
||||
Branch: "archie/issue-1", ReviewPayload: payload,
|
||||
}
|
||||
runner := agentRunnerFunc(func(_ context.Context, _ string, req agentexec.Request, _ agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
return agentexec.Result{
|
||||
Version: agentexec.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, Stage: req.Stage,
|
||||
Status: agentexec.StatusPassed, Summary: "added the nil check", Changes: []string{"a.go"},
|
||||
}, nil
|
||||
})
|
||||
tc := &TaskContext{
|
||||
Task: task, Repo: config.Repo{Owner: "o", Name: "r", MaxRetries: 3},
|
||||
Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}},
|
||||
Agent: runner, Trees: trees, Forge: forge, Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
|
||||
wf := Remediate()
|
||||
for _, stage := range wf.Stages {
|
||||
if err := stage.Run(t.Context(), tc); err != nil {
|
||||
t.Fatalf("stage %s: %v", stage.Name, err)
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !trees.resumed {
|
||||
t.Fatal("worktree was never resumed")
|
||||
}
|
||||
if !trees.pushed {
|
||||
t.Fatal("remediation commit was never pushed")
|
||||
}
|
||||
if forge.replyCommentID != 10 {
|
||||
t.Fatalf("replyCommentID = %d, want 10", forge.replyCommentID)
|
||||
}
|
||||
if task.RetryCount != 1 {
|
||||
t.Fatalf("RetryCount = %d, want 1 (one round consumed)", task.RetryCount)
|
||||
}
|
||||
if task.ReviewPayload != "" {
|
||||
t.Fatalf("ReviewPayload = %q, want cleared", task.ReviewPayload)
|
||||
}
|
||||
if tc.Outcome.Status != StatusPROpen {
|
||||
t.Fatalf("Outcome.Status = %q, want pr_open", tc.Outcome.Status)
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,97 @@ func runReview(ctx context.Context, tc *TaskContext) (ReviewReport, error) {
|
||||
return tc.Reviewer.Review(ctx, req), nil
|
||||
}
|
||||
|
||||
// StagePostReviewComments posts the review's line-anchored findings as inline
|
||||
// comments on the pull request StageOpenPR has just opened (archie-core-q9au).
|
||||
//
|
||||
// Only line-anchored findings are posted. A whole-file finding has no line to
|
||||
// attach to and stays in the PR-body list, which remains the complete record and
|
||||
// the fallback. A blocking finding never reaches here either: StageReview parks
|
||||
// the task before StageOpenPR when a confirmed error-level finding survives, so
|
||||
// there is no PR to comment on.
|
||||
//
|
||||
// Best-effort by construction. The PR is already open and its body already
|
||||
// carries every finding, so a comment that failed to post must not park a task
|
||||
// whose actual work succeeded -- the same reasoning as OpenPR's best-effort
|
||||
// LinkBranch call. A failure is logged, never returned. That includes the forge
|
||||
// refusing the set because the pull request's head moved past ReviewedHeadSHA:
|
||||
// the line numbers would then describe a revision the author is no longer
|
||||
// looking at, and the PR body is the record that survives anyway.
|
||||
func StagePostReviewComments() Stage {
|
||||
return Stage{Name: "post-review-comments", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if !tc.ReviewReport.Ran() {
|
||||
return nil
|
||||
}
|
||||
comments := lineAnchoredReviewComments(tc.ReviewReport)
|
||||
if len(comments) == 0 {
|
||||
return nil
|
||||
}
|
||||
// OpenPR records the number; without one there is nothing to anchor to,
|
||||
// and a guess would attach the findings to unrelated work.
|
||||
if tc.Task.PRNumber <= 0 {
|
||||
tc.Log.Warn("review comments not posted: the task carries no pull request number",
|
||||
"findings", len(comments))
|
||||
return nil
|
||||
}
|
||||
err := tc.Forge.CreateReviewComments(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, tc.ReviewedHeadSHA, comments)
|
||||
if err != nil {
|
||||
tc.Log.Error("review comments not posted; the pull request body still lists every finding",
|
||||
"err", err, "pr", tc.Task.PRNumber, "comments", len(comments))
|
||||
return nil
|
||||
}
|
||||
tc.Log.Info("review comments posted", "pr", tc.Task.PRNumber, "comments", len(comments))
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// ReviewComment is one line-anchored comment to post on an open pull request:
|
||||
// the repo-relative path, the line in the reviewed revision, and the rendered
|
||||
// body -- which may carry a fenced suggestion block. It is what the review stage
|
||||
// hands the forge through Forger, so it names nothing forge-specific.
|
||||
type ReviewComment struct {
|
||||
Path string
|
||||
Line int
|
||||
Body string
|
||||
}
|
||||
|
||||
// lineAnchoredReviewComments renders the findings that can carry an inline
|
||||
// comment. It is the one place "which findings, with what body" is decided, so
|
||||
// the PR body and the inline comments cannot disagree about a finding beyond the
|
||||
// location the body has to state in text.
|
||||
func lineAnchoredReviewComments(report ReviewReport) []ReviewComment {
|
||||
comments := make([]ReviewComment, 0, len(report.Findings))
|
||||
for _, f := range report.Findings {
|
||||
if f.Line <= 0 {
|
||||
continue
|
||||
}
|
||||
comments = append(comments, ReviewComment{Path: f.File, Line: f.Line, Body: renderReviewCommentBody(f)})
|
||||
}
|
||||
return comments
|
||||
}
|
||||
|
||||
// renderReviewCommentBody renders one finding as the body of a comment anchored
|
||||
// to its line: the anchor carries the location, so the body states the defect,
|
||||
// the scenario that produces it, and -- for a confirmed defect the reviewer
|
||||
// supplied a replacement for -- the replacement as a fence GitHub applies in one
|
||||
// click.
|
||||
//
|
||||
// The fence is gated on confirmed here rather than left to the reviewer, because
|
||||
// it is a one-click apply: a wrong suggestion breaks the code and the author has
|
||||
// to notice. The prompt asks for a suggestion only on a confirmed, mechanically
|
||||
// fixable finding, but an agent's output is input, so the rule is enforced where
|
||||
// the fence is written.
|
||||
func renderReviewCommentBody(f ReviewFinding) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "**%s (%s)**: %s", f.Verdict, f.Level, f.Defect)
|
||||
if f.FailureScenario != "" {
|
||||
fmt.Fprintf(&b, "\n\n%s", f.FailureScenario)
|
||||
}
|
||||
if f.Verdict == ReviewVerdictConfirmed && f.Suggestion != "" {
|
||||
fmt.Fprintf(&b, "\n\n```suggestion\n%s\n```", strings.TrimRight(f.Suggestion, "\n"))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// renderReviewDetail formats a review report as a park Detail: why the
|
||||
// task stopped, and what a human (or a retry) needs to know.
|
||||
func renderReviewDetail(report ReviewReport) string {
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestStagePostReviewCommentsPostsLineAnchoredFindings is the q9au stage
|
||||
// contract: a line-anchored finding reaches the forge as an inline comment,
|
||||
// a whole-file finding does not (it has no line to attach to and stays in the
|
||||
// PR body), and only a confirmed defect carries the one-click suggestion fence.
|
||||
func TestStagePostReviewCommentsPostsLineAnchoredFindings(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
finding ReviewFinding
|
||||
wantPosted bool
|
||||
wantSuggestion bool
|
||||
wantBodyHas []string
|
||||
wantBodyHasNot []string
|
||||
}{
|
||||
{
|
||||
name: "a confirmed defect carries its suggestion",
|
||||
finding: ReviewFinding{
|
||||
File: "a.go", Line: 12, Defect: "nil deref on an empty map",
|
||||
FailureScenario: "an issue with no labels panics the poller",
|
||||
Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn,
|
||||
// Single-line only: a multi-line suggestion is rejected by
|
||||
// ReviewFinding.Validate (Issue 2), so the posted fence replaces
|
||||
// the anchored line exactly.
|
||||
Suggestion: "if len(labels) == 0 { return nil }",
|
||||
},
|
||||
wantPosted: true,
|
||||
wantSuggestion: true,
|
||||
wantBodyHas: []string{"nil deref on an empty map", "an issue with no labels panics the poller", "confirmed"},
|
||||
},
|
||||
{
|
||||
name: "a plausible worry never carries one, even when supplied",
|
||||
finding: ReviewFinding{
|
||||
File: "b.go", Line: 3, Defect: "possible race",
|
||||
FailureScenario: "two writers", Verdict: ReviewVerdictPlausible,
|
||||
Level: ReviewLevelWarn, Suggestion: "mu.Lock()",
|
||||
},
|
||||
wantPosted: true,
|
||||
wantSuggestion: false,
|
||||
wantBodyHas: []string{"possible race", "plausible"},
|
||||
wantBodyHasNot: []string{"```suggestion", "mu.Lock()"},
|
||||
},
|
||||
{
|
||||
name: "a confirmed defect with no mechanical fix has no fence",
|
||||
finding: ReviewFinding{
|
||||
File: "c.go", Line: 9, Defect: "wrong ordering",
|
||||
FailureScenario: "retry drops the newest event",
|
||||
Verdict: ReviewVerdictConfirmed, Level: ReviewLevelError,
|
||||
},
|
||||
wantPosted: true,
|
||||
wantSuggestion: false,
|
||||
wantBodyHasNot: []string{"```suggestion"},
|
||||
},
|
||||
{
|
||||
name: "a whole-file finding is not posted inline",
|
||||
finding: ReviewFinding{
|
||||
File: "README.md", Line: 0, Defect: "docs describe the old topology",
|
||||
Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn,
|
||||
},
|
||||
wantPosted: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := reviewCommentContext(f, ReviewReport{
|
||||
Status: ReviewStatusCompleted,
|
||||
Findings: []ReviewFinding{tt.finding},
|
||||
})
|
||||
|
||||
if err := StagePostReviewComments().Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("stage returned %v; a posting failure must never fail the task", err)
|
||||
}
|
||||
if got := len(f.reviewComments); (got > 0) != tt.wantPosted {
|
||||
t.Fatalf("posted %d comments, want posted=%v", got, tt.wantPosted)
|
||||
}
|
||||
if !tt.wantPosted {
|
||||
return
|
||||
}
|
||||
got := f.reviewComments[0]
|
||||
if got.Path != tt.finding.File || got.Line != tt.finding.Line {
|
||||
t.Errorf("anchor = %s:%d, want %s:%d", got.Path, got.Line, tt.finding.File, tt.finding.Line)
|
||||
}
|
||||
for _, want := range tt.wantBodyHas {
|
||||
if !strings.Contains(got.Body, want) {
|
||||
t.Errorf("body %q does not mention %q", got.Body, want)
|
||||
}
|
||||
}
|
||||
for _, unwanted := range tt.wantBodyHasNot {
|
||||
if strings.Contains(got.Body, unwanted) {
|
||||
t.Errorf("body %q contains %q, which must not be offered", got.Body, unwanted)
|
||||
}
|
||||
}
|
||||
hasFence := strings.Contains(got.Body, "```suggestion")
|
||||
if hasFence != tt.wantSuggestion {
|
||||
t.Errorf("suggestion fence present = %v, want %v (body %q)", hasFence, tt.wantSuggestion, got.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStagePostReviewCommentsPostsEveryAnchoredFindingInOneCall pins the batch
|
||||
// shape: Gitea carries inline comments only on a submitted review, so the set
|
||||
// must travel as one call rather than one call per finding.
|
||||
func TestStagePostReviewCommentsPostsEveryAnchoredFindingInOneCall(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := reviewCommentContext(f, ReviewReport{
|
||||
Status: ReviewStatusCompleted,
|
||||
Findings: []ReviewFinding{
|
||||
{File: "a.go", Line: 1, Defect: "one", Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn},
|
||||
{File: "b.go", Line: 2, Defect: "two", Verdict: ReviewVerdictPlausible, Level: ReviewLevelWarn},
|
||||
{File: "c.go", Line: 0, Defect: "file-level", Verdict: ReviewVerdictPlausible, Level: ReviewLevelWarn},
|
||||
},
|
||||
})
|
||||
|
||||
if err := StagePostReviewComments().Run(context.Background(), tc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.reviewCalls != 1 {
|
||||
t.Errorf("CreateReviewComments called %d times, want 1", f.reviewCalls)
|
||||
}
|
||||
if len(f.reviewComments) != 2 {
|
||||
t.Errorf("posted %d comments, want the 2 anchored findings", len(f.reviewComments))
|
||||
}
|
||||
}
|
||||
|
||||
// TestStagePostReviewCommentsIsANoOpWithoutAReview keeps the stage silent when
|
||||
// there is nothing to post: a disabled or never-wired review must not reach the
|
||||
// forge at all, and a clean review has nothing to anchor.
|
||||
func TestStagePostReviewCommentsIsANoOpWithoutAReview(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
report ReviewReport
|
||||
}{
|
||||
{name: "the review never ran", report: ReviewReport{}},
|
||||
{name: "the review was skipped", report: ReviewReport{Status: ReviewStatusSkipped, SkipReason: "no reviewer"}},
|
||||
{name: "the review ran and found nothing", report: ReviewReport{Status: ReviewStatusCompleted}},
|
||||
{
|
||||
name: "the review found only a whole-file finding",
|
||||
report: ReviewReport{Status: ReviewStatusCompleted, Findings: []ReviewFinding{
|
||||
{File: "README.md", Line: 0, Defect: "stale", Verdict: ReviewVerdictPlausible, Level: ReviewLevelWarn},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := reviewCommentContext(f, tt.report)
|
||||
if err := StagePostReviewComments().Run(context.Background(), tc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.reviewCalls != 0 {
|
||||
t.Errorf("CreateReviewComments called %d times, want 0", f.reviewCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStagePostReviewCommentsSurvivesAPostingFailure is the "best effort"
|
||||
// clause: the PR is already open and its body already lists every finding, so a
|
||||
// failed comment must be logged, not turned into a parked task.
|
||||
func TestStagePostReviewCommentsSurvivesAPostingFailure(t *testing.T) {
|
||||
f := &fakeForge{reviewErr: errors.New("422 line is not part of the diff")}
|
||||
tc := reviewCommentContext(f, ReviewReport{
|
||||
Status: ReviewStatusCompleted,
|
||||
Findings: []ReviewFinding{
|
||||
{File: "a.go", Line: 4, Defect: "nil deref", Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn},
|
||||
},
|
||||
})
|
||||
|
||||
if err := StagePostReviewComments().Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("stage returned %v; a posting failure must never fail the task", err)
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
t.Errorf("outcome = %q, want unset: a failed comment must not end the workflow", tc.Outcome.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStagePostReviewCommentsNeedsAPullRequestNumber covers the one precondition
|
||||
// the stage cannot invent. A task with no recorded PR number has nothing to
|
||||
// anchor to, and guessing would attach the findings to unrelated work.
|
||||
func TestStagePostReviewCommentsNeedsAPullRequestNumber(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := reviewCommentContext(f, ReviewReport{
|
||||
Status: ReviewStatusCompleted,
|
||||
Findings: []ReviewFinding{
|
||||
{File: "a.go", Line: 4, Defect: "nil deref", Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn},
|
||||
},
|
||||
})
|
||||
tc.Task.PRNumber = 0
|
||||
|
||||
if err := StagePostReviewComments().Run(context.Background(), tc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.reviewCalls != 0 {
|
||||
t.Errorf("CreateReviewComments called %d times, want 0 with no PR number", f.reviewCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStagePostReviewCommentsAddressesTheRecordedPullRequest pins that the
|
||||
// comment lands on the task's own PR, in the task's own repo.
|
||||
func TestStagePostReviewCommentsAddressesTheRecordedPullRequest(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := reviewCommentContext(f, ReviewReport{
|
||||
Status: ReviewStatusCompleted,
|
||||
Findings: []ReviewFinding{
|
||||
{File: "a.go", Line: 4, Defect: "nil deref", Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn},
|
||||
},
|
||||
})
|
||||
|
||||
if err := StagePostReviewComments().Run(context.Background(), tc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.reviewOwner != "acme" || f.reviewRepo != "widget" || f.reviewNumber != 42 {
|
||||
t.Errorf("anchored at %s/%s#%d, want acme/widget#42", f.reviewOwner, f.reviewRepo, f.reviewNumber)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStagePostReviewCommentsThreadsTheReviewedHeadSHA is the producer half of
|
||||
// the head-drift guard: the forge can only refuse a set whose line numbers
|
||||
// describe a revision the pull request has left if the stage tells it which
|
||||
// revision those numbers were measured on.
|
||||
func TestStagePostReviewCommentsThreadsTheReviewedHeadSHA(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
reviewed string
|
||||
}{
|
||||
{name: "a measured revision reaches the forge", reviewed: "1a2b3c4d"},
|
||||
{
|
||||
name: "an unmeasured revision is passed through as empty so the forge posts unverified",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := reviewCommentContext(f, ReviewReport{
|
||||
Status: ReviewStatusCompleted,
|
||||
Findings: []ReviewFinding{
|
||||
{File: "a.go", Line: 4, Defect: "nil deref", Verdict: ReviewVerdictConfirmed, Level: ReviewLevelWarn},
|
||||
},
|
||||
})
|
||||
tc.ReviewedHeadSHA = tt.reviewed
|
||||
|
||||
if err := StagePostReviewComments().Run(context.Background(), tc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.reviewHeadSHA != tt.reviewed {
|
||||
t.Errorf("forge was handed reviewed head %q, want %q", f.reviewHeadSHA, tt.reviewed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func reviewCommentContext(f *fakeForge, report ReviewReport) *TaskContext {
|
||||
return &TaskContext{
|
||||
Task: &Task{ID: 1, Owner: "acme", Repo: "widget", IssueNumber: 7, PRNumber: 42},
|
||||
Forge: f,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
ReviewReport: report,
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package workflow
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ReviewLevel represents the severity level of a review finding.
|
||||
@@ -88,6 +89,12 @@ type ReviewFinding struct {
|
||||
Defect string `json:"defect"`
|
||||
// FailureScenario describes the concrete inputs or state that produce the wrong output or crash.
|
||||
FailureScenario string `json:"failure_scenario"`
|
||||
// Suggestion is the replacement text for the anchored line, when the
|
||||
// reviewer can state the fix mechanically. Only a confirmed finding may
|
||||
// carry one: it is rendered as a one-click apply, and a wrong one-click
|
||||
// fix is worse than no fix (h019.5 calibration). Empty means "no
|
||||
// mechanical fix", not "no fix needed".
|
||||
Suggestion string `json:"suggestion,omitempty"`
|
||||
// Verdict distinguishes confirmed defects from plausible hypotheses. Only confirmed findings may block.
|
||||
Verdict ReviewVerdict `json:"verdict"`
|
||||
// Disposition records the action taken once the finding is addressed.
|
||||
@@ -170,6 +177,18 @@ func (r ReviewReport) Passed() bool {
|
||||
|
||||
// Validate checks that the finding satisfies contract invariants.
|
||||
func (f ReviewFinding) Validate() error {
|
||||
if err := f.validateAnchor(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := f.validateClassification(); err != nil {
|
||||
return err
|
||||
}
|
||||
return f.validateDisposition()
|
||||
}
|
||||
|
||||
// validateAnchor checks where the defect is and what fix, if any, accompanies
|
||||
// it.
|
||||
func (f ReviewFinding) validateAnchor() error {
|
||||
if f.File == "" {
|
||||
return errors.New("review finding file is required")
|
||||
}
|
||||
@@ -182,6 +201,28 @@ func (f ReviewFinding) Validate() error {
|
||||
if f.FailureScenario == "" {
|
||||
return errors.New("review finding failure scenario is required")
|
||||
}
|
||||
// A suggestion is applied in one click, so only a confirmed defect may
|
||||
// carry one: a wrong suggestion breaks the code and the author has to
|
||||
// notice, where a plausible worry gets a sentence (h019.5 calibration).
|
||||
// Enforced at the value so the agent's record_finding call is rejected with
|
||||
// something the model can act on, instead of the suggestion being dropped
|
||||
// somewhere later where nothing tells it.
|
||||
if f.Suggestion != "" && f.Verdict != ReviewVerdictConfirmed {
|
||||
return fmt.Errorf("review finding %s:%d offers a one-click suggestion with verdict %q; only %q may", f.File, f.Line, f.Verdict, ReviewVerdictConfirmed)
|
||||
}
|
||||
// A suggestion is a one-line replacement GitHub applies with a single click,
|
||||
// so it must be single-line: an embedded newline renders a multi-line fence
|
||||
// that GitHub applies only up to the first line, silently corrupting the file
|
||||
// (docs/prds/inline-review.md). Enforced at the value so the agent's
|
||||
// record_finding call is rejected with something the model can act on.
|
||||
if f.Suggestion != "" && strings.ContainsAny(f.Suggestion, "\n\r") {
|
||||
return fmt.Errorf("review finding %s:%d suggestion must be single-line; got %d line(s)", f.File, f.Line, strings.Count(f.Suggestion, "\n")+1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateClassification checks the three enums that classify the finding.
|
||||
func (f ReviewFinding) validateClassification() error {
|
||||
switch f.Verdict {
|
||||
case ReviewVerdictConfirmed, ReviewVerdictPlausible:
|
||||
default:
|
||||
@@ -204,12 +245,16 @@ func (f ReviewFinding) Validate() error {
|
||||
default:
|
||||
return fmt.Errorf("invalid review category %q", f.Category)
|
||||
}
|
||||
if f.Disposition != "" {
|
||||
switch f.Disposition {
|
||||
case ReviewDispositionFixed, ReviewDispositionSkipped, ReviewDispositionNoChangeNeeded:
|
||||
default:
|
||||
return fmt.Errorf("invalid review disposition %q", f.Disposition)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateDisposition checks the optional record of what was done about the
|
||||
// finding once it was acted on.
|
||||
func (f ReviewFinding) validateDisposition() error {
|
||||
switch f.Disposition {
|
||||
case "", ReviewDispositionFixed, ReviewDispositionSkipped, ReviewDispositionNoChangeNeeded:
|
||||
default:
|
||||
return fmt.Errorf("invalid review disposition %q", f.Disposition)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -773,6 +773,34 @@ func TestReviewFindingValidation(t *testing.T) {
|
||||
},
|
||||
wantError: true,
|
||||
},
|
||||
{
|
||||
name: "multi-line suggestion is rejected",
|
||||
finding: ReviewFinding{
|
||||
File: "file.go",
|
||||
Line: 10,
|
||||
Defect: "Defect with multi-line suggestion",
|
||||
FailureScenario: "Scenario",
|
||||
Verdict: ReviewVerdictConfirmed,
|
||||
Level: ReviewLevelError,
|
||||
Category: ReviewCategoryNilRisk,
|
||||
Suggestion: "return nil\nmu.Lock()",
|
||||
},
|
||||
wantError: true,
|
||||
},
|
||||
{
|
||||
name: "single-line suggestion on a confirmed finding is valid",
|
||||
finding: ReviewFinding{
|
||||
File: "file.go",
|
||||
Line: 10,
|
||||
Defect: "Defect with single-line suggestion",
|
||||
FailureScenario: "Scenario",
|
||||
Verdict: ReviewVerdictConfirmed,
|
||||
Level: ReviewLevelError,
|
||||
Category: ReviewCategoryNilRisk,
|
||||
Suggestion: "mu.Lock()",
|
||||
},
|
||||
wantError: false,
|
||||
},
|
||||
{
|
||||
name: "invalid verdict",
|
||||
finding: ReviewFinding{
|
||||
|
||||
@@ -28,6 +28,7 @@ func builtins() workflow.Registry {
|
||||
"tdd": workflow.TDD(),
|
||||
"feasibility": workflow.Feasibility(),
|
||||
"triage": workflow.Triage(),
|
||||
"remediate": workflow.Remediate(),
|
||||
"default": workflow.Implement(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,21 +51,27 @@ type changeStatsReader interface {
|
||||
// Capturing is reporting, not work: every failure path here logs and returns,
|
||||
// because a provenance record that could not be written must never park or
|
||||
// fail a run that otherwise succeeded.
|
||||
func (tc *TaskContext) captureChanges(ctx context.Context, after string) {
|
||||
//
|
||||
// It returns the measured stats so a caller that runs at a point the worktree's
|
||||
// own revision matters (OpenPR) can reuse the read instead of paying for a
|
||||
// second one -- and gets the zero value on any failure path, which is why a
|
||||
// caller must treat an empty HeadSHA as "not measured" rather than as a
|
||||
// revision.
|
||||
func (tc *TaskContext) captureChanges(ctx context.Context, after string) task.ChangeStats {
|
||||
if tc.Dir == "" {
|
||||
tc.Log.Warn("change capture skipped: no worktree to read", "captured_after", after)
|
||||
return
|
||||
return task.ChangeStats{}
|
||||
}
|
||||
reader, ok := tc.Trees.(changeStatsReader)
|
||||
if !ok {
|
||||
tc.Log.Warn("change capture unavailable: this worktree implementation cannot report a diffstat",
|
||||
"captured_after", after)
|
||||
return
|
||||
return task.ChangeStats{}
|
||||
}
|
||||
stats, err := reader.ChangedFileStats(ctx, tc.Dir, tc.Repo.BaseBranch())
|
||||
if err != nil {
|
||||
tc.Log.Warn("change capture failed", "captured_after", after, "err", err)
|
||||
return
|
||||
return task.ChangeStats{}
|
||||
}
|
||||
// Durable, never bus-only: the worktree this was measured from is gone by
|
||||
// the time anyone reads it, so a capture that only reached the live feed
|
||||
@@ -73,6 +79,7 @@ func (tc *TaskContext) captureChanges(ctx context.Context, after string) {
|
||||
if err := tc.EmitDurable(ctx, events.KindChangesCaptured, tc.Task.Stage, "", changeCaptureData(tc, after, stats)); err != nil {
|
||||
tc.Log.Warn("change capture not persisted", "captured_after", after, "err", err)
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
// changeCaptureData builds the persisted payload for one capture. Totals are
|
||||
@@ -308,7 +315,14 @@ func OpenPR(ctx context.Context, tc *TaskContext, body string) error {
|
||||
// it. This is the one point where the number is known and the worktree is
|
||||
// still there to measure, so it is captured here rather than left for a
|
||||
// read to reconstruct. Reporting only: captureChanges never fails the stage.
|
||||
tc.captureChanges(ctx, capturedAfterOpenPR)
|
||||
//
|
||||
// The same read answers which revision this run's line numbers describe:
|
||||
// nothing commits between StageReview and here, so the worktree still holds
|
||||
// the head the review read, and the stage that posts line-anchored comments
|
||||
// needs it to refuse a post once the PR's head has moved past it.
|
||||
if stats := tc.captureChanges(ctx, capturedAfterOpenPR); stats.HeadSHA != "" {
|
||||
tc.ReviewedHeadSHA = stats.HeadSHA
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -77,6 +77,15 @@ type Task struct {
|
||||
// later edits to the binding cannot silently rewrite history.
|
||||
BindingID int64 `json:"binding_id"`
|
||||
BindingVersion int `json:"binding_version"`
|
||||
// ReviewPayload is the JSON-encoded review unit (the forge review's
|
||||
// actionable comments) the remediate workflow's current run must
|
||||
// address. The daemon's reaction consumer injects it before queuing a
|
||||
// remediation run, so the run is recoverable from the task record
|
||||
// itself rather than only from a prompt (docs/prds/pr-review-remediation.md
|
||||
// decision 4). Empty outside a remediation run. RetryCount doubles as
|
||||
// the remediation round counter for this same task, bounded by the
|
||||
// repo's existing max_retries (decision 5's round cap).
|
||||
ReviewPayload string `json:"review_payload"`
|
||||
// CreatedAt and UpdatedAt are the SQLite row timestamps, exposed so
|
||||
// callers can show a task's age and last activity. They are written by
|
||||
// column defaults and the UPDATE statements, never by the caller.
|
||||
|
||||
+99
-5
@@ -4,16 +4,24 @@ package wfextract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"go/constant"
|
||||
"go/token"
|
||||
"reflect"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Symbols["github.com/samcharles93/archie-core/internal/domain/workflow/workflow"] = map[string]reflect.Value{
|
||||
// function, constant and variable definitions
|
||||
"Bootstrap": reflect.ValueOf(workflow.Bootstrap),
|
||||
"DecodeReviewUnit": reflect.ValueOf(workflow.DecodeReviewUnit),
|
||||
"Definitions": reflect.ValueOf(workflow.Definitions),
|
||||
"DefinitionsWithOrigins": reflect.ValueOf(workflow.DefinitionsWithOrigins),
|
||||
"EncodeReviewUnit": reflect.ValueOf(workflow.EncodeReviewUnit),
|
||||
"ErrNoReviewPayload": reflect.ValueOf(&workflow.ErrNoReviewPayload).Elem(),
|
||||
"Feasibility": reflect.ValueOf(workflow.Feasibility),
|
||||
"GateFromRepo": reflect.ValueOf(workflow.GateFromRepo),
|
||||
"Implement": reflect.ValueOf(workflow.Implement),
|
||||
@@ -26,6 +34,7 @@ func init() {
|
||||
"NewNotRunReviewReport": reflect.ValueOf(workflow.NewNotRunReviewReport),
|
||||
"NewSkippedReviewReport": reflect.ValueOf(workflow.NewSkippedReviewReport),
|
||||
"OpenPR": reflect.ValueOf(workflow.OpenPR),
|
||||
"Remediate": reflect.ValueOf(workflow.Remediate),
|
||||
"ReviewBlocking": reflect.ValueOf(workflow.ReviewBlocking),
|
||||
"ReviewCategoryDeadCode": reflect.ValueOf(workflow.ReviewCategoryDeadCode),
|
||||
"ReviewCategoryGoroutineLeak": reflect.ValueOf(workflow.ReviewCategoryGoroutineLeak),
|
||||
@@ -49,15 +58,32 @@ func init() {
|
||||
"Run": reflect.ValueOf(workflow.Run),
|
||||
"SetKindWorkflows": reflect.ValueOf(workflow.SetKindWorkflows),
|
||||
"SetLabelWorkflows": reflect.ValueOf(workflow.SetLabelWorkflows),
|
||||
"SourceChat": reflect.ValueOf(constant.MakeFromLiteral("\"chat\"", token.STRING, 0)),
|
||||
"SourceForge": reflect.ValueOf(constant.MakeFromLiteral("\"forge\"", token.STRING, 0)),
|
||||
"StageBaselineGate": reflect.ValueOf(workflow.StageBaselineGate),
|
||||
"StageCheckReviewPayload": reflect.ValueOf(workflow.StageCheckReviewPayload),
|
||||
"StageCommit": reflect.ValueOf(workflow.StageCommit),
|
||||
"StageCommitPush": reflect.ValueOf(workflow.StageCommitPush),
|
||||
"StageDiffCap": reflect.ValueOf(workflow.StageDiffCap),
|
||||
"StageOpenPR": reflect.ValueOf(workflow.StageOpenPR),
|
||||
"StagePostReviewComments": reflect.ValueOf(workflow.StagePostReviewComments),
|
||||
"StagePrepareWorktree": reflect.ValueOf(workflow.StagePrepareWorktree),
|
||||
"StageRemediationCommitPush": reflect.ValueOf(workflow.StageRemediationCommitPush),
|
||||
"StageRemediationReply": reflect.ValueOf(workflow.StageRemediationReply),
|
||||
"StageRemediationRoundCap": reflect.ValueOf(workflow.StageRemediationRoundCap),
|
||||
"StageRepoStages": reflect.ValueOf(workflow.StageRepoStages),
|
||||
"StageResumeWorktree": reflect.ValueOf(workflow.StageResumeWorktree),
|
||||
"StageReview": reflect.ValueOf(workflow.StageReview),
|
||||
"StageYaegiGate": reflect.ValueOf(workflow.StageYaegiGate),
|
||||
"StatusClosedWontDo": reflect.ValueOf(constant.MakeFromLiteral("\"closed_wont_do\"", token.STRING, 0)),
|
||||
"StatusDead": reflect.ValueOf(constant.MakeFromLiteral("\"dead\"", token.STRING, 0)),
|
||||
"StatusMerged": reflect.ValueOf(constant.MakeFromLiteral("\"merged\"", token.STRING, 0)),
|
||||
"StatusPROpen": reflect.ValueOf(constant.MakeFromLiteral("\"pr_open\"", token.STRING, 0)),
|
||||
"StatusParked": reflect.ValueOf(constant.MakeFromLiteral("\"parked\"", token.STRING, 0)),
|
||||
"StatusQueued": reflect.ValueOf(constant.MakeFromLiteral("\"queued\"", token.STRING, 0)),
|
||||
"StatusRejected": reflect.ValueOf(constant.MakeFromLiteral("\"rejected\"", token.STRING, 0)),
|
||||
"StatusRunning": reflect.ValueOf(constant.MakeFromLiteral("\"running\"", token.STRING, 0)),
|
||||
"StatusWaitingHuman": reflect.ValueOf(constant.MakeFromLiteral("\"waiting_human\"", token.STRING, 0)),
|
||||
"TDD": reflect.ValueOf(workflow.TDD),
|
||||
"Triage": reflect.ValueOf(workflow.Triage),
|
||||
|
||||
@@ -70,15 +96,21 @@ func init() {
|
||||
"Outcome": reflect.ValueOf((*workflow.Outcome)(nil)),
|
||||
"Registry": reflect.ValueOf((*workflow.Registry)(nil)),
|
||||
"ReviewCategory": reflect.ValueOf((*workflow.ReviewCategory)(nil)),
|
||||
"ReviewCheck": reflect.ValueOf((*workflow.ReviewCheck)(nil)),
|
||||
"ReviewComment": reflect.ValueOf((*workflow.ReviewComment)(nil)),
|
||||
"ReviewDisposition": reflect.ValueOf((*workflow.ReviewDisposition)(nil)),
|
||||
"ReviewFinding": reflect.ValueOf((*workflow.ReviewFinding)(nil)),
|
||||
"ReviewLevel": reflect.ValueOf((*workflow.ReviewLevel)(nil)),
|
||||
"ReviewReport": reflect.ValueOf((*workflow.ReviewReport)(nil)),
|
||||
"ReviewRequest": reflect.ValueOf((*workflow.ReviewRequest)(nil)),
|
||||
"ReviewStatus": reflect.ValueOf((*workflow.ReviewStatus)(nil)),
|
||||
"ReviewUnit": reflect.ValueOf((*workflow.ReviewUnit)(nil)),
|
||||
"ReviewUnitComment": reflect.ValueOf((*workflow.ReviewUnitComment)(nil)),
|
||||
"ReviewVerdict": reflect.ValueOf((*workflow.ReviewVerdict)(nil)),
|
||||
"Reviewer": reflect.ValueOf((*workflow.Reviewer)(nil)),
|
||||
"Stage": reflect.ValueOf((*workflow.Stage)(nil)),
|
||||
"Store": reflect.ValueOf((*workflow.Store)(nil)),
|
||||
"Task": reflect.ValueOf((*workflow.Task)(nil)),
|
||||
"TaskContext": reflect.ValueOf((*workflow.TaskContext)(nil)),
|
||||
"Trees": reflect.ValueOf((*workflow.Trees)(nil)),
|
||||
"Workflow": reflect.ValueOf((*workflow.Workflow)(nil)),
|
||||
@@ -86,16 +118,20 @@ func init() {
|
||||
// interface wrapper definitions
|
||||
"_Forger": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Forger)(nil)),
|
||||
"_Reviewer": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer)(nil)),
|
||||
"_Store": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Store)(nil)),
|
||||
"_Trees": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Trees)(nil)),
|
||||
}
|
||||
}
|
||||
|
||||
// _github_com_samcharles93_archie_core_internal_domain_workflow_Forger is an interface wrapper for Forger type
|
||||
type _github_com_samcharles93_archie_core_internal_domain_workflow_Forger struct {
|
||||
IValue interface{}
|
||||
WCloseIssue func(ctx context.Context, owner string, repo string, number int, comment string) error
|
||||
WCreatePR func(ctx context.Context, owner string, repo string, title string, head string, base string, body string) (int, error)
|
||||
WLinkBranch func(ctx context.Context, owner string, repo string, issueNumber int, branch string) error
|
||||
IValue interface{}
|
||||
WCloseIssue func(ctx context.Context, owner string, repo string, number int, comment string) error
|
||||
WComment func(ctx context.Context, owner string, repo string, number int, body string) (int64, error)
|
||||
WCreatePR func(ctx context.Context, owner string, repo string, title string, head string, base string, body string) (int, error)
|
||||
WCreateReviewComments func(ctx context.Context, owner string, repo string, number int, reviewedHeadSHA string, comments []workflow.ReviewComment) error
|
||||
WLinkBranch func(ctx context.Context, owner string, repo string, issueNumber int, branch string) error
|
||||
WReplyToReview func(ctx context.Context, owner string, repo string, number int, commentID int64, body string) error
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) CloseIssue(ctx context.Context, owner string, repo string, number int, comment string) error {
|
||||
@@ -104,12 +140,28 @@ func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) Cl
|
||||
}
|
||||
return W.WCloseIssue(ctx, owner, repo, number, comment)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) Comment(ctx context.Context, owner string, repo string, number int, body string) (int64, error) {
|
||||
if W.WComment == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return W.WComment(ctx, owner, repo, number, body)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) CreatePR(ctx context.Context, owner string, repo string, title string, head string, base string, body string) (int, error) {
|
||||
if W.WCreatePR == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return W.WCreatePR(ctx, owner, repo, title, head, base, body)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) CreateReviewComments(ctx context.Context, owner string, repo string, number int, reviewedHeadSHA string, comments []workflow.ReviewComment) error {
|
||||
if W.WCreateReviewComments == nil {
|
||||
return nil
|
||||
}
|
||||
return W.WCreateReviewComments(ctx, owner, repo, number, reviewedHeadSHA, comments)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) LinkBranch(ctx context.Context, owner string, repo string, issueNumber int, branch string) error {
|
||||
if W.WLinkBranch == nil {
|
||||
return nil
|
||||
@@ -117,6 +169,13 @@ func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) Li
|
||||
return W.WLinkBranch(ctx, owner, repo, issueNumber, branch)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) ReplyToReview(ctx context.Context, owner string, repo string, number int, commentID int64, body string) error {
|
||||
if W.WReplyToReview == nil {
|
||||
return nil
|
||||
}
|
||||
return W.WReplyToReview(ctx, owner, repo, number, commentID, body)
|
||||
}
|
||||
|
||||
// _github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer is an interface wrapper for Reviewer type
|
||||
type _github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer struct {
|
||||
IValue interface{}
|
||||
@@ -130,6 +189,35 @@ func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer)
|
||||
return W.WReview(ctx, req)
|
||||
}
|
||||
|
||||
// _github_com_samcharles93_archie_core_internal_domain_workflow_Store is an interface wrapper for Store type
|
||||
type _github_com_samcharles93_archie_core_internal_domain_workflow_Store struct {
|
||||
IValue interface{}
|
||||
WInsertEvent func(ctx context.Context, e events.Event) (int64, error)
|
||||
WTransition func(ctx context.Context, taskID int64, from string, to string, detail string) error
|
||||
WUpdate func(ctx context.Context, t *task.Task) error
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Store) InsertEvent(ctx context.Context, e events.Event) (int64, error) {
|
||||
if W.WInsertEvent == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return W.WInsertEvent(ctx, e)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Store) Transition(ctx context.Context, taskID int64, from string, to string, detail string) error {
|
||||
if W.WTransition == nil {
|
||||
return nil
|
||||
}
|
||||
return W.WTransition(ctx, taskID, from, to, detail)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Store) Update(ctx context.Context, t *task.Task) error {
|
||||
if W.WUpdate == nil {
|
||||
return nil
|
||||
}
|
||||
return W.WUpdate(ctx, t)
|
||||
}
|
||||
|
||||
// _github_com_samcharles93_archie_core_internal_domain_workflow_Trees is an interface wrapper for Trees type
|
||||
type _github_com_samcharles93_archie_core_internal_domain_workflow_Trees struct {
|
||||
IValue interface{}
|
||||
@@ -148,36 +236,42 @@ func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Cha
|
||||
}
|
||||
return W.WChangedFiles(ctx, dir, base)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) ChangedLines(ctx context.Context, dir string, base string) (int, error) {
|
||||
if W.WChangedLines == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return W.WChangedLines(ctx, dir, base)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) CommitAll(ctx context.Context, dir string, message string) (bool, error) {
|
||||
if W.WCommitAll == nil {
|
||||
return false, nil
|
||||
}
|
||||
return W.WCommitAll(ctx, dir, message)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Diff(ctx context.Context, dir string, base string) (string, error) {
|
||||
if W.WDiff == nil {
|
||||
return "", nil
|
||||
}
|
||||
return W.WDiff(ctx, dir, base)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Prepare(ctx context.Context, owner string, repo string, base string, issue int, title string, body string, labels string) (dir string, branch string, err error) {
|
||||
if W.WPrepare == nil {
|
||||
return "", "", nil
|
||||
}
|
||||
return W.WPrepare(ctx, owner, repo, base, issue, title, body, labels)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Push(ctx context.Context, dir string, branch string) error {
|
||||
if W.WPush == nil {
|
||||
return nil
|
||||
}
|
||||
return W.WPush(ctx, dir, branch)
|
||||
}
|
||||
|
||||
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Snapshot(ctx context.Context, dir string, destDir string) error {
|
||||
if W.WSnapshot == nil {
|
||||
return nil
|
||||
|
||||
@@ -94,6 +94,16 @@ func TestWrapperNilGuardsPreserved(t *testing.T) {
|
||||
t.Errorf("LinkBranch on nil WLinkBranch = %v, want nil", err)
|
||||
}
|
||||
|
||||
if _, err := forger.Comment(context.Background(), "", "", 0, ""); err != nil {
|
||||
t.Errorf("Comment on nil WComment = %v, want nil", err)
|
||||
}
|
||||
if err := forger.ReplyToReview(context.Background(), "", "", 0, 0, ""); err != nil {
|
||||
t.Errorf("ReplyToReview on nil WReplyToReview = %v, want nil", err)
|
||||
}
|
||||
if err := forger.CreateReviewComments(context.Background(), "", "", 0, "", nil); err != nil {
|
||||
t.Errorf("CreateReviewComments on nil WCreateReviewComments = %v, want nil", err)
|
||||
}
|
||||
|
||||
var reviewer _github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer
|
||||
if got := reviewer.Review(context.Background(), workflow.ReviewRequest{}); len(got.Findings) != 0 || got.Status != "" || got.Summary != "" {
|
||||
t.Errorf("Review on nil WReview = %#v, want empty report", got)
|
||||
|
||||
@@ -24,12 +24,34 @@ import (
|
||||
)
|
||||
|
||||
// Forger is the subset of forge.Forge that workflow stages call mid-run.
|
||||
// forge.Forge (the daemon's real implementations) and forgerpc.Client
|
||||
// (archie-agent's NATS-backed proxy) both satisfy it.
|
||||
// Production reaches it through forgerpc.Client, which proxies each call to the
|
||||
// daemon over NATS -- the worker holds no forge credentials, so the daemon stays
|
||||
// the only caller of forge.Forge. Test fakes implement it directly.
|
||||
type Forger interface {
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error)
|
||||
LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error
|
||||
// CreateReviewComments posts line-anchored review comments on an open pull
|
||||
// request. The whole set travels in one call because Gitea's only inline
|
||||
// shape is a single submitted review holding many comments, and because
|
||||
// one call cannot half-succeed against a rate limit.
|
||||
//
|
||||
// reviewedHeadSHA is the revision those line numbers were measured on. The
|
||||
// implementation reads the pull request's head itself -- the worker holds no
|
||||
// forge credentials -- and posts only while that head is still this
|
||||
// revision, because a line number means nothing against a revision it was
|
||||
// not measured on. Empty means "not measured": the comments post without
|
||||
// the check rather than being dropped.
|
||||
CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []ReviewComment) error
|
||||
// Comment posts a plain, non-anchored PR comment and returns its ID.
|
||||
// The remediate workflow's round-cap stage uses this to tell an
|
||||
// operator why it stopped remediating, and a whole-review reply (no
|
||||
// single inline comment to thread onto) falls back to it.
|
||||
Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error)
|
||||
// ReplyToReview posts a threaded reply to one review comment. The
|
||||
// remediate workflow calls it once per remediation run, summarising
|
||||
// what changed (docs/prds/pr-review-remediation.md decision 4).
|
||||
ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error
|
||||
}
|
||||
|
||||
// Trees is the subset of *worktree.Manager that workflow stages call
|
||||
@@ -106,6 +128,10 @@ type TaskContext struct {
|
||||
ReproProof string
|
||||
// decision is the feasibility assess stage's verdict.
|
||||
decision *decision
|
||||
// reviewUnit is the remediate workflow's decoded Task.ReviewPayload,
|
||||
// stashed by its build stage so the commit-push and reply stages that
|
||||
// follow don't each re-decode the same JSON.
|
||||
reviewUnit ReviewUnit
|
||||
// Outcome describes where the task ended up; the engine applies it.
|
||||
Outcome Outcome
|
||||
|
||||
@@ -131,6 +157,15 @@ type TaskContext struct {
|
||||
// body (h019.6). Zero value means the review did not run (disabled or
|
||||
// skipped); ReviewReport.Ran() is the test for "render the section".
|
||||
ReviewReport ReviewReport
|
||||
// ReviewedHeadSHA is the worktree head at the moment the pull request was
|
||||
// opened, which is the revision the review's line numbers were measured on
|
||||
// (StageReview runs against that same worktree and commits nothing, so no
|
||||
// revision intervenes). StagePostReviewComments threads it to the forge so
|
||||
// a comment whose line numbers describe a head the pull request has since
|
||||
// moved past is refused instead of attaching to unrelated code. Empty when
|
||||
// the revision could not be read -- posting then proceeds unverified rather
|
||||
// than dropping every finding.
|
||||
ReviewedHeadSHA string
|
||||
}
|
||||
|
||||
// Emit publishes an observability event stamped with the task's
|
||||
|
||||
@@ -156,6 +156,53 @@ type PullRequestReviewReader interface {
|
||||
ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error
|
||||
}
|
||||
|
||||
// InlineReviewComment is one line-anchored comment to post on a PR: the file,
|
||||
// the line in the reviewed commit's version of it, and the body -- which may
|
||||
// carry a fenced suggestion block the author can apply in one click.
|
||||
type InlineReviewComment struct {
|
||||
Path string
|
||||
Line int
|
||||
Body string
|
||||
}
|
||||
|
||||
// ReviewCommentWriter posts line-anchored review comments on an open pull
|
||||
// request. Forge implementations that cannot (the noop forge) do not implement
|
||||
// it; callers type-assert and degrade to the PR-body list rather than faking it.
|
||||
//
|
||||
// The set travels in one call because that is Gitea's native shape (a single
|
||||
// COMMENT-state review carrying many comments); GitHub loops internally. Each
|
||||
// implementation reads the pull request's current head itself and anchors the
|
||||
// comments to it, but only after checking it against reviewedHeadSHA -- the
|
||||
// revision the caller's line numbers were measured on. A line number that
|
||||
// outlives its revision does not fail loudly at the forge: it attaches to
|
||||
// whatever is on that line now, so the set is refused once the head has moved.
|
||||
// An empty reviewedHeadSHA means the caller could not measure one, and posts
|
||||
// unanchored by revision rather than dropping every finding.
|
||||
type ReviewCommentWriter interface {
|
||||
CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []InlineReviewComment) error
|
||||
}
|
||||
|
||||
// reviewHeadDrift is the rule ReviewCommentWriter's implementations share: a
|
||||
// line-anchored comment set may be posted only while the pull request's head is
|
||||
// still the revision those line numbers were measured on. It returns nil when
|
||||
// there is nothing to refuse, including when the caller could not measure a
|
||||
// revision at all (reviewedHeadSHA == "") -- posting unverified is the
|
||||
// pre-existing behaviour, and is strictly better than dropping every finding.
|
||||
//
|
||||
// The check lives here rather than in each implementation because the danger is
|
||||
// identical on both: GitHub and Gitea accept a line number against the current
|
||||
// head and anchor it to whatever now occupies that line, so a stale anchor does
|
||||
// not fail loudly -- it misinforms.
|
||||
func reviewHeadDrift(owner, repo string, number int, head, reviewedHeadSHA string) error {
|
||||
if reviewedHeadSHA == "" || strings.EqualFold(head, reviewedHeadSHA) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf(
|
||||
"pull request %s/%s#%d has moved off the reviewed revision (%s): head is now %s, so the line-anchored comments would land on lines they were not measured against",
|
||||
owner, repo, number, reviewedHeadSHA, head,
|
||||
)
|
||||
}
|
||||
|
||||
// normalizeReviewState maps a GitHub review state string onto the neutral
|
||||
// ReviewState* constants. Unknown states pass through lowercased.
|
||||
func normalizeReviewState(s string) string {
|
||||
|
||||
@@ -238,6 +238,51 @@ func (c *GiteaClient) ReplyToReview(ctx context.Context, owner, repo string, num
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateReviewComments posts the line-anchored comments as one COMMENT-state
|
||||
// review, anchored to the pull request's head revision.
|
||||
//
|
||||
// Gitea has no standalone inline-comment call: inline comments are carried by a
|
||||
// submitted review, so a single review is both the native shape and the fewest
|
||||
// round trips. It is also all-or-nothing -- one comment Gitea refuses fails the
|
||||
// whole request, and the review carries nothing -- where GitHub's loop keeps the
|
||||
// comments it could post. The PR-body findings list is the fallback in either
|
||||
// case.
|
||||
//
|
||||
// The head SHA is read here rather than taken from the caller: it is what Gitea
|
||||
// anchors the review to, and the caller that produced the line numbers (a
|
||||
// workflow stage running in archie-agent) holds no forge credentials to read it
|
||||
// with. reviewedHeadSHA is the revision those line numbers were measured on, and
|
||||
// the review is refused outright if the head has moved past it -- see
|
||||
// reviewHeadDrift.
|
||||
func (c *GiteaClient) CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []InlineReviewComment) error {
|
||||
pr, err := c.GetPullRequest(ctx, owner, repo, number)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if pr.HeadSHA == "" {
|
||||
return fmt.Errorf("resolve head revision of %s/%s#%d: the forge reported no head sha", owner, repo, number)
|
||||
}
|
||||
if err := reviewHeadDrift(owner, repo, number, pr.HeadSHA, reviewedHeadSHA); err != nil {
|
||||
return err
|
||||
}
|
||||
reviewComments := make([]gitea.CreatePullReviewComment, 0, len(comments))
|
||||
for _, cm := range comments {
|
||||
reviewComments = append(reviewComments, gitea.CreatePullReviewComment{
|
||||
Path: cm.Path,
|
||||
Body: cm.Body,
|
||||
NewLineNum: int64(cm.Line),
|
||||
})
|
||||
}
|
||||
if _, _, err := c.cli.CreatePullReview(owner, repo, int64(number), gitea.CreatePullReviewOptions{
|
||||
State: gitea.ReviewStateComment,
|
||||
CommitID: pr.HeadSHA,
|
||||
Comments: reviewComments,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("create review comments on %s/%s#%d: %w", owner, repo, number, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// giteaReviewAuthor returns a review/comment author's login, or "" when the
|
||||
// author is absent (a team review, or a deleted user).
|
||||
func giteaReviewAuthor(u *gitea.User) string {
|
||||
|
||||
@@ -6,6 +6,7 @@ package forge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
@@ -260,6 +261,58 @@ func (c *GitHubClient) ReplyToReview(ctx context.Context, owner, repo string, nu
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateReviewComments posts line-anchored review comments, one GitHub call per
|
||||
// comment, anchored to the RIGHT (new) side of the pull request's head revision.
|
||||
//
|
||||
// The head SHA is read here rather than taken from the caller: it is what the
|
||||
// comments are anchored to, and the caller that produced the line numbers (a
|
||||
// workflow stage running in archie-agent) holds no forge credentials to read it
|
||||
// with. reviewedHeadSHA is the revision those line numbers were measured on, and
|
||||
// the set is refused outright if the head has moved past it -- see
|
||||
// reviewHeadDrift.
|
||||
//
|
||||
// A comment GitHub refuses -- a line that falls outside the diff, a file the
|
||||
// push renamed -- does not abandon the rest. The failures are joined and
|
||||
// returned, so one unanchorable finding cannot silently drop the others.
|
||||
func (c *GitHubClient) CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []InlineReviewComment) error {
|
||||
head, err := c.reviewHeadSHA(ctx, owner, repo, number)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := reviewHeadDrift(owner, repo, number, head, reviewedHeadSHA); err != nil {
|
||||
return err
|
||||
}
|
||||
var errs []error
|
||||
for _, cm := range comments {
|
||||
comment := &github.PullRequestComment{
|
||||
Body: new(cm.Body),
|
||||
Path: new(cm.Path),
|
||||
Line: new(cm.Line),
|
||||
Side: new("RIGHT"),
|
||||
CommitID: new(head),
|
||||
}
|
||||
if _, _, err := c.gh.PullRequests.CreateComment(ctx, owner, repo, number, comment); err != nil {
|
||||
errs = append(errs, fmt.Errorf("create review comment %s:%d on %s/%s#%d: %w", cm.Path, cm.Line, owner, repo, number, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// reviewHeadSHA resolves the commit a PR's line numbers are anchored to. A
|
||||
// forge that reports an empty head SHA is a failure, not an anchor: an empty
|
||||
// commit_id makes GitHub reject every comment in the set with nothing that says
|
||||
// why.
|
||||
func (c *GitHubClient) reviewHeadSHA(ctx context.Context, owner, repo string, number int) (string, error) {
|
||||
pr, err := c.GetPullRequest(ctx, owner, repo, number)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if pr.HeadSHA == "" {
|
||||
return "", fmt.Errorf("resolve head revision of %s/%s#%d: the forge reported no head sha", owner, repo, number)
|
||||
}
|
||||
return pr.HeadSHA, nil
|
||||
}
|
||||
|
||||
// CloseIssue closes an issue with a final comment (feasibility "won't do").
|
||||
func (c *GitHubClient) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
if comment != "" {
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGitHubCreateReviewComments(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
// The head SHA is deliberately not "headsha": the comments are anchored to
|
||||
// the revision the forge reports for the pull request, never to a value the
|
||||
// caller supplied. The caller's reviewed revision gates the posting, it is
|
||||
// not the anchor itself.
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "title": "Add widget", "state": "open",
|
||||
"head": map[string]any{"ref": "feature/widget", "sha": "pulled-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
var got []map[string]any
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, body)
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
comments := []InlineReviewComment{
|
||||
{Path: "a.go", Line: 12, Body: "nil deref"},
|
||||
{Path: "b.go", Line: 3, Body: "```suggestion\nfixed\n```"},
|
||||
}
|
||||
if err := c.CreateReviewComments(t.Context(), "o", "r", 7, "pulled-head-sha", comments); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("posted %d comments, want 2", len(got))
|
||||
}
|
||||
if got[0]["path"] != "a.go" || got[0]["line"] != float64(12) || got[0]["side"] != "RIGHT" {
|
||||
t.Errorf("comment[0] = %v, want path=a.go line=12 side=RIGHT", got[0])
|
||||
}
|
||||
if got[0]["commit_id"] != "pulled-head-sha" {
|
||||
t.Errorf("comment[0].commit_id = %v, want the head pull requests.Get reported", got[0]["commit_id"])
|
||||
}
|
||||
if got[1]["body"] != "```suggestion\nfixed\n```" {
|
||||
t.Errorf("comment[1].body = %v, want the suggestion block preserved", got[1]["body"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubCreateReviewCommentsKeepsGoingAfterARefusal pins that one comment
|
||||
// GitHub will not accept -- a line outside the diff, a file the push renamed --
|
||||
// cannot silently drop the comments after it.
|
||||
func TestGitHubCreateReviewCommentsKeepsGoingAfterARefusal(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open",
|
||||
"head": map[string]any{"ref": "f", "sha": "headsha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
attempts := 0
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 2})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "headsha", []InlineReviewComment{
|
||||
{Path: "a.go", Line: 1, Body: "refused"},
|
||||
{Path: "b.go", Line: 2, Body: "accepted"},
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("CreateReviewComments error = nil, want the refused comment surfaced")
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Errorf("attempted %d comments, want 2: a refusal must not abandon the rest", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubCreateReviewCommentsRefusesAnEmptyHeadSHA guards the anchor itself.
|
||||
// An empty commit_id makes GitHub reject every comment with nothing that says
|
||||
// why, so it fails before the first request instead.
|
||||
func TestGitHubCreateReviewCommentsRefusesAnEmptyHeadSHA(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open",
|
||||
"head": map[string]any{"ref": "f"}, "base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
posted := false
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
posted = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 1, Body: "x"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a missing-head-sha error")
|
||||
}
|
||||
if posted {
|
||||
t.Error("a comment was posted despite no head sha to anchor it to")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubCreateReviewCommentsRefusesAMovedHead is the q9au drift guard. The
|
||||
// line numbers in a finding describe one revision; if the pull request's head
|
||||
// has moved since the review, GitHub anchors a line number against the CURRENT
|
||||
// file and attaches the comment to whatever now occupies that line rather than
|
||||
// failing. So the set is refused before the first comment is attempted, and the
|
||||
// PR body remains the record.
|
||||
func TestGitHubCreateReviewCommentsRefusesAMovedHead(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open",
|
||||
"head": map[string]any{"ref": "f", "sha": "moved-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
posted := false
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
posted = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 12, Body: "nil deref"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a refusal for a head that moved off the reviewed revision")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "reviewed-sha") || !strings.Contains(err.Error(), "moved-head-sha") {
|
||||
t.Errorf("error = %v, want it to name both revisions so an operator can tell what moved", err)
|
||||
}
|
||||
if posted {
|
||||
t.Error("a comment was anchored to a revision its line numbers were not measured on")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreateReviewComments(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "title": "Add widget", "state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "feature/widget", "sha": "pulled-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
var got map[string]any
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
comments := []InlineReviewComment{
|
||||
{Path: "a.go", Line: 12, Body: "nil deref"},
|
||||
{Path: "b.go", Line: 3, Body: "race"},
|
||||
}
|
||||
if err := c.CreateReviewComments(t.Context(), "o", "r", 7, "pulled-head-sha", comments); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Gitea carries inline comments on one COMMENT-state review.
|
||||
if got["event"] != "COMMENT" || got["commit_id"] != "pulled-head-sha" {
|
||||
t.Errorf("review = %v, want event=COMMENT and the reported head sha", got)
|
||||
}
|
||||
posted, _ := got["comments"].([]any)
|
||||
if len(posted) != 2 {
|
||||
t.Fatalf("review carried %d comments, want 2", len(posted))
|
||||
}
|
||||
first, _ := posted[0].(map[string]any)
|
||||
if first["path"] != "a.go" || first["new_position"] != float64(12) {
|
||||
t.Errorf("comments[0] = %v, want path=a.go new_position=12", first)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreateReviewCommentsRefusesAnEmptyHeadSHA(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "f"}, "base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
reviewed := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
reviewed = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 1, Body: "x"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a missing-head-sha error")
|
||||
}
|
||||
if reviewed {
|
||||
t.Error("a review was submitted despite no head sha to anchor it to")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiteaCreateReviewCommentsRefusesAMovedHead is the Gitea half of the q9au
|
||||
// drift guard: the same refusal, reached before the review is submitted, because
|
||||
// Gitea's inline comments live on that one review and a wrong line is applied
|
||||
// with one click.
|
||||
func TestGiteaCreateReviewCommentsRefusesAMovedHead(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "f", "sha": "moved-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
reviewed := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
reviewed = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 12, Body: "nil deref"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a refusal for a head that moved off the reviewed revision")
|
||||
}
|
||||
if reviewed {
|
||||
t.Error("a review was submitted against a revision its line numbers were not measured on")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReviewCommentWriterIsOptional pins the degrade path the forgerpc server
|
||||
// relies on: a forge that cannot post inline comments must not satisfy the
|
||||
// interface, so the caller is told rather than handed a silent no-op.
|
||||
func TestReviewCommentWriterIsOptional(t *testing.T) {
|
||||
if _, ok := any(&NoopForge{}).(ReviewCommentWriter); ok {
|
||||
t.Error("NoopForge satisfies ReviewCommentWriter; the capability must be absent, not faked")
|
||||
}
|
||||
for _, c := range []any{&GitHubClient{}, &GiteaClient{}} {
|
||||
if _, ok := c.(ReviewCommentWriter); !ok {
|
||||
t.Errorf("%T does not satisfy ReviewCommentWriter", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Compile-time guard: the workflow stage reaches this through a Forger whose
|
||||
// signature carries the domain's own comment value, so the conversion is the
|
||||
// caller's. The interface carries the revision the caller MEASURED, never a
|
||||
// commit to anchor to: the anchor stays a per-forge detail (GitHub pins
|
||||
// commit_id, Gitea anchors the review), while the caller's revision is only ever
|
||||
// compared against the head the forge reads for itself.
|
||||
var _ = func(ctx context.Context, c ReviewCommentWriter) error {
|
||||
return c.CreateReviewComments(ctx, "o", "r", 1, "reviewed-sha", nil)
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
// Package forgerpc lets archie-agent call the forge methods workflow stages
|
||||
// invoke mid-run -- CloseIssue, CreatePR and LinkBranch, the workflow.Forger
|
||||
// set -- over core NATS request/reply, instead of the agent container holding
|
||||
// a live forge API token. archied remains the sole holder of forge credentials
|
||||
// and the sole caller of forge.Forge.
|
||||
// invoke mid-run -- CloseIssue, CreatePR, LinkBranch, CreateReviewComments,
|
||||
// Comment and ReplyToReview, the workflow.Forger set -- over core NATS
|
||||
// request/reply, instead of the agent
|
||||
// container holding a live forge API token. archied remains the sole holder of
|
||||
// forge credentials and the sole caller of forge.Forge.
|
||||
//
|
||||
// The rest of forge.Forge (issue polling, invitations, reactions, PR-state
|
||||
// reconciliation) is used exclusively by the daemon's own poll/reconcile
|
||||
@@ -15,11 +16,16 @@
|
||||
// against an OLD daemon has no LinkBranch handler to reach, and the request
|
||||
// times out, so an image skew that way parks tasks. Note it in release notes
|
||||
// rather than assuming either side can lag.
|
||||
//
|
||||
// CreateReviewComments is the one method whose absence does NOT park a task: the
|
||||
// stage that calls it is best-effort by design, so the same new-agent/old-daemon
|
||||
// skew costs the inline comments and leaves the PR-body findings list intact.
|
||||
package forgerpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
@@ -27,16 +33,19 @@ import (
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
SubjectComment = "archie.forge.comment"
|
||||
SubjectCloseIssue = "archie.forge.close_issue"
|
||||
SubjectCreatePR = "archie.forge.create_pr"
|
||||
SubjectLinkBranch = "archie.forge.link_branch"
|
||||
SubjectSetStateLabel = "archie.forge.set_state_label"
|
||||
SubjectComment = "archie.forge.comment"
|
||||
SubjectCloseIssue = "archie.forge.close_issue"
|
||||
SubjectCreatePR = "archie.forge.create_pr"
|
||||
SubjectLinkBranch = "archie.forge.link_branch"
|
||||
SubjectSetStateLabel = "archie.forge.set_state_label"
|
||||
SubjectCreateReviewComment = "archie.forge.create_review_comments"
|
||||
SubjectReplyToReview = "archie.forge.reply_to_review"
|
||||
)
|
||||
|
||||
// SubjectFor returns the subject for base, scoped to identity when set.
|
||||
@@ -91,6 +100,40 @@ type SetStateLabelRequest struct {
|
||||
KnownLabels []string
|
||||
}
|
||||
|
||||
// CreateReviewCommentsRequest carries one review's worth of line-anchored
|
||||
// comments. The payload mirrors workflow.ReviewComment rather than reusing it:
|
||||
// the wire shape is a contract between two processes that can be at different
|
||||
// versions, so it is stated here instead of inherited from a type that may be
|
||||
// renamed or reshaped for reasons that never crossed the wire.
|
||||
type CreateReviewCommentsRequest struct {
|
||||
Owner, Repo string
|
||||
Number int
|
||||
// ReviewedHeadSHA is the revision the comments' line numbers were measured
|
||||
// on, which the worker records when it opens the pull request. It is
|
||||
// additive on the wire: a worker that predates it omits the field and the
|
||||
// server posts unverified (the pre-existing behaviour) rather than refusing
|
||||
// every set, and a server that predates it ignores the field. Neither
|
||||
// direction breaks, and neither silently mints a revision that was never
|
||||
// measured.
|
||||
ReviewedHeadSHA string
|
||||
Comments []InlineReviewCommentPayload
|
||||
}
|
||||
|
||||
// InlineReviewCommentPayload is one comment on the wire.
|
||||
type InlineReviewCommentPayload struct {
|
||||
Path string
|
||||
Line int
|
||||
Body string
|
||||
}
|
||||
|
||||
// ReplyToReviewRequest carries one threaded reply to a review comment.
|
||||
type ReplyToReviewRequest struct {
|
||||
Owner, Repo string
|
||||
Number int
|
||||
CommentID int64
|
||||
Body string
|
||||
}
|
||||
|
||||
// Response is a bare success/error envelope for calls with no return value.
|
||||
type Response struct {
|
||||
natsrpc.Envelope
|
||||
@@ -118,6 +161,8 @@ func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func()
|
||||
{Subject: SubjectFor(identity, SubjectCreatePR), Handler: s.handleCreatePR},
|
||||
{Subject: SubjectFor(identity, SubjectLinkBranch), Handler: s.handleLinkBranch},
|
||||
{Subject: SubjectFor(identity, SubjectSetStateLabel), Handler: s.handleSetStateLabel},
|
||||
{Subject: SubjectFor(identity, SubjectCreateReviewComment), Handler: s.handleCreateReviewComments},
|
||||
{Subject: SubjectFor(identity, SubjectReplyToReview), Handler: s.handleReplyToReview},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -161,6 +206,40 @@ func (s *Server) handleLinkBranch(msg *nats.Msg) {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateReviewComments(msg *nats.Msg) {
|
||||
var req CreateReviewCommentsRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode create_review_comments request: %w", err))})
|
||||
return
|
||||
}
|
||||
writer, ok := s.Forge.(forge.ReviewCommentWriter)
|
||||
if !ok {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(errors.New("this forge cannot post review comments"))})
|
||||
return
|
||||
}
|
||||
comments := make([]forge.InlineReviewComment, 0, len(req.Comments))
|
||||
for _, cm := range req.Comments {
|
||||
comments = append(comments, forge.InlineReviewComment{Path: cm.Path, Line: cm.Line, Body: cm.Body})
|
||||
}
|
||||
err := writer.CreateReviewComments(context.Background(), req.Owner, req.Repo, req.Number, req.ReviewedHeadSHA, comments)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleReplyToReview(msg *nats.Msg) {
|
||||
var req ReplyToReviewRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode reply_to_review request: %w", err))})
|
||||
return
|
||||
}
|
||||
reader, ok := s.Forge.(forge.PullRequestReviewReader)
|
||||
if !ok {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(errors.New("this forge cannot reply to reviews"))})
|
||||
return
|
||||
}
|
||||
err := reader.ReplyToReview(context.Background(), req.Owner, req.Repo, req.Number, req.CommentID, req.Body)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetStateLabel(msg *nats.Msg) {
|
||||
var req SetStateLabelRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
@@ -244,3 +323,37 @@ func (c *Client) SetStateLabel(ctx context.Context, owner, repo string, number i
|
||||
req := SetStateLabelRequest{Owner: owner, Repo: repo, Number: number, Label: label, KnownLabels: knownLabels}
|
||||
_, _ = natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectSetStateLabel), req)
|
||||
}
|
||||
|
||||
// CreateReviewComments posts the review's line-anchored findings on the pull
|
||||
// request. It is the one proxied method a workflow stage treats as best-effort,
|
||||
// which is why it is also the one whose failure cannot park a task.
|
||||
//
|
||||
// reviewedHeadSHA travels with the call so the daemon -- the only side holding
|
||||
// forge credentials, and so the only side that can read a pull request's head --
|
||||
// can refuse a set whose line numbers describe a revision the PR has left.
|
||||
func (c *Client) CreateReviewComments(ctx context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []workflow.ReviewComment) error {
|
||||
payload := make([]InlineReviewCommentPayload, 0, len(comments))
|
||||
for _, cm := range comments {
|
||||
payload = append(payload, InlineReviewCommentPayload{Path: cm.Path, Line: cm.Line, Body: cm.Body})
|
||||
}
|
||||
req := CreateReviewCommentsRequest{
|
||||
Owner: owner, Repo: repo, Number: number,
|
||||
ReviewedHeadSHA: reviewedHeadSHA, Comments: payload,
|
||||
}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectCreateReviewComment), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// ReplyToReview posts a threaded reply to one review comment, on behalf of
|
||||
// the remediate workflow.
|
||||
func (c *Client) ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error {
|
||||
req := ReplyToReviewRequest{Owner: owner, Repo: repo, Number: number, CommentID: commentID, Body: body}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectReplyToReview), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return resp.Err()
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
)
|
||||
|
||||
@@ -44,6 +46,16 @@ type fakeForge struct {
|
||||
commentErr error
|
||||
closeErr error
|
||||
prErr error
|
||||
|
||||
reviews []reviewCommentsCall
|
||||
reviewErr error
|
||||
}
|
||||
|
||||
type reviewCommentsCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
reviewedSHA string
|
||||
comments []forge.InlineReviewComment
|
||||
}
|
||||
|
||||
type commentCall struct {
|
||||
@@ -100,6 +112,13 @@ func (f *fakeForge) LinkBranch(_ context.Context, owner, repo string, number int
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateReviewComments makes fakeForge satisfy forge.ReviewCommentWriter, the
|
||||
// optional capability the server type-asserts.
|
||||
func (f *fakeForge) CreateReviewComments(_ context.Context, owner, repo string, number int, reviewedHeadSHA string, comments []forge.InlineReviewComment) error {
|
||||
f.reviews = append(f.reviews, reviewCommentsCall{owner: owner, repo: repo, number: number, reviewedSHA: reviewedHeadSHA, comments: comments})
|
||||
return f.reviewErr
|
||||
}
|
||||
|
||||
func (f *fakeForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
|
||||
func (f *fakeForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
@@ -193,6 +212,88 @@ func TestClientLinkBranchPersistsViaServer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCreateReviewCommentsPersistsViaServer(t *testing.T) {
|
||||
fg, client := newTestServer(t)
|
||||
|
||||
comments := []workflow.ReviewComment{
|
||||
{Path: "a.go", Line: 12, Body: "**confirmed (warn)**: nil deref\n\n```suggestion\nreturn nil\n```"},
|
||||
{Path: "b.go", Line: 3, Body: "**plausible (warn)**: possible race"},
|
||||
}
|
||||
if err := client.CreateReviewComments(context.Background(), "acme", "widget", 7, "reviewed-head-sha", comments); err != nil {
|
||||
t.Fatalf("CreateReviewComments: %v", err)
|
||||
}
|
||||
if len(fg.reviews) != 1 {
|
||||
t.Fatalf("reviews reached server %d times, want 1 batch", len(fg.reviews))
|
||||
}
|
||||
got := fg.reviews[0]
|
||||
if got.owner != "acme" || got.repo != "widget" || got.number != 7 {
|
||||
t.Errorf("anchored at %s/%s#%d, want acme/widget#7", got.owner, got.repo, got.number)
|
||||
}
|
||||
// The daemon is the only side that can read a pull request's head, so the
|
||||
// revision the worker measured has to survive the round trip for the drift
|
||||
// check to have anything to compare against.
|
||||
if got.reviewedSHA != "reviewed-head-sha" {
|
||||
t.Errorf("server saw reviewed head %q, want the worker's measured revision", got.reviewedSHA)
|
||||
}
|
||||
want := []forge.InlineReviewComment{
|
||||
{Path: "a.go", Line: 12, Body: comments[0].Body},
|
||||
{Path: "b.go", Line: 3, Body: comments[1].Body},
|
||||
}
|
||||
if !slices.Equal(got.comments, want) {
|
||||
t.Errorf("comments = %+v, want %+v", got.comments, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientCreateReviewCommentsReportsAnIncapableForge is the degrade path: a
|
||||
// forge without the optional writer must answer with an error the best-effort
|
||||
// stage can log, not a silent success that leaves the operator believing
|
||||
// comments were posted.
|
||||
func TestClientCreateReviewCommentsReportsAnIncapableForge(t *testing.T) {
|
||||
fg := &fakeForge{}
|
||||
srv := startEmbedded(t)
|
||||
serverConn := connect(t, srv.ClientURL())
|
||||
// Embedding the forge.Forge INTERFACE (not the fake) keeps the promoted
|
||||
// method set free of CreateReviewComments, which is what makes the type
|
||||
// assertion fail -- exactly as it does for the noop forge.
|
||||
rpcServer := &Server{Forge: noReviewCommentsForge{Forge: fg}, Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
t.Cleanup(unsub)
|
||||
|
||||
client := &Client{Conn: connect(t, srv.ClientURL()), Timeout: 2 * time.Second}
|
||||
err = client.CreateReviewComments(context.Background(), "acme", "widget", 7, "reviewed-sha", []workflow.ReviewComment{{Path: "a.go", Line: 1, Body: "x"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want an incapable-forge error")
|
||||
}
|
||||
if len(fg.reviews) != 0 {
|
||||
t.Errorf("the forge was called %d times despite lacking the capability", len(fg.reviews))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCreateReviewCommentsPropagatesAForgeError(t *testing.T) {
|
||||
fg := &fakeForge{reviewErr: errors.New("422 line is not part of the diff")}
|
||||
srv := startEmbedded(t)
|
||||
serverConn := connect(t, srv.ClientURL())
|
||||
rpcServer := &Server{Forge: fg, Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
t.Cleanup(unsub)
|
||||
|
||||
client := &Client{Conn: connect(t, srv.ClientURL()), Timeout: 2 * time.Second}
|
||||
err = client.CreateReviewComments(context.Background(), "acme", "widget", 7, "reviewed-sha", []workflow.ReviewComment{{Path: "a.go", Line: 1, Body: "x"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want the forge failure surfaced")
|
||||
}
|
||||
}
|
||||
|
||||
// noReviewCommentsForge is a forge.Forge whose method set lacks the optional
|
||||
// review-comment writer.
|
||||
type noReviewCommentsForge struct{ forge.Forge }
|
||||
|
||||
func TestClientPropagatesServerError(t *testing.T) {
|
||||
fg := &fakeForge{commentErr: errors.New("forge unavailable")}
|
||||
srv := startEmbedded(t)
|
||||
|
||||
@@ -1,66 +1,21 @@
|
||||
package gateway
|
||||
|
||||
import "context"
|
||||
import "github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
|
||||
// SendResult captures the outcome of a platform media delivery. It classifies
|
||||
// failures so callers can apply retry policy without inspecting
|
||||
// platform-specific error types.
|
||||
type SendResult struct {
|
||||
// MessageID is the platform-assigned identifier of the sent message.
|
||||
// Empty when the send failed before the platform acknowledged it.
|
||||
MessageID string
|
||||
|
||||
// Success is true when the platform accepted the message.
|
||||
Success bool
|
||||
|
||||
// Retryable is true when the failure is transient and the caller may
|
||||
// retry with backoff.
|
||||
Retryable bool
|
||||
|
||||
// Error is the underlying error when Success is false.
|
||||
Error error
|
||||
|
||||
// ErrorCode classifies the failure for observability and retry policy.
|
||||
// Current values are "rate_limited", "network", "auth",
|
||||
// "invalid_message", and "internal"; success uses the empty string.
|
||||
ErrorCode string
|
||||
}
|
||||
// SendResult captures the outcome of a platform media delivery.
|
||||
type SendResult = messaging.SendResult
|
||||
|
||||
// AdapterCapabilities reports which optional delivery behaviors a sender
|
||||
// implements, so callers can check support before attempting an optional call.
|
||||
type AdapterCapabilities struct {
|
||||
// Media is true when the sender implements MediaSender.
|
||||
Media bool
|
||||
}
|
||||
// implements.
|
||||
type AdapterCapabilities = messaging.AdapterCapabilities
|
||||
|
||||
// MediaSender delivers a MessageEvent carrying MediaAttachments (image,
|
||||
// video, audio, document) through a platform-specific media API. Senders are
|
||||
// launch-scoped delivery values, separate from a channel's connection
|
||||
// lifecycle; for example, Telegram binds one to a bot launch and chat.
|
||||
type MediaSender interface {
|
||||
SendMedia(ctx context.Context, event MessageEvent) (SendResult, error)
|
||||
}
|
||||
// MediaSender delivers a MessageEvent carrying MediaAttachments.
|
||||
type MediaSender = messaging.MediaSender
|
||||
|
||||
// CapabilityReporter is the optional interface a sender implements to
|
||||
// self-report which optional behaviors it supports. Callers should go
|
||||
// through CapabilitiesOf rather than type-asserting this directly, so an
|
||||
// implementation's capability declaration is checked consistently.
|
||||
type CapabilityReporter interface {
|
||||
Capabilities() AdapterCapabilities
|
||||
}
|
||||
// CapabilityReporter is the optional interface a sender implements.
|
||||
type CapabilityReporter = messaging.CapabilityReporter
|
||||
|
||||
// CapabilitiesOf reports which optional behaviors sender supports. One that
|
||||
// implements CapabilityReporter is asked directly; one that doesn't is
|
||||
// treated as reporting the zero value regardless of which optional
|
||||
// interfaces it actually implements under the hood, which is itself the
|
||||
// contract every Capabilities() implementation must honor -- see the
|
||||
// regression coverage in adapter_capabilities_test.go.
|
||||
//
|
||||
// It takes any deliberately: media is delivered by launch-scoped sender
|
||||
// values, not by a channel lifecycle interface.
|
||||
// CapabilitiesOf reports which optional behaviors sender supports.
|
||||
func CapabilitiesOf(sender any) AdapterCapabilities {
|
||||
if reporter, ok := sender.(CapabilityReporter); ok {
|
||||
return reporter.Capabilities()
|
||||
}
|
||||
return AdapterCapabilities{}
|
||||
return messaging.CapabilitiesOf(sender)
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func (a *LocalChatAdapter) Snapshot(ctx context.Context) (ChatSnapshot, error) {
|
||||
if err != nil {
|
||||
return ChatSnapshot{}, err
|
||||
}
|
||||
s := ChatSnapshot{Sessions: sessions, Models: []string{}, Providers: []string{}, Personas: []string{}, ModelsByProvider: map[string][]string{}, ActivePersonas: map[string]string{}, RestartAvailable: a.Router.Restart != nil, CancellationAvailable: a.Turns != nil, PersonasAvailable: a.Personas != nil}
|
||||
s := ChatSnapshot{Sessions: sessions, Models: []string{}, Providers: []string{}, Personas: []string{}, ModelsByProvider: map[string][]string{}, ActivePersonas: map[string]string{}, RestartAvailable: a.Router.Restart != nil, CancellationAvailable: a.Turns != nil, PersonasAvailable: a.Personas != nil, Version: a.Router.Version}
|
||||
if a.Models != nil {
|
||||
s.Models = slices.Clone(a.Models.Models())
|
||||
s.ActiveModel = a.Models.ActiveModel()
|
||||
|
||||
@@ -26,25 +26,8 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// Lifecycle receives adapter-owned startup facts. Callbacks are optional.
|
||||
// Starting is reported before each launch attempt; Running is reported only
|
||||
// after the adapter's external delivery boundary is ready.
|
||||
type Lifecycle struct {
|
||||
Starting func()
|
||||
Running func()
|
||||
}
|
||||
|
||||
func (l Lifecycle) ReportStarting() {
|
||||
if l.Starting != nil {
|
||||
l.Starting()
|
||||
}
|
||||
}
|
||||
|
||||
func (l Lifecycle) ReportRunning() {
|
||||
if l.Running != nil {
|
||||
l.Running()
|
||||
}
|
||||
}
|
||||
// Lifecycle receives adapter-owned startup facts.
|
||||
type Lifecycle = messaging.Lifecycle
|
||||
|
||||
// A Gateway owns a persistent connection to a chat channel. Start blocks;
|
||||
// the gateway should remain running until ctx is cancelled or Stop is called.
|
||||
@@ -106,17 +89,7 @@ type ProviderModelManager interface {
|
||||
|
||||
// ModelDetails is the catalog metadata rendered after an interactive model
|
||||
// selection. Limits are zero when the upstream catalog does not publish them.
|
||||
type ModelDetails struct {
|
||||
Ref string
|
||||
Name string
|
||||
ContextWindow int
|
||||
MaxOutputTokens int
|
||||
Reasoning bool
|
||||
Tools bool
|
||||
Attachment bool
|
||||
Structured bool
|
||||
InputModalities []string
|
||||
}
|
||||
type ModelDetails = messaging.ModelDetails
|
||||
|
||||
// DetailedModelManager is the optional catalog-aware extension used by rich
|
||||
// model selectors. Runtime routing remains on ModelManager.
|
||||
|
||||
@@ -1,92 +1,6 @@
|
||||
package gateway
|
||||
|
||||
// MessageEvent is the rich message model for all gateway channels. It
|
||||
// carries the platform detail an adapter needs beyond the persisted
|
||||
// record, and keeps the Text() and FromID() helpers for callers that only
|
||||
// want a sender and a body.
|
||||
//
|
||||
// Every field except Type is optional. A minimal text message needs
|
||||
// only Type=MsgText, Text, ChannelID, Platform, and SenderID.
|
||||
type MessageEvent struct {
|
||||
// Type discriminates the message kind.
|
||||
Type MessageType `json:"type"`
|
||||
import "github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
|
||||
// Text is the human-readable message body. It carries the caption
|
||||
// for media messages and the full content for text and system
|
||||
// messages.
|
||||
Text string `json:"text,omitempty"`
|
||||
|
||||
// ── Identifiers ──────────────────────────────────────────────
|
||||
|
||||
// ID is the platform-assigned message identifier. Used for reply
|
||||
// threading, reactions, and edit/delete tracking.
|
||||
ID string `json:"id,omitempty"`
|
||||
|
||||
// ChannelID identifies the conversation within the platform
|
||||
// (chat ID, channel name, DM thread).
|
||||
ChannelID string `json:"channel_id"`
|
||||
|
||||
// Platform names the source adapter ("telegram", "discord",
|
||||
// "web", "slack").
|
||||
Platform string `json:"platform"`
|
||||
|
||||
// ── Sender ───────────────────────────────────────────────────
|
||||
|
||||
// SenderID is the platform-specific sender identifier.
|
||||
SenderID string `json:"sender_id"`
|
||||
|
||||
// SenderName is the display name when available.
|
||||
SenderName string `json:"sender_name,omitempty"`
|
||||
|
||||
// ── Threading ────────────────────────────────────────────────
|
||||
|
||||
// ReplyToID is the platform message ID this message is in reply
|
||||
// to. Empty for top-level messages.
|
||||
ReplyToID string `json:"reply_to_id,omitempty"`
|
||||
|
||||
// ThreadID identifies the conversation thread for platforms that
|
||||
// support threading (Slack, Discord forums).
|
||||
ThreadID string `json:"thread_id,omitempty"`
|
||||
|
||||
// ── Media ────────────────────────────────────────────────────
|
||||
|
||||
// Media holds attached files. Nil for text-only messages.
|
||||
Media []MediaAttachment `json:"media,omitempty"`
|
||||
|
||||
// ── Edit tracking ────────────────────────────────────────────
|
||||
|
||||
// EditedFrom is the original text before the edit. Set only when
|
||||
// Type is MsgEdited.
|
||||
EditedFrom string `json:"edited_from,omitempty"`
|
||||
|
||||
// ── Reactions ────────────────────────────────────────────────
|
||||
|
||||
// Reaction is the emoji used when Type is MsgReaction.
|
||||
Reaction string `json:"reaction,omitempty"`
|
||||
|
||||
// ReactedToID is the message being reacted to.
|
||||
ReactedToID string `json:"reacted_to_id,omitempty"`
|
||||
|
||||
// ── Callbacks ────────────────────────────────────────────────
|
||||
|
||||
// CallbackData is the payload from a button or inline-keyboard
|
||||
// press (Type == MsgCallback).
|
||||
CallbackData string `json:"callback_data,omitempty"`
|
||||
|
||||
// ── Timestamp ────────────────────────────────────────────────
|
||||
|
||||
// Timestamp is the platform-assigned message time in Unix
|
||||
// milliseconds. Zero when unknown.
|
||||
Timestamp int64 `json:"timestamp,omitempty"`
|
||||
|
||||
// ── Platform payload ─────────────────────────────────────────
|
||||
|
||||
// Raw is the original platform-specific payload. Adapters set
|
||||
// this for debug logging or handlers that need platform details
|
||||
// not captured by the generic fields.
|
||||
Raw map[string]any `json:"raw,omitempty"`
|
||||
}
|
||||
|
||||
// FromID returns the sender identifier, under the name callers that only
|
||||
// need a sender use.
|
||||
func (e MessageEvent) FromID() string { return e.SenderID }
|
||||
// MessageEvent is the rich message model for all gateway channels.
|
||||
type MessageEvent = messaging.MessageEvent
|
||||
@@ -1,79 +1,22 @@
|
||||
package gateway
|
||||
|
||||
// MessageType discriminates inbound gateway messages. Every MessageEvent
|
||||
// carries a type so handlers can branch on message kind without inspecting
|
||||
// the raw platform payload.
|
||||
type MessageType string
|
||||
import "github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
|
||||
// MessageType discriminates inbound gateway messages.
|
||||
type MessageType = messaging.MessageType
|
||||
|
||||
const (
|
||||
// MsgText is a plain text message.
|
||||
MsgText MessageType = "text"
|
||||
|
||||
// MsgImage is a message with an image attachment.
|
||||
MsgImage MessageType = "image"
|
||||
|
||||
// MsgVideo is a message with a video attachment.
|
||||
MsgVideo MessageType = "video"
|
||||
|
||||
// MsgAudio is a message with an audio attachment (voice note, etc.).
|
||||
MsgAudio MessageType = "audio"
|
||||
|
||||
// MsgDocument is a message with a file attachment.
|
||||
MsgDocument MessageType = "document"
|
||||
|
||||
// MsgLocation is a shared location.
|
||||
MsgLocation MessageType = "location"
|
||||
|
||||
// MsgSticker is a sticker or animated emoji.
|
||||
MsgSticker MessageType = "sticker"
|
||||
|
||||
// MsgContact is a shared contact card.
|
||||
MsgContact MessageType = "contact"
|
||||
|
||||
// MsgCallback is a button press or inline keyboard interaction.
|
||||
MsgCallback MessageType = "callback"
|
||||
|
||||
// MsgReaction is an emoji reaction on a prior message.
|
||||
MsgReaction MessageType = "reaction"
|
||||
|
||||
// MsgEdited signals that a prior message text was changed.
|
||||
MsgEdited MessageType = "edited"
|
||||
|
||||
// MsgDeleted signals that a prior message was removed.
|
||||
MsgDeleted MessageType = "deleted"
|
||||
|
||||
// MsgSystem is a non-user system event (member join/leave, etc.).
|
||||
MsgSystem MessageType = "system"
|
||||
MsgText = messaging.MsgText
|
||||
MsgImage = messaging.MsgImage
|
||||
MsgVideo = messaging.MsgVideo
|
||||
MsgAudio = messaging.MsgAudio
|
||||
MsgDocument = messaging.MsgDocument
|
||||
MsgLocation = messaging.MsgLocation
|
||||
MsgSticker = messaging.MsgSticker
|
||||
MsgContact = messaging.MsgContact
|
||||
MsgCallback = messaging.MsgCallback
|
||||
MsgReaction = messaging.MsgReaction
|
||||
MsgEdited = messaging.MsgEdited
|
||||
MsgDeleted = messaging.MsgDeleted
|
||||
MsgSystem = messaging.MsgSystem
|
||||
)
|
||||
|
||||
// IsMedia reports whether the type carries a media attachment.
|
||||
func (t MessageType) IsMedia() bool {
|
||||
switch t {
|
||||
case MsgImage, MsgVideo, MsgAudio, MsgDocument, MsgSticker:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsEphemeral reports whether the type is a transient signal
|
||||
// (typing indicators, read receipts) that should not be stored.
|
||||
// Note: MsgEdited is NOT ephemeral -- it carries content (original
|
||||
// and updated text) that must be persisted to avoid serving stale data.
|
||||
func (t MessageType) IsEphemeral() bool {
|
||||
switch t {
|
||||
case MsgReaction, MsgDeleted:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsRich reports whether the type requires a MessageEvent with
|
||||
// structured fields rather than a plain text fallback.
|
||||
func (t MessageType) IsRich() bool {
|
||||
switch t {
|
||||
case MsgText:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
+8
-406
@@ -1,386 +1,23 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
import "github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
// toolSummaryMaxRunes bounds a rendered tool summary. Tool output is
|
||||
// unbounded -- a grep can return thousands of lines -- and the summary is
|
||||
// one line in a chat transcript, so it is cut rather than allowed to bury the
|
||||
// answer it precedes.
|
||||
const (
|
||||
toolSummaryMaxRunes = 80
|
||||
toolParametersMaxRunes = 120
|
||||
redactedParameterValue = "[redacted]"
|
||||
)
|
||||
|
||||
// RenderToolCall returns the channel-neutral compact representation used by
|
||||
// chat surfaces. Parameters are intentionally omitted: JSON/schema-shaped
|
||||
// inputs are noisy, often contain secrets, and are not useful progress text.
|
||||
// Results are reduced semantically instead of clipped blindly: file contents,
|
||||
// listings and structured envelopes are described, never echoed.
|
||||
// RenderToolCall returns the channel-neutral compact representation used by
|
||||
// chat surfaces. (A function rather than a method because ToolCallEvent is a
|
||||
// messaging alias: see chat_contract_aliases.go.)
|
||||
// RenderToolCall returns the channel-neutral compact representation used by chat surfaces.
|
||||
func RenderToolCall(e ToolCallEvent) string {
|
||||
if limit, ok := legacyTurnBudgetLimit(e.Err); ok {
|
||||
return toolProgressBlock("tools", "stopped", fmt.Sprintf("tool-output limit reached (%s chars); further results suppressed", limit))
|
||||
}
|
||||
if line := cleanToolError(e.Name, e.Err); line != "" {
|
||||
return toolProgressBlock(e.Name, "failed", line)
|
||||
}
|
||||
return toolProgressBlock(e.Name, "done", toolPreview(e.Name, e.Output))
|
||||
return messaging.RenderToolCall(e)
|
||||
}
|
||||
|
||||
// FailureKey identifies equivalent tool calls for channel adapters that
|
||||
// collapse repeated activity. Legacy aggregate-output-limit errors deliberately
|
||||
// share one key across tool names: they are one obsolete turn-level condition,
|
||||
// not five independently useful failures. (A function rather than a method
|
||||
// because ToolCallEvent is a messaging alias: see chat_contract_aliases.go.)
|
||||
// FailureKey identifies equivalent tool calls for channel adapters that collapse repeated activity.
|
||||
func FailureKey(e ToolCallEvent) string {
|
||||
if _, ok := legacyTurnBudgetLimit(e.Err); ok {
|
||||
return "legacy-turn-output-limit"
|
||||
}
|
||||
if line := cleanToolError(e.Name, e.Err); line != "" {
|
||||
return strings.TrimSpace(e.Name) + "\x00" + line
|
||||
}
|
||||
// Successful calls are also eligible for aggregation. Use the same
|
||||
// compact summary that is shown to the user so equivalent results share a
|
||||
// key while different result summaries remain distinct.
|
||||
return "success\x00" + strings.TrimSpace(e.Name) + "\x00" + toolPreview(e.Name, e.Output)
|
||||
return messaging.FailureKey(e)
|
||||
}
|
||||
|
||||
func toolProgressBlock(name, status, preview string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
name = "tool"
|
||||
}
|
||||
preview = strings.ReplaceAll(strings.TrimSpace(preview), "```", "''' ")
|
||||
if preview == "" {
|
||||
preview = "completed"
|
||||
}
|
||||
return "🔧 " + name + " — " + status + "\n```text\n" + truncateRunes(preview, 180) + "\n```"
|
||||
}
|
||||
|
||||
// toolPreview reduces a tool result to one informative line.
|
||||
//
|
||||
// The result is described, never quoted: a search returns match lines that say
|
||||
// nothing on their own (a path, a line number, a closing brace), so the preview
|
||||
// states what came back and how much of it. The count comes from the tool's own
|
||||
// truncation notice when it printed one, because a count recomputed from the
|
||||
// visible sample describes the sample, not the result set -- rendering both
|
||||
// produced two different numbers for one search ("194 more lines" next to
|
||||
// "… 3 more lines"), which reads as noise.
|
||||
func toolPreview(name, output string) string {
|
||||
content, _ := unwrapToolContent(output)
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return "completed"
|
||||
}
|
||||
// A notice the tool printed is the only trustworthy source for how much
|
||||
// came back; anything counted here describes the visible sample.
|
||||
if summary, ok := toolNoticeSummary(content); ok {
|
||||
return summary
|
||||
}
|
||||
// Only a search gets a counted summary. A compiler or linter diagnostic has
|
||||
// the same "file.go:42: message" shape as a search hit, so counting every
|
||||
// tool's output would report a build error as "3 matches" and hide the very
|
||||
// output the operator asked for.
|
||||
if isSearchTool(name) {
|
||||
if summary, ok := searchResultSummary(content); ok {
|
||||
return summary
|
||||
}
|
||||
}
|
||||
preview := firstInformativeLine(content)
|
||||
if preview == "" {
|
||||
return "completed with no printable preview"
|
||||
}
|
||||
return preview
|
||||
}
|
||||
|
||||
// searchToolNames are the tools whose output is a set of matches, and so reads
|
||||
// better counted than sampled. Every other tool is described by its first
|
||||
// informative line.
|
||||
var searchToolNames = map[string]bool{
|
||||
"grep": true,
|
||||
"rg": true,
|
||||
"search": true,
|
||||
"toolsearch": true,
|
||||
}
|
||||
|
||||
func isSearchTool(name string) bool {
|
||||
return searchToolNames[strings.ToLower(strings.TrimSpace(name))]
|
||||
}
|
||||
|
||||
// toolNoticeSummary renders the "how much came back" summary from the
|
||||
// truncation notice the tool printed, if any.
|
||||
//
|
||||
// Two notice shapes exist (internal/tools/builtin): shell prints "[truncated:
|
||||
// showing last N/M lines, …]" and the other tools print "[truncated: showing
|
||||
// N/M lines, …]". Both are metadata, never content, so both must be recognised
|
||||
// -- missing the "last" form would quote the raw notice as the preview, which
|
||||
// is the exact defect this change removes.
|
||||
//
|
||||
// The same notice also tells us WHICH END was kept, which changes the summary:
|
||||
// a head-truncation ("showing 3/197") lost the tail, so "showing 3" describes
|
||||
// the sample; a tail-truncation ("showing last 66/97") lost the head, so the
|
||||
// count of what is visible says nothing useful about the whole.
|
||||
func toolNoticeSummary(content string) (string, bool) {
|
||||
for line := range strings.SplitSeq(content, "\n") {
|
||||
notice, ok := parseTruncationNotice(strings.TrimSpace(line))
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if notice.total <= notice.shown {
|
||||
continue // showing everything is not a truncation
|
||||
}
|
||||
if notice.truncatedHead {
|
||||
return fmt.Sprintf("%d lines total; showing last %d", notice.total, notice.shown), true
|
||||
}
|
||||
return fmt.Sprintf("%d lines total; showing %d", notice.total, notice.shown), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// truncationNotice describes how much a tool reported and which end it kept.
|
||||
type truncationNotice struct {
|
||||
shown int
|
||||
total int
|
||||
truncatedHead bool // the kept lines are the tail ("showing last N/M")
|
||||
}
|
||||
|
||||
// parseTruncationNotice reads "<shown>/<total> lines" out of a truncation
|
||||
// notice, accepting both the plain and the "showing last" form.
|
||||
//
|
||||
// The "[truncated: … ]" wrapper is required, not tolerated. It is the only
|
||||
// marker that distinguishes a notice the tool printed from ordinary output that
|
||||
// happens to contain the same phrasing: both built-in producers emit the
|
||||
// wrapper (internal/tools/builtin/truncate.go), so a bare "showing 3/197 lines"
|
||||
// inside a log or a document is content and must be left alone rather than
|
||||
// replaced by a summary.
|
||||
func parseTruncationNotice(line string) (truncationNotice, bool) {
|
||||
_, rest, found := strings.Cut(line, "[truncated: ")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
_, rest, found = strings.Cut(rest, "showing ")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
truncatedHead := false
|
||||
if after, ok := strings.CutPrefix(rest, "last "); ok {
|
||||
rest, truncatedHead = after, true
|
||||
}
|
||||
counts, _, found := strings.Cut(rest, " lines")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
left, right, found := strings.Cut(counts, "/")
|
||||
if !found {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
shown, errShown := strconv.Atoi(strings.TrimSpace(left))
|
||||
total, errTotal := strconv.Atoi(strings.TrimSpace(right))
|
||||
if errShown != nil || errTotal != nil {
|
||||
return truncationNotice{}, false
|
||||
}
|
||||
return truncationNotice{shown: shown, total: total, truncatedHead: truncatedHead}, true
|
||||
}
|
||||
|
||||
// searchResultSummary counts the match lines in ripgrep-shaped output. Only
|
||||
// matches are counted: with context requested, ripgrep also emits context lines
|
||||
// ("path-12-text", hyphen separator) and "--" group separators, and counting
|
||||
// those would report the match count plus every context line around it.
|
||||
func searchResultSummary(content string) (string, bool) {
|
||||
matches := countSearchMatches(content)
|
||||
if matches == 0 {
|
||||
return "", false
|
||||
}
|
||||
return fmt.Sprintf("%d %s", matches, pluralize(matches, "match", "matches")), true
|
||||
}
|
||||
|
||||
// countSearchMatches counts lines using ripgrep's match separator (":").
|
||||
func countSearchMatches(content string) int {
|
||||
matches := 0
|
||||
for line := range strings.SplitSeq(content, "\n") {
|
||||
if isSearchMatchLine(strings.TrimSpace(line)) {
|
||||
matches++
|
||||
}
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
// isSearchMatchLine reports whether line has ripgrep's "path:N:text" match
|
||||
// shape -- a colon separator. The hyphen form ("path-N-text") is a CONTEXT
|
||||
// line, not a match, and "--" is a group separator between context blocks;
|
||||
// neither is a match and neither is counted.
|
||||
//
|
||||
// The path may itself contain colons, so the separator is located by scanning
|
||||
// from the end for a colon followed by digits and another colon.
|
||||
func isSearchMatchLine(line string) bool {
|
||||
if line == "" || strings.HasPrefix(line, "[") {
|
||||
return false
|
||||
}
|
||||
if strings.Trim(line, "-") == "" {
|
||||
return false // "--" group separator
|
||||
}
|
||||
for i := len(line) - 1; i > 0; i-- {
|
||||
if line[i] != ':' {
|
||||
continue
|
||||
}
|
||||
digits := line[i+1:]
|
||||
end := 0
|
||||
for end < len(digits) && digits[end] >= '0' && digits[end] <= '9' {
|
||||
end++
|
||||
}
|
||||
// Require <path>:<digits>:<text> -- the trailing colon distinguishes a
|
||||
// match from a "path:42" reference with nothing after it.
|
||||
if end > 0 && end < len(digits) && digits[end] == ':' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// firstInformativeLine returns the first line worth showing: not blank, not a
|
||||
// module-cache path, and not a truncation notice (which is metadata the notice
|
||||
// path already consumed).
|
||||
func firstInformativeLine(content string) string {
|
||||
for line := range strings.SplitSeq(content, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(line, "/pkg/mod/") {
|
||||
continue
|
||||
}
|
||||
if _, ok := parseTruncationNotice(line); ok {
|
||||
continue
|
||||
}
|
||||
return truncateRunes(line, 120)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func pluralize(n int, one, many string) string {
|
||||
if n == 1 {
|
||||
return one
|
||||
}
|
||||
return many
|
||||
}
|
||||
|
||||
func unwrapToolContent(output string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(output)
|
||||
if trimmed == "" {
|
||||
return "", false
|
||||
}
|
||||
var envelope struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if json.Unmarshal([]byte(trimmed), &envelope) == nil && envelope.Content != "" {
|
||||
return envelope.Content, true
|
||||
}
|
||||
var quoted string
|
||||
if json.Unmarshal([]byte(trimmed), "ed) == nil {
|
||||
return quoted, true
|
||||
}
|
||||
return output, false
|
||||
}
|
||||
|
||||
func cleanToolError(name, raw string) string {
|
||||
line := firstNonEmptyLine(raw)
|
||||
prefix := "tool " + strings.TrimSpace(name) + ": "
|
||||
line = strings.TrimPrefix(line, prefix)
|
||||
return truncateRunes(strings.TrimSpace(line), toolSummaryMaxRunes)
|
||||
}
|
||||
|
||||
func legacyTurnBudgetLimit(raw string) (string, bool) {
|
||||
const marker = "turn budget exceeded ("
|
||||
_, after, ok := strings.Cut(raw, marker)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
rest := after
|
||||
end := strings.Index(rest, " chars)")
|
||||
if end < 1 {
|
||||
return "", false
|
||||
}
|
||||
return rest[:end], true
|
||||
}
|
||||
|
||||
// SummarizeToolParameters returns a bounded JSON shape of tool input. Every
|
||||
// string value is replaced rather than echoed because credentials can appear
|
||||
// inside ordinary parameters such as command, content, or body. Values under
|
||||
// secret-bearing keys use an explicit redaction marker; other strings retain
|
||||
// only their type. Invalid JSON is never echoed.
|
||||
// SummarizeToolParameters returns a bounded JSON shape of tool input.
|
||||
func SummarizeToolParameters(input string) string {
|
||||
if strings.TrimSpace(input) == "" {
|
||||
return ""
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(input))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return "[unavailable]"
|
||||
}
|
||||
value = redactToolParameters(value, false)
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "[unavailable]"
|
||||
}
|
||||
return truncateRunesWithinLimit(string(encoded), toolParametersMaxRunes)
|
||||
return messaging.SummarizeToolParameters(input)
|
||||
}
|
||||
|
||||
func redactToolParameters(value any, sensitive bool) any {
|
||||
if sensitive {
|
||||
return redactedParameterValue
|
||||
}
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range typed {
|
||||
typed[key] = redactToolParameters(child, sensitiveParameterKey(key))
|
||||
}
|
||||
return typed
|
||||
case []any:
|
||||
for i, child := range typed {
|
||||
typed[i] = redactToolParameters(child, sensitive)
|
||||
}
|
||||
return typed
|
||||
case string:
|
||||
return "[string]"
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
func sensitiveParameterKey(key string) bool {
|
||||
normalized := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(key))
|
||||
for _, marker := range webhookguard.SensitiveKeyMarkers {
|
||||
if strings.Contains(normalized, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func truncateRunesWithinLimit(s string, limit int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= limit {
|
||||
return s
|
||||
}
|
||||
if limit <= 1 {
|
||||
return "…"
|
||||
}
|
||||
return string(runes[:limit-1]) + "…"
|
||||
}
|
||||
|
||||
// DeltaFunc adapts a plain text-delta callback to TurnStream for callers that
|
||||
// render text only. Tool events are discarded. A nil DeltaFunc is inert, so
|
||||
// DeltaFunc(nil) is a usable "stream nothing" sink.
|
||||
// DeltaFunc adapts a plain text-delta callback to TurnStream.
|
||||
type DeltaFunc func(string)
|
||||
|
||||
// Delta forwards the fragment to the wrapped callback.
|
||||
@@ -397,26 +34,17 @@ func (f DeltaFunc) ToolCall(ToolCallEvent) {}
|
||||
// Media discards the event: a text-only caller has nowhere to put it.
|
||||
func (f DeltaFunc) Media(MediaEvent) {}
|
||||
|
||||
// toolCallRecorder wraps a TurnStream, forwarding every event to it
|
||||
// unchanged while also recording the tool calls in arrival order. The
|
||||
// recording happens regardless of whether next is nil (a non-streaming
|
||||
// caller, e.g. Router.LLM) so a turn's tool activity is captured for
|
||||
// persistence and later replay even when nothing rendered it live the first
|
||||
// time.
|
||||
type toolCallRecorder struct {
|
||||
next TurnStream
|
||||
events []ToolCallEvent
|
||||
}
|
||||
|
||||
// Delta forwards the fragment to the wrapped stream, if any.
|
||||
func (r *toolCallRecorder) Delta(text string) {
|
||||
if r.next != nil {
|
||||
r.next.Delta(text)
|
||||
}
|
||||
}
|
||||
|
||||
// ToolCall records the event, then forwards it to the wrapped stream, if
|
||||
// any.
|
||||
func (r *toolCallRecorder) ToolCall(event ToolCallEvent) {
|
||||
r.events = append(r.events, event)
|
||||
if r.next != nil {
|
||||
@@ -424,34 +52,8 @@ func (r *toolCallRecorder) ToolCall(event ToolCallEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
// Media forwards the event to the wrapped stream, if any. Unlike ToolCall,
|
||||
// it is not recorded: media persistence and replay are not yet a supported
|
||||
// path (see archie-core-1786748942243-6-f109697e), so recording it here
|
||||
// would create a ledger field nothing reads.
|
||||
func (r *toolCallRecorder) Media(event MediaEvent) {
|
||||
if r.next != nil {
|
||||
r.next.Media(event)
|
||||
}
|
||||
}
|
||||
|
||||
// firstNonEmptyLine returns the first line of s that holds something other
|
||||
// than whitespace, trimmed. It returns "" when there is no such line.
|
||||
func firstNonEmptyLine(s string) string {
|
||||
for line := range strings.SplitSeq(s, "\n") {
|
||||
if trimmed := strings.TrimSpace(line); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// truncateRunes shortens s to at most maxRunes runes, marking the cut with an
|
||||
// ellipsis. Counting runes rather than bytes keeps multi-byte text from being
|
||||
// cut mid-character.
|
||||
func truncateRunes(s string, maxRunes int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= maxRunes {
|
||||
return s
|
||||
}
|
||||
return string(runes[:maxRunes]) + "…"
|
||||
}
|
||||
@@ -1,130 +1,9 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
func TestRedactionConsumersShareMarkerSet(t *testing.T) {
|
||||
if len(webhookguard.SensitiveKeyMarkers) == 0 {
|
||||
t.Fatal("webhookguard.SensitiveKeyMarkers is empty, want a non-empty shared set")
|
||||
}
|
||||
for _, marker := range webhookguard.SensitiveKeyMarkers {
|
||||
if !sensitiveParameterKey(marker) {
|
||||
t.Errorf("sensitiveParameterKey(%q) = false, want true (shared marker set)", marker)
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{marker: "secret"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := webhookguard.RedactPayload(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("RedactPayload(%q): %v", marker, err)
|
||||
}
|
||||
if string(got) == string(payload) {
|
||||
t.Errorf("webhookguard did not redact shared marker key %q", marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeToolParameters(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{name: "empty", input: "", want: ""},
|
||||
{name: "compact object", input: `{ "path": "/tmp/file", "line": 2 }`, want: `{"line":2,"path":"[string]"}`},
|
||||
{name: "nested secrets", input: `{"headers":{"Authorization":"Bearer secret"},"api-token":"secret","safe":"visible"}`, want: `{"api-token":"[redacted]","headers":{"Authorization":"[redacted]"},"safe":"[string]"}`},
|
||||
{name: "secret embedded in ordinary value", input: `{"command":"curl -H 'Authorization: Bearer secret'"}`, want: `{"command":"[string]"}`},
|
||||
{name: "secret in array", input: `[{"password":"secret"}]`, want: `[{"password":"[redacted]"}]`},
|
||||
{name: "non-string secret", input: `{"password":123456,"token":true}`, want: `{"password":"[redacted]","token":"[redacted]"}`},
|
||||
{name: "nested value under sensitive key", input: `{"credentials":{"user":"archie","password":"secret"}}`, want: `{"credentials":"[redacted]"}`},
|
||||
{name: "invalid JSON", input: `token=secret`, want: "[unavailable]"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := SummarizeToolParameters(tc.input); got != tc.want {
|
||||
t.Fatalf("SummarizeToolParameters() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
got := SummarizeToolParameters(`{"value":[` + strings.Repeat("0,", toolParametersMaxRunes) + `0]}`)
|
||||
if len([]rune(got)) != toolParametersMaxRunes {
|
||||
t.Fatalf("bounded summary is %d runes, want %d", len([]rune(got)), toolParametersMaxRunes)
|
||||
}
|
||||
if !strings.HasSuffix(got, "…") {
|
||||
t.Fatalf("bounded summary = %q, want ellipsis", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolCallEventSummary(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
event ToolCallEvent
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "single line output is the summary",
|
||||
event: ToolCallEvent{Name: "memory_edit", Output: "added entry"},
|
||||
want: "added entry",
|
||||
},
|
||||
{
|
||||
name: "only the first non-empty line is kept",
|
||||
event: ToolCallEvent{Name: "read", Output: "\n\nfirst line\nsecond line"},
|
||||
want: "first line",
|
||||
},
|
||||
{
|
||||
name: "surrounding whitespace is trimmed",
|
||||
event: ToolCallEvent{Name: "shell", Output: " exit 0 \n"},
|
||||
want: "exit 0",
|
||||
},
|
||||
{
|
||||
name: "an error replaces the output",
|
||||
event: ToolCallEvent{Name: "shell", Output: "partial", Err: "exit status 2"},
|
||||
want: "failed: exit status 2",
|
||||
},
|
||||
{
|
||||
name: "a multi-line error is reduced the same way",
|
||||
event: ToolCallEvent{Name: "shell", Err: "exit status 2\nstack trace"},
|
||||
want: "failed: exit status 2",
|
||||
},
|
||||
{
|
||||
name: "no output at all still reads as a completed call",
|
||||
event: ToolCallEvent{Name: "write"},
|
||||
want: "done",
|
||||
},
|
||||
{
|
||||
name: "whitespace-only output reads as a completed call",
|
||||
event: ToolCallEvent{Name: "write", Output: " \n "},
|
||||
want: "done",
|
||||
},
|
||||
{
|
||||
name: "a long line is truncated with an ellipsis",
|
||||
event: ToolCallEvent{Name: "grep", Output: strings.Repeat("x", toolSummaryMaxRunes+10)},
|
||||
want: strings.Repeat("x", toolSummaryMaxRunes) + "…",
|
||||
},
|
||||
{
|
||||
name: "truncation counts runes, not bytes",
|
||||
event: ToolCallEvent{Name: "grep", Output: strings.Repeat("é", toolSummaryMaxRunes+10)},
|
||||
want: strings.Repeat("é", toolSummaryMaxRunes) + "…",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := tc.event.Summary(); got != tc.want {
|
||||
t.Fatalf("Summary() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A caller that only renders text must be able to keep passing a plain
|
||||
// callback, and must never be handed a tool event it cannot use.
|
||||
func TestDeltaFuncIsTextOnly(t *testing.T) {
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user