feat: add optional NATS JetStream task distribution
Adds optional NATS-based task distribution alongside the existing
SQLite flow. When [nats] is absent from config, zero behaviour change.
New internal/nats package:
- Subject constants matching PRD §2 (archie.task.{bug,feature,default,bootstrap})
- Client: Connect (stream + durable pull consumer), PublishTask
(Nats-Msg-Id dedup), Fetch, DecodeTask
- Tests with embedded NATS server (connect/publish, dedup, subject routing)
Config: NATSConfig{URL, TokenEnv} on Config, commented-out [nats] block
in config.example.toml
Store: ClaimByIssue atomic claim by owner/repo/number for NATS consumer
Daemon: Nats client field, poll() branches to pollNATS/pollSQLite,
Cycle() branches to drainNATS/drainSQLite (NATS fetch then SQLite
ClaimNext fallback for requeued tasks), processNATSTask
(decode → EnqueueIssue → ClaimByIssue → process → Ack)
Scratch: explorer and plan agent outputs from parallel-explore phase
This commit is contained in:
1 parent
ac44d56965
commit
bb2193e5e4
14 files changed
+1999
-26
No files matched your search
@@ -0,0 +1,219 @@
|
||||
# agentexec-protocol
|
||||
|
||||
我现在掌握了所有需要的信息。以下是完整的报告。
|
||||
|
||||
---
|
||||
|
||||
## 报告:Archie 核心中的代理执行协议和 Runner 架构
|
||||
|
||||
### 1. Runner 接口
|
||||
|
||||
定义位置:`/work/apps/archie-core/internal/agentexec/inprocess.go`,第 20-22 行
|
||||
|
||||
```go
|
||||
type Runner interface {
|
||||
Run(ctx context.Context, workspace string, req Request) (Result, error)
|
||||
}
|
||||
```
|
||||
|
||||
**一个单一方法接口:** `Run` 接受一个上下文、一个工作目录路径(字符串)和一个 `Request`,返回一个 `Result` 和一个错误。工作目录路径与请求分开传递,供容器运行器将主机路径映射到内部文件系统。
|
||||
|
||||
该接口有两个具体实现:
|
||||
|
||||
- **`InProcessRunner`** (`/work/apps/archie-core/internal/agentexec/inprocess.go`,第 29-33 行) -- 拥有一个 `*runtime.Runtime`、一个 `*slog.Logger` 和一个 `loopFunc` 字段(默认为 `agentloop.Run`)。它在与 `archied` 相同的进程空间中运行代理循环。
|
||||
|
||||
- **`SubprocessRunner`** (`/work/apps/archie-core/internal/agentexec/subprocess.go`,第 17-27 行) -- 拥有 `Command`、`Args`、`Environ`、`AdditionalEnv`、`Diagnostics io.Writer` 和 `Providers`。它将完整的 `Invocation` 序列化到 stdin,启动一个 `archie-agent` 二进制文件,并从 stdout 解码 `Response`。
|
||||
|
||||
### 2. 线路协议
|
||||
|
||||
所有消息类型都定义在 `/work/apps/archie-core/internal/agentexec/protocol.go` 中。
|
||||
|
||||
**Invocation** (第 139-144 行) -- 被 `archie-agent` 接受的完整请求:
|
||||
```go
|
||||
type Invocation struct {
|
||||
Version int `json:"version"`
|
||||
Workspace string `json:"workspace"`
|
||||
Request Request `json:"request"`
|
||||
Providers map[string]Provider `json:"providers"`
|
||||
}
|
||||
```
|
||||
|
||||
**Request** (第 59-74 行) -- 代理阶段的有效载荷:
|
||||
```go
|
||||
type Request struct {
|
||||
Version int `json:"version"`
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Stage string `json:"stage"`
|
||||
Model string `json:"model"`
|
||||
Mission string `json:"mission"`
|
||||
ExtraRules string `json:"extra_rules,omitempty"`
|
||||
ReadOnly bool `json:"read_only,omitempty"`
|
||||
Budget Budget `json:"budget"`
|
||||
Gate Gate `json:"gate"`
|
||||
Preflight []Command `json:"preflight,omitempty"`
|
||||
Protection Protection `json:"protection"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
CaptureTools []CaptureTool `json:"capture_tools,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
**Result** (第 97-111 行) -- 输出:
|
||||
```go
|
||||
type Result struct {
|
||||
Version int `json:"version"`
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Stage string `json:"stage"`
|
||||
Status string `json:"status"`
|
||||
StopReason string `json:"stop_reason,omitempty"`
|
||||
Changes []string `json:"changes,omitempty"`
|
||||
Iterations int `json:"iterations,omitempty"`
|
||||
TokensUsed int `json:"tokens_used,omitempty"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
AppendedNotes []string `json:"appended_notes,omitempty"`
|
||||
Captures map[string][]json.RawMessage `json:"captures,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
**Response** (第 168-172 行) -- 从 `archie-agent` 返回的顶层信封:
|
||||
```go
|
||||
type Response struct {
|
||||
Version int `json:"version"`
|
||||
Result Result `json:"result"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
**辅助类型:**
|
||||
- `Command` (第 18-22 行):`Name`、`Argv`、`ExpectFailure`
|
||||
- `Gate` (第 25-28 行):`Commands`、`MaxConsecutiveFailures`
|
||||
- `Budget` (第 31-35 行):`MaxSteps`、`MaxTokens`、`WallClock`
|
||||
- `Protection` (第 38-41 行):`Suffixes`、`Globs`
|
||||
- `CaptureTool` (第 45-53 行):`Name`、`Description`、`Parameters`、`RequiredFields`、`NonEmptyStrings`、`BooleanFields`、`MaxCalls`
|
||||
- `Provider` (第 115-119 行):`Class`、`APIKeyEnv`、`BaseURL`
|
||||
|
||||
协议通过 JSON 在 stdin/stdout 上使用。`ServeOne` (`worker.go`,第 16-43 行) 解码一个 `Invocation`,验证它,构建一个 `InProcessRunner`,运行它,然后将单个 `Response` 写入 stdout。`ServeOne` 不会循环——它处理一个调用然后返回。
|
||||
|
||||
### 3. cmd/archied 如何连接 Runner
|
||||
|
||||
在 `/work/apps/archie-core/cmd/archied/main.go` 中,第 109-125 行:
|
||||
|
||||
```go
|
||||
providers := executionProviders(cfg)
|
||||
llm := agentexec.NewRuntime(providers)
|
||||
var agentRunner agentexec.Runner
|
||||
if llm != nil {
|
||||
switch cfg.Agent.Mode {
|
||||
case "subprocess":
|
||||
agentRunner = &agentexec.SubprocessRunner{
|
||||
Command: cfg.Agent.Command,
|
||||
Environ: os.Environ(),
|
||||
AdditionalEnv: cfg.Agent.Env,
|
||||
Diagnostics: os.Stderr,
|
||||
Providers: providers,
|
||||
}
|
||||
case "inprocess":
|
||||
agentRunner = agentexec.NewInProcessRunner(llm, log)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
运行器模式由 `cfg.Agent.Mode` 控制,它来自配置 TOML。有两个 case:
|
||||
|
||||
- **`"subprocess"`**:创建一个 `SubprocessRunner`,将完整的环境、一个可执行文件命令(来自 `cfg.Agent.Command`,通常是 `archie-agent` 二进制文件的路径)以及提供者映射传递给它。
|
||||
- **`"inprocess"`**:通过 `NewInProcessRunner(llm, log)` 创建一个 `InProcessRunner`,其中 `llm` 是 `runtime.NewRuntime(providers)` 的结果。
|
||||
|
||||
然后,`agentRunner` 被放入 `Daemon` 结构体 (`/work/apps/archie-core/internal/daemon/daemon.go`,第 33 行) 作为 `Agent agentexec.Runner`。守护进程的 `process` 方法 (第 356-377 行) 将其传递到 `TaskContext`:
|
||||
|
||||
```go
|
||||
workflow.Run(ctx, wf, &workflow.TaskContext{
|
||||
Task: task,
|
||||
Repo: repo,
|
||||
...
|
||||
Agent: d.Agent,
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
如果 `cfg.Agent.Mode` 既不是 `"subprocess"` 也不是 `"inprocess"`,或者如果 `llm` 是 nil(没有提供者),则 `agentRunner` 保持为 nil。当 `Agent` 为 nil 时,`AgentStage.Stage()` 方法 (`agent.go`,第 49-50 行) 返回一个合适的错误。
|
||||
|
||||
### 4. TaskContext 和 Agent 字段
|
||||
|
||||
定义位置:`/work/apps/archie-core/internal/workflow/workflow.go`,第 26-57 行。
|
||||
|
||||
```go
|
||||
type TaskContext struct {
|
||||
Task *store.Task
|
||||
Repo config.Repo
|
||||
Cfg config.Config
|
||||
Forge forge.Forge
|
||||
Store *store.Store
|
||||
Trees *worktree.Manager
|
||||
Agent agentexec.Runner // <-- 第 33 行
|
||||
Bus *events.Bus
|
||||
Log *slog.Logger
|
||||
CustomStages func(dir string) ([]Stage, error)
|
||||
Dir string
|
||||
Branch string
|
||||
BuildSummary string
|
||||
ReproProof string
|
||||
decision *decision
|
||||
Outcome Outcome
|
||||
}
|
||||
```
|
||||
|
||||
`Agent` 字段是 `agentexec.Runner`。工作流通过 `AgentStage.Stage()` (`agent.go`,第 47-148 行) 调用它。核心调用顺序是:
|
||||
|
||||
1. `AgentStage.Stage()` 从上下文字段 (`agent.go`,第 94-109 行) 构建一个 `agentexec.Request`。
|
||||
2. 调用 `tc.Agent.Run(ctx, tc.Dir, req)` (第 110 行)。
|
||||
3. 然后处理结果:验证 (`ValidateFor`,第 114 行)、追加笔记 (第 117-124 行)、累积代币/迭代次数 (第 129-130 行)、检查非 `"passed"` 状态 (第 136-141 行),以及分派给 `OnResult` 回调 (第 143-145 行)。
|
||||
|
||||
只有 `InProcessRunner` 使用 `runtime.Runtime` 直接调用 `agentloop.Run`。`SubprocessRunner` 构建一个 `Invocation`,通过提供者名称映射将完整的请求序列化,并通过 `exec.CommandContext` 启动一个子进程。
|
||||
|
||||
### 5. 使 `archie-agent` 成为长期运行的消息总线进程所需的变化
|
||||
|
||||
以下是关键的变化领域:
|
||||
|
||||
**A. 入口点 (`cmd/archie-agent/main.go`)**
|
||||
|
||||
- 目前它调用 `agentexec.ServeOne`,后者解码一个 JSON 调用,执行,并将一个 JSON 响应写入 stdout。这严格是一次性的。
|
||||
- 要变为长期运行,`main()` 需要初始化一个消息总线客户端(例如,NATS、RabbitMQ、AMQP 甚至是简单的 gRPC 流),订阅一个主题/队列,并在每个传入的 `Invocation` 上循环调用 `ServeOne`(或者更确切地说,其核心逻辑)。
|
||||
- 信号处理需要优雅地等待进行中的工作完成,而不是在 `SIGTERM` 时直接退出。
|
||||
|
||||
**B. worker.go 中的 `ServeOne` 函数**
|
||||
|
||||
- 目前它在全局范围内构建一个 `InProcessRunner`(将 `NewRuntime(invocation.Providers)` 传递给 `NewInProcessRunner`)。
|
||||
- 如果进程是长期运行的,则 `runtime.Runtime` 应该在启动时构造一次(可能来自配置或环境变量),而不是每个调用都动态构建。提供者配置会在进程的生命周期内保持不变,因此没有理由每次从 JSON 重新创建运行时。
|
||||
- `protocol.go` 中的 `Invocation` 类型包含 `Providers`——如果一个长期运行的 worker 已经在启动时知道其提供者,这可能就不需要了。工作区路径也有问题:对于长期运行的进程,工作区可能由消息路由到(或使用单独的 RPC 调用来准备),而不是嵌入在调用请求中。
|
||||
|
||||
**C. 线路协议适配**
|
||||
|
||||
- 当前协议是 request/reply(1 个 JSON 值用于输入,1 个用于输出)。对于总线,`Response` 会被发布到单独的回复主题/队列,而不是写入 stdout。
|
||||
- 运行器接口本身 (`Runner.Run(ctx, workspace, req)`) 是同步的,这很适合总线——每个消息都可以通过 `Run` 处理,结果被发布出去。
|
||||
- 调用/响应帧中的 `Version`、`TaskID`、`Attempt`、`Stage` 字段提供了足够的路由/关联上下文——`Response` 中的 `TaskID` 和 `Stage` 使得在回复主题上正确路由变得简单。
|
||||
|
||||
**D. 环境架构**
|
||||
|
||||
- 目前,`SubprocessRunner` 通过继承的环境变量传递 API 密钥,并使用 `WorkerEnvironment` 进行过滤(`subprocess.go`,第 155-162 行)。一个长期运行的进程已经在进行中,但需要能够更新/重新加载提供者凭证而不重新启动(例如,密钥轮换)。这可能需要一个控制通道或一个动态重新加载配置的方法。
|
||||
|
||||
**E. 配置和工作目录**
|
||||
|
||||
- 目前,`Invocation` 承载 `Workspace`,并且每个路径都是请求的一部分。一个基于总线的 worker 可能希望要么:
|
||||
- 在工作区已经准备就绪时接收带外消息(例如,一个单独的“准备”RPC),或者
|
||||
- 除了运行代理之外,还执行一些较小的设置步骤(克隆 repo)。
|
||||
- 守护进程当前通过 `worktree.Manager` (`steps.go`,第 22-30 行) 处理工作目录准备。如果 `archie-agent` 处理其自己的工作目录设置,这会创建一个职责划分问题。
|
||||
|
||||
**F. `SubprocessRunner` 对 `agentexec` 包的依赖**
|
||||
|
||||
- `SubprocessRunner` 是 `archied` 端的替代品——它从 `archied` 启动 `archie-agent`。如果 `archie-agent` 是一个长期运行的进程,`archied` 不会直接启动它;连接成为出站消息总线连接。`SubprocessRunner` 可能会变得过时或需要重构为一个“远程”运行器,该运行器通过总线发送消息而不是生成子进程。
|
||||
|
||||
**G. 错误处理和死信队列**
|
||||
|
||||
- 目前,`cmd.Run()` 中的进程退出代码表示协议失败。对于长期运行的进程,反序列化故障或无效调用应发布到死信队列主题。
|
||||
|
||||
总而言之,`Runner` 接口 (`Run(ctx, workspace, req)`) 本身不需要改变。然而,它的调用方式会改变:
|
||||
- `cmd/archie-agent/main.go` 将从一次性 stdin/stdout 变为总线主题订阅循环。
|
||||
- `cmd/archied/main.go` 将使用一个基于总线的远程运行器,而不是 `SubprocessRunner`。
|
||||
- 提供者查找和运行时生命周期管理将从每次调用(`worker.go` 中的 `ServeOne`)移动到进程启动时。
|
||||
@@ -0,0 +1,350 @@
|
||||
# daemon-task-loop
|
||||
|
||||
Here is the full report.
|
||||
|
||||
---
|
||||
|
||||
## 1. Full Lifecycle: GitHub Issue to Completed Task
|
||||
|
||||
The lifecycle spans four subsystems: **forge** (GitHub polling), **store** (SQLite persistence), **daemon** (orchestration loop), and **workflow** (pipeline engine). Here is the exact call chain.
|
||||
|
||||
### Phase 1 -- Discovery (polling)
|
||||
|
||||
**Entry:** `Daemon.Run()` at `daemon.go:72`
|
||||
- Creates a `time.NewTicker` from `d.Cfg.PollInterval` (default 60s, line 259 of config.go).
|
||||
- Calls `d.Cycle(ctx)` on every tick.
|
||||
|
||||
**`Daemon.Cycle()`** at `daemon.go:88` does three discovery activities, then drains the queue:
|
||||
|
||||
1. **`d.poll(ctx)`** -- line 89. Iterates over `d.Cfg.Repos`, calling `d.pollIssues(ctx, repo)` (line 140).
|
||||
2. **`d.reconcilePRs(ctx)`** -- line 90. Finds tasks at `StatusPROpen` and checks GitHub for merged/closed status.
|
||||
3. **`d.checkWaiting(ctx)`** -- line 91. Finds tasks at `StatusWaitingHuman` and LLM-judges human replies.
|
||||
|
||||
**`Daemon.pollIssues()`** at `daemon.go:140` routes by `d.Cfg.Dispatch.Trigger`:
|
||||
- `"assignee"`: calls `d.Forge.AssignedIssues(ctx, owner, repo, botUser)`.
|
||||
- `"label"`: calls `d.Forge.IssuesWithLabel(ctx, owner, repo, label)`.
|
||||
- `"either"`: calls `pollEither()` (line 163), which unions both lists deduped by issue number.
|
||||
|
||||
### Phase 2 -- Enqueue
|
||||
|
||||
**`Daemon.poll()`** at `daemon.go:111-133`: for each discovered `forge.Issue`, calls:
|
||||
- `d.Store.EnqueueIssue(ctx, owner, repo, number, title, body, labels)` -- this is an `INSERT ... ON CONFLICT DO NOTHING` at `store.go:115-118`. Returns `true` if a new row was inserted (idempotency via the `UNIQUE(owner, repo, issue_number)` constraint at line 99).
|
||||
- On insert: posts an emoji reaction via `d.Forge.React()` (default "eyes", config line 319), sets the "queued" state label, and emits a `KindTaskQueued` event.
|
||||
- On duplicate (inserted==false): calls `d.maybeRetryParked()` (line 134) which checks whether a human removed the `archie:parked` label and if so calls `d.Store.Requeue()`.
|
||||
|
||||
### Phase 3 -- Claim (queue drain)
|
||||
|
||||
Back in `Daemon.Cycle()` at lines 92-106, an inner `for` loop:
|
||||
1. Calls `d.Store.ClaimNext(ctx)` (line 96).
|
||||
2. If nil, returns (queue empty).
|
||||
3. Otherwise calls `d.process(ctx, task)` (line 104), then loops again.
|
||||
|
||||
**`Store.ClaimNext()`** at `store.go:129-141`: one atomic SQL statement:
|
||||
```sql
|
||||
UPDATE tasks SET status='running', attempt=attempt+1, updated_at=datetime('now')
|
||||
WHERE id = (SELECT id FROM tasks WHERE status='queued' ORDER BY id LIMIT 1)
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status,
|
||||
workflow, stage, branch, plan, notes, pr_number, tokens_used,
|
||||
iterations, attempt, park_reason
|
||||
```
|
||||
Because SQLite locks the database file for the duration of the UPDATE, no two claimed tasks can overlap -- the daemon is effectively single-consumer. The `RETURNING` clause returns the full row.
|
||||
|
||||
### Phase 4 -- Process
|
||||
|
||||
**`Daemon.process()`** at `daemon.go:356`:
|
||||
1. Looks up the `config.Repo` for the task via `d.repoFor(task)` (line 358). Fails/tasks that belong to a now-unconfigured repo go to `StatusParked`.
|
||||
2. Routes to a workflow: `wf := workflow.Route(task, d.Workflows)` (line 362).
|
||||
3. Sets the "working" state label on the issue.
|
||||
4. Calls `workflow.Run(ctx, wf, taskContext)` (line 365).
|
||||
|
||||
### Phase 5 -- Workflow Execution
|
||||
|
||||
**`workflow.Route()`** at `workflow.go:103-141` decides the workflow:
|
||||
1. If `t.Workflow` is non-empty (set by a prior `Requeue`), use that exact workflow from the registry.
|
||||
2. Otherwise inspect labels: `"bug"` -> `"tdd"`, `"feature"` -> `"feasibility"`, `"bootstrap"` -> `"bootstrap"`.
|
||||
3. Falls back to `"implement"`, then `"default"`, then a hardcoded failing error workflow.
|
||||
|
||||
**`workflow.Run()`** at `workflow.go:145-185` executes stages sequentially:
|
||||
1. Sets `t.Workflow = wf.Name`, persists via `tc.Store.Update()`.
|
||||
2. For each stage: sets `t.Stage`, persists, emits `KindStageStart`, runs `stage.Run(ctx, tc)`, emits `KindStageFinish` with timing data.
|
||||
3. On stage error: if `ctx.Err()` is set (daemon shutting down), returns cleanly; otherwise calls `park()` at line 216, which transitions to `StatusParked`, posts a comment, and emits `KindParked`.
|
||||
4. If `tc.Outcome.Status` is non-empty after a stage, calls `finish()` at line 187, which transitions to that terminal status.
|
||||
|
||||
### Phase 6 -- Terminal States
|
||||
|
||||
A workflow terminates through `finish()` (`workflow.go:187`) or `park()` (`workflow.go:216`):
|
||||
|
||||
| Outcome | Status | What happens |
|
||||
|---|---|---|
|
||||
| `park()` | `parked` | Worktree kept, park-reason comment posted, label set. Human can remove `archie:parked` to trigger `maybeRetryParked()`. |
|
||||
| `finish()` with `StatusPROpen` | `pr_open` | PR is open on GitHub. Subsequent `Cycle()` passes call `reconcilePRs()` which checks merged/closed. |
|
||||
| `finish()` with `StatusWaitingHuman` | `waiting_human` | Daemon watches for human replies via `checkWaiting()`, LLM-judges approve/reject/unclear. |
|
||||
| `finish()` with `StatusMerged` | `merged` | Final -- PR merged, labels cleared. |
|
||||
| `finish()` with `StatusClosedWontDo` | `closed_wont_do` | Issue closed on GitHub. |
|
||||
| `finish()` with `StatusRejected` | `rejected` | PR closed without merge. |
|
||||
|
||||
### Crash Recovery
|
||||
|
||||
`Daemon.Startup()` at line 52 calls `d.Store.RecoverStale(ctx)` (`store.go:234`) which runs:
|
||||
```sql
|
||||
UPDATE tasks SET status='queued' WHERE status='running'
|
||||
```
|
||||
This re-queues any task that was `running` when the previous daemon crashed. There is no distributed locking -- the single SQLite file is the authority.
|
||||
|
||||
---
|
||||
|
||||
## 2. Event Struct and Bus
|
||||
|
||||
### `events.Event` at `events.go:31-42`
|
||||
|
||||
```go
|
||||
type Event struct {
|
||||
ID int64 `json:"id,omitempty"` // set by the store sink
|
||||
At time.Time `json:"at"`
|
||||
Kind string `json:"kind"`
|
||||
TaskID int64 `json:"task_id,omitempty"`
|
||||
Repo string `json:"repo,omitempty"`
|
||||
Issue int `json:"issue,omitempty"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Data map[string]any `json:"data,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
**Kind constants** at `events.go:16-26`:
|
||||
- `KindTaskQueued`, `KindStageStart`, `KindStageFinish` (data: `duration_ms`, `error`), `KindAgentFinish` (data: `status`, `stop_reason`, `tokens`, `iterations`, `model`), `KindParked` (data: `reason`), `KindOutcome` (data: `status`, `detail`), `KindPRMerged`, `KindPRRejected`, `KindLog` (data: `level`, `msg`).
|
||||
|
||||
Events are intentionally the single wire type -- every consumer is just another subscriber.
|
||||
|
||||
### `events.Bus` at `events.go:59-128`
|
||||
|
||||
A simple in-process fan-out bus:
|
||||
|
||||
- **`Subscribe(buffer int) *Sub`** (line 68): creates a buffered channel (default 64), appends to `b.subs`. Returns a `*Sub` whose `.C` field is the read-only receive channel.
|
||||
- **`Publish(e Event)`** (line 86): stamps `At` if zero, then iterates all subscribers and does a non-blocking send (`select` with `default`). If a subscriber's buffer is full, the event is dropped and `s.dropped.Add(1)` is incremented. **This is the critical design property: backpressure from a slow consumer never blocks the publisher.**
|
||||
- **`unsubscribe(sub *Sub)`** (line 104): removes the sub from the slice, closes its channel.
|
||||
- **`Close()`** (line 117): sets `closed` flag, closes all subscriber channels, nils the slice.
|
||||
- **Bounded per-subscriber buffers** with drop-on-overflow, as documented at line 6: "a stalled dashboard connection can never apply backpressure to the task engine."
|
||||
|
||||
### Publish Side
|
||||
|
||||
The daemon has a convenience method `emit()` at `daemon.go:44-49`:
|
||||
```go
|
||||
func (d *Daemon) emit(e events.Event) {
|
||||
if d.Bus != nil { d.Bus.Publish(e) }
|
||||
}
|
||||
```
|
||||
Called explicitly at every lifecycle transition -- see `daemon.go:128` (queued), `daemon.go:207` (retried), `daemon.go:237` (PR merged), `daemon.go:248` (PR rejected), `daemon.go:294` (human approved), `daemon.go:303` (human rejected).
|
||||
|
||||
The workflow engine also publishes via `TaskContext.Emit()` at `workflow.go:61-75`, which stamps the task identity and delegates to `tc.Bus.Publish()`.
|
||||
|
||||
### Subscribe Side (Consumers)
|
||||
|
||||
The bus is consumed by at least two subscriber patterns visible in the codebase:
|
||||
|
||||
1. **SQLite event log** (`internal/store/events.go`): some goroutine must subscribe and call `s.InsertEvent()` to persist each event. (The subscription setup is in the composition root `cmd/archied`. I did not read that file, but `InsertEvent` at `events.go:32` clearly exists for this purpose.)
|
||||
|
||||
2. **SSE fan-out** for the dashboard: the bus is designed so each HTTP SSE connection gets its own `Sub` with a small buffer, and the drop-on-overload behavior lets the dashboard fall behind without slowing the daemon.
|
||||
|
||||
---
|
||||
|
||||
## 3. ClaimNext -- SQL, Locking, Concurrency
|
||||
|
||||
### The SQL
|
||||
|
||||
At `store.go:129-141`:
|
||||
```sql
|
||||
UPDATE tasks SET status='running', attempt=attempt+1, updated_at=datetime('now')
|
||||
WHERE id = (SELECT id FROM tasks WHERE status='queued' ORDER BY id LIMIT 1)
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status,
|
||||
workflow, stage, branch, plan, notes, pr_number, tokens_used,
|
||||
iterations, attempt, park_reason
|
||||
```
|
||||
|
||||
Three operations in one statement:
|
||||
- **Subquery**: selects the oldest queued task (`ORDER BY id LIMIT 1`).
|
||||
- **UPDATE**: atomically marks it `running`, increments `attempt`.
|
||||
- **RETURNING**: returns the full row, scanned by `scanTask()` (line 143).
|
||||
|
||||
### Concurrency Model
|
||||
|
||||
- **Single-process, single-threaded consumers.** SQLite's locking means only one writer at a time. The daemon has a single `Store` backed by a `*sql.DB` with `_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)` (line 61). In WAL mode, readers do not block writers, but `UPDATE` still acquires a write lock -- so two concurrent `ClaimNext` calls would serialize on the database lock.
|
||||
|
||||
- **No distributed claims.** There is no advisory lock, no `SELECT ... FOR UPDATE`, no external coordination. The claim is just the SQL mutation + the WAL busy_timeout (5s). If two daemon processes somehow connected to the same SQLite file, one would get an error or timeout on concurrent UPDATE -- not a correctness issue, but not a supported deployment.
|
||||
|
||||
- **Crash recovery, not fencing.** Instead of distributed locking, `Startup()` calls `RecoverStale()` on boot (`store.go:235`): `UPDATE tasks SET status='queued' WHERE status='running'`. This re-queues any task that was in-flight when the previous process died.
|
||||
|
||||
- **Single-consumer queue semantics.** `Daemon.Cycle()` at line 92 loops: claim, process, claim, process. There is no parallelism within one daemon instance -- `process()` is synchronous. The `for` returns when the queue is empty (ClaimNext returns nil).
|
||||
|
||||
---
|
||||
|
||||
## 4. forge.Issue to store.Task Mapping
|
||||
|
||||
### `forge.Issue` at `forge.go:10-15`
|
||||
|
||||
```go
|
||||
type Issue struct {
|
||||
Number int
|
||||
Title string
|
||||
Body string
|
||||
Labels []string
|
||||
}
|
||||
```
|
||||
|
||||
A pure value type -- no methods, no identity. It represents one GitHub issue at poll time.
|
||||
|
||||
### `store.Task` at `store.go:30-52`
|
||||
|
||||
```go
|
||||
type Task struct {
|
||||
ID int64 // autoincrement PK
|
||||
Owner string // GitHub owner
|
||||
Repo string // GitHub repo
|
||||
IssueNumber int // matches Issue.Number
|
||||
Title string // matches Issue.Title
|
||||
Body string // matches Issue.Body
|
||||
Labels string // comma-separated from Issue.Labels
|
||||
Status string // lifecycle: queued, running, waiting_human, ...
|
||||
Workflow string // routed workflow name
|
||||
Stage string // current stage name
|
||||
Branch string // worktree branch
|
||||
Plan string // PRD / implementation plan
|
||||
Notes string // appended agent notes
|
||||
PRNumber int // opened PR number
|
||||
TokensUsed int
|
||||
Iterations int
|
||||
Attempt int
|
||||
ParkReason string
|
||||
WatchCommentID int64 // human-reply anchor
|
||||
}
|
||||
```
|
||||
|
||||
### Mapping at Enqueue Time
|
||||
|
||||
In `Daemon.poll()` at `daemon.go:112-113`:
|
||||
```go
|
||||
inserted, err := d.Store.EnqueueIssue(ctx,
|
||||
repo.Owner, repo.Name, is.Number, is.Title, is.Body, strings.Join(is.Labels, ","))
|
||||
```
|
||||
|
||||
The forge-side `[]string` labels are joined into a comma-separated string. The FORGE-side structure is flat (Number, Title, Body, Labels) -- it is the STORE that adds status tracking, routing, and operational fields. The `UNIQUE(owner, repo, issue_number)` constraint at `store.go:99` is the idempotency key: re-polling the same issue does not create a duplicate task.
|
||||
|
||||
### Mapping at Enqueue SQL
|
||||
|
||||
`store.go:115-118`:
|
||||
```sql
|
||||
INSERT INTO tasks (owner, repo, issue_number, title, body, labels)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(owner, repo, issue_number) DO NOTHING
|
||||
```
|
||||
|
||||
Only 6 of 18 Task fields are set at creation. The remaining fields (status defaults to `'queued'`, workflow/stage/branch etc. default to `''` or `0`) are filled in during the processing lifecycle.
|
||||
|
||||
---
|
||||
|
||||
## 5. What Changes If ClaimNext Is Replaced with NATS JetStream?
|
||||
|
||||
### Current Architecture
|
||||
```
|
||||
[Ticker] -> Cycle() -> poll() -> [SQLite EnqueueIssue]
|
||||
-> [SQLite ClaimNext] -> process(task) -> [workflow.Run]
|
||||
```
|
||||
The daemon is a single in-memory loop pulling from SQLite. It is **push-based** from SQLite's perspective (the daemon polls the DB), but effectively **single-consumer** -- no parallelism.
|
||||
|
||||
### Target Architecture with NATS JetStream
|
||||
```
|
||||
[GitHub Webhook] -> [NATS JetStream] -> [Daemon consumes from stream]
|
||||
```
|
||||
or
|
||||
```
|
||||
[Ticker] -> poll() -> [NATS JetStream Publish]
|
||||
-> [Daemon Subscribe] -> process(task)
|
||||
```
|
||||
|
||||
### What Stays the Same
|
||||
|
||||
1. **`foreach`-over-repos polling** (`Daemon.poll()`, `daemon.go:108`). The GitHub API polling logic (`IssuesWithLabel`, `AssignedIssues`) is independent of the task queue -- you still poll GitHub the same way, you just publish the discovered issue to a NATS subject instead of INSERTing into SQLite.
|
||||
|
||||
2. **`workflow.Run()` and the entire workflow engine** (`workflow.go:145-185`, `steps.go`, `agent.go`, `feasibility.go`, `implement.go`, `tdd.go`). The workflow pipeline is agnostic to how tasks arrive -- it receives a `*store.Task` and a `TaskContext`. A NATS consumer would still build the same `TaskContext` and call `workflow.Run()`.
|
||||
|
||||
3. **`workflow.Route()`** (`workflow.go:103`). Label-to-workflow routing remains identical -- it operates on `t.Labels` and `t.Workflow`.
|
||||
|
||||
4. **`forge` interface and `GitHubClient`** (`forge.go`, `github.go`). The forge is only called to interact with GitHub (comment, label, PR, react) -- not as the task queue. No forge change needed.
|
||||
|
||||
5. **`events.Bus` and all `emit()` / `Emit()` calls.** The in-process observability bus is orthogonal to task distribution. NATS JetStream would be the task queue, not the event bus; the two are conceptually separate.
|
||||
|
||||
6. **Crash recovery via `RecoverStale()`** would be replaced by NATS's exactly-once delivery (with consumer sequence tracking) or at-least-once with deduplication. But the principle is the same: the daemon should be restartable without losing work.
|
||||
|
||||
7. **`store.Update()` and `store.Transition()`** for persisting task progress. Even with NATS as the queue, you still want an audit trail of task state. SQLite is fine for that -- it just becomes the state store rather than the queue.
|
||||
|
||||
### What Changes
|
||||
|
||||
**A. `Daemon.Run()` and `Cyc1e()` (`daemon.go:72-106`)**
|
||||
|
||||
Currently `Run()` has a ticker that calls `Cycle()` which does both poll-and-drain. With NATS:
|
||||
- The poll ticker would still exist but would `Publish()` discovered issues to a NATS subject rather than `EnqueueIssue`.
|
||||
- The drain loop would be replaced by a NATS subscription callback. The daemon would register a Pull Consumer or a Push Consumer on the stream, and `process()` would be called from the message handler, not from a `ClaimNext()` call.
|
||||
|
||||
Something like:
|
||||
```go
|
||||
func (d *Daemon) Run(ctx context.Context) error {
|
||||
sub, _ := d.JS.PullSubscribe("archie.tasks", ...)
|
||||
for {
|
||||
msgs, _ := sub.Fetch(1, ...)
|
||||
for _, msg := range msgs {
|
||||
task := deserialize(msg.Data)
|
||||
d.process(ctx, task)
|
||||
msg.Ack()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**B. `Store.ClaimNext()` is removed (`store.go:129`).**
|
||||
|
||||
The atomic SQL `UPDATE ... WHERE id = (SELECT ...)` is the heart of the single-consumer model. With NATS, the message broker provides the claim -- by delivering the message to exactly one consumer in the consumer group (JetStream's built-in `MaxDeliver` / `Ack` / `DeliveryGroup`). The entire function is replaced by `sub.Fetch()` or `sub.Consume()`.
|
||||
|
||||
**C. `Store.EnqueueIssue()` (`store.go:114`) becomes optional.**
|
||||
|
||||
You may or may not persist tasks in SQLite at enqueue time. Options:
|
||||
- Keep SQLite as the system of record: the NATS subscriber writes a row on receive, then passes `*store.Task` to `process()`. This preserves the dashboard's ability to query task history without replaying the stream.
|
||||
- Drop SQLite entirely at the queue level: the NATS message body carries the equivalent of `forge.Issue` + routing metadata, and the first workflow stage does the persistence.
|
||||
|
||||
**D. `Daemon.Startup()` crash recovery changes (`daemon.go:52`).**
|
||||
|
||||
`RecoverStale()` (`store.go:234`) re-queues tasks left `running`. With NATS:
|
||||
- If a consumer crashes mid-process, the message is either `NACK`ed or redelivered after the `AckWait` timeout. No explicit recovery step needed.
|
||||
- But: if NATS delivers a message and the daemon starts processing (updates task to `running` in SQLite), then crashes, the NATS message might already be `Ack`ed. You still need the crash-recovery query as a safety net, or you redesign to only `Ack` after the workflow completes.
|
||||
- Best practice: `Ack` *after* `workflow.Run()` returns, and keep `RecoverStale` for the SQLite side.
|
||||
|
||||
**E. Concurrency model changes fundamentally.**
|
||||
|
||||
Currently one daemon processes tasks sequentially (one `ClaimNext` -> `process()` -> next `ClaimNext`). With NATS:
|
||||
- You can horizontally scale: multiple daemon instances subscribe to the same JetStream consumer group, and NATS round-robins delivery.
|
||||
- Within one daemon, you can parallelize: call `process()` in a goroutine per message, bounded by a semaphore. Each message has an independent worktree, so parallel workflows on different repos are safe. (Current SQLite model could also parallelize, but the synchronous `Cycle()` design prevents it.)
|
||||
|
||||
**F. Idempotency moves from SQL UNIQUE constraint to JetStream dedup.**
|
||||
|
||||
Currently `EnqueueIssue` uses `ON CONFLICT DO NOTHING` at `store.go:118`. With NATS, you would use JetStream message deduplication (`Nats-Msg-Id` header set to `owner/repo/issue_number`) to prevent re-processing the same issue enqueue.
|
||||
|
||||
**G. Task ordering.**
|
||||
|
||||
Currently FIFO via `ORDER BY id LIMIT 1`. NATS JetStream supports ordered delivery within a stream, but with multiple repos and priorities this may differ. You would need a stream per repo or use a subject hierarchy like `archie.tasks.<owner>.<repo>` to preserve ordering semantics.
|
||||
|
||||
### Summary Table
|
||||
|
||||
| Component | Current (SQLite) | NATS JetStream |
|
||||
|---|---|---|
|
||||
| Task queue | `tasks` table, `status='queued'` | JetStream stream |
|
||||
| Claim | `UPDATE ... WHERE id = (SELECT ...) RETURNING` | `sub.Fetch()` / consumer group |
|
||||
| Concurrency | Single-process, sequential | Multi-process, parallel via consumer groups |
|
||||
| Idempotency | `ON CONFLICT DO NOTHING` + `UNIQUE` constraint | `Nats-Msg-Id` dedup |
|
||||
| Crash recovery | `RecoverStale()` at startup | NAck/redelivery + eventual `RecoverStale` guard |
|
||||
| Ordering | `ORDER BY id` (FIFO) | Stream ordering per subject |
|
||||
| Daemon.Run() | `time.Ticker` -> `Cycle()` -> {poll, claim-loop} | `time.Ticker` -> poll() -> publish; sub callback -> process() |
|
||||
| `Store.ClaimNext()` | **Must remove** | No equivalent needed |
|
||||
| `Store.EnqueueIssue()` | **Optional** | Still useful as system-of-record |
|
||||
| Workflow engine | Unchanged | Unchanged |
|
||||
| Forge interface | Unchanged | Unchanged |
|
||||
| events.Bus | Unchanged | Unchanged |
|
||||
@@ -0,0 +1,189 @@
|
||||
# nats-integration
|
||||
|
||||
Here is the full analysis.
|
||||
|
||||
---
|
||||
|
||||
## Report: archie-core Codebase Exploration for NATS Integration
|
||||
|
||||
### 1. Current Go Version and Key Dependencies
|
||||
|
||||
**Go version:** `go 1.26.2` (from `/work/apps/archie-core/go.mod`, line 3)
|
||||
|
||||
**Direct dependencies** (from `/work/apps/archie-core/go.mod`):
|
||||
- `github.com/BurntSushi/toml v1.6.0` -- TOML config parsing
|
||||
- `github.com/google/go-github/v78 v78.0.0` -- GitHub API client
|
||||
- `modernc.org/sqlite v1.54.0` -- pure-Go SQLite (no CGo)
|
||||
- `github.com/samcharles93/ai-sdk v0.1.17` -- local LLM SDK (replaced to `/work/projects/ai-sdk`)
|
||||
- `github.com/traefik/yaegi v0.16.1` -- Go interpreter for custom skill/workflow stages
|
||||
|
||||
**Indirect dependencies:** `go-humanize`, `go-querystring`, `uuid`, `go-isatty`, `go-strftime`, `browser`, `bigfft`, `golang.org/x/sys`, `modernc.org/libc/mathutil/memory`
|
||||
|
||||
**Key observation:** The dependency tree is very lean. There are zero messaging, queue, or streaming libraries. No `go.sum` entries match "nats" -- zero NATS transitive dependencies exist.
|
||||
|
||||
---
|
||||
|
||||
### 2. Full Config Struct (all fields, all structs)
|
||||
|
||||
File: `/work/apps/archie-core/internal/config/config.go`
|
||||
|
||||
```
|
||||
Config (205-231)
|
||||
├── WorkDir string `toml:"work_dir"`
|
||||
├── DBPath string `toml:"db_path"`
|
||||
├── PollInterval Duration `toml:"poll_interval"` (custom Duration type, TOML strings like "60s")
|
||||
├── Label string `toml:"label"`
|
||||
├── BotUser string `toml:"bot_user"`
|
||||
├── BotEmail string `toml:"bot_email"`
|
||||
├── DiffCapLines int `toml:"diff_cap_lines"`
|
||||
├── Forge Forge `toml:"forge"`
|
||||
│ ├── Type string `toml:"type"` (default: "github")
|
||||
│ ├── Host string `toml:"host"` (default: "https://github.com")
|
||||
│ └── TokenEnv string `toml:"token_env"` (default: "ARCHIE_GITHUB_TOKEN")
|
||||
├── Dispatch Dispatch `toml:"dispatch"`
|
||||
│ ├── Trigger string `toml:"trigger"` ("assignee", "label", "either"; default: "assignee")
|
||||
│ ├── AckReaction string `toml:"ack_reaction"` ("eyes"; "off" disables)
|
||||
│ └── Labels map[string]string `toml:"labels"` (keys: queued/working/waiting/pr/parked)
|
||||
├── Models map[string]string `toml:"models"` (role -> model ref, e.g. "triage", "planner", "builder")
|
||||
├── Providers map[string]Provider `toml:"providers"`
|
||||
│ ├── Class string `toml:"class"` ("openai", "ollama", etc.)
|
||||
│ ├── APIKeyEnv string `toml:"api_key_env"`
|
||||
│ └── BaseURL string `toml:"base_url"`
|
||||
├── Agent Agent `toml:"agent"`
|
||||
│ ├── Mode string `toml:"mode"` ("inprocess" or "subprocess")
|
||||
│ ├── Command string `toml:"command"` (executable path for subprocess mode)
|
||||
│ └── Env []string `toml:"env"` (extra env vars forwarded to worker)
|
||||
├── Budgets Budgets `toml:"budgets"`
|
||||
│ ├── MaxSteps int `toml:"max_steps"`
|
||||
│ ├── MaxTokens int `toml:"max_tokens"`
|
||||
│ ├── WallClock Duration `toml:"wall_clock"`
|
||||
│ └── GateMaxFailures int `toml:"gate_max_failures"`
|
||||
├── Web Web `toml:"web"`
|
||||
│ └── Listen string `toml:"listen"` (default: "127.0.0.1:8484"; "off" disables)
|
||||
├── Notify Notify `toml:"notify"`
|
||||
│ └── Webhook string `toml:"webhook"` (n8n webhook URL)
|
||||
└── Repos []Repo `toml:"repos"`
|
||||
├── Owner string `toml:"owner"`
|
||||
├── Name string `toml:"name"`
|
||||
├── Base string `toml:"base"` (branch PRs target; default "main")
|
||||
├── Gate [][]string `toml:"gate"` (quality-gate commands)
|
||||
├── Protect []string `toml:"protect"` (path suffixes agents cannot write)
|
||||
├── Ecosystem string `toml:"ecosystem"` ("go", "python", "node", "rust", "custom")
|
||||
├── Preflight [][]string `toml:"preflight"` (override ecosystem default)
|
||||
└── TestGlob string `toml:"test_glob"` (override ecosystem default)
|
||||
```
|
||||
|
||||
The `Config` struct is loaded by `config.Load(path)` which decodes TOML, then applies defaults. The `Load()` function validates: agent mode, provider URLs, dispatch trigger values, dispatch labels, bot_user requirement, repos requirement, forge type (currently only "github"), and test glob patterns.
|
||||
|
||||
---
|
||||
|
||||
### 3. How the Project is Built/Run Today
|
||||
|
||||
**No Makefile, Taskfile, justfile, Dockerfile, docker-compose, or CI config files exist anywhere in the project.**
|
||||
|
||||
The project is built and run directly with the Go toolchain:
|
||||
|
||||
- **Build:** `go build ./cmd/archied` to build the daemon binary, `go build ./cmd/archie-agent` for the subprocess worker.
|
||||
- **Run:** `archied -config ~/.config/archie/config.toml` (the `run()` func in `cmd/archied/main.go`).
|
||||
- **Entry points:**
|
||||
- `/work/apps/archie-core/cmd/archied/main.go` -- the daemon (orchestrator)
|
||||
- `/work/apps/archie-core/cmd/archie-agent/main.go` -- standalone worker (used in subprocess mode)
|
||||
- **Composition root** is `cmd/archied/main.go`. It wires: config loading, forge client creation, SQLite store, event bus, web UI server, LLM runtime, agent runner, worktree manager, workflow registry.
|
||||
- **Daemon lifecycle:** `Startup()` (recovery, invitation accept, push verify) -> `Run()` (poll loop with ticker) -> each `Cycle()` does: poll issues, reconcile PRs, check waiting tasks, drain queued tasks sequentially.
|
||||
- **Testing:** standard `go test ./...` -- no bespoke task runner.
|
||||
|
||||
---
|
||||
|
||||
### 4. Existing NATS or Messaging Patterns
|
||||
|
||||
**NATS: None whatsoever.** Zero references in Go source, zero in go.sum, zero in any config.
|
||||
|
||||
**Existing messaging system -- in-process event bus** (`/work/apps/archie-core/internal/events/events.go`):
|
||||
|
||||
This is a lightweight in-process pub/sub bus designed for observability. Key design:
|
||||
- Single `Event` type carries all observability data (timestamps, kind strings, task IDs, freeform `Data map[string]any`)
|
||||
- Mutex-based fan-out with bounded per-subscriber channels
|
||||
- **Drops on overflow** -- a stalled dashboard client cannot backpressure the task engine
|
||||
- Subscribers register via `bus.Subscribe(buffer int)` which returns a `*Sub` with a read-only `C <-chan Event`
|
||||
- Event kinds: `task_queued`, `stage_start`, `stage_finish`, `agent_finish`, `parked`, `outcome`, `pr_merged`, `pr_rejected`, `log`
|
||||
|
||||
**How it is used** (from `cmd/archied/main.go` lines 86-107):
|
||||
1. A `bus := events.NewBus()` is created in `main()`
|
||||
2. A store-sink subscriber consumes all events, writes them to SQLite, then broadcasts to the web UI
|
||||
3. The `webui.Server.Broadcast()` fans events to SSE clients
|
||||
4. The `daemon.Daemon` has a `Bus *events.Bus` field used in `emit()` calls throughout task lifecycle
|
||||
|
||||
**Current architecture is single-process:** The daemon polls GitHub issues, processes them sequentially in-process (or via subprocess `archie-agent`), and all state lives in SQLite. There is no multi-worker, no job queue, no cross-process communication beyond the subprocess protocol in `internal/agentexec/`.
|
||||
|
||||
---
|
||||
|
||||
### 5. Recommended `[nats]` Config Block
|
||||
|
||||
Following the existing TOML conventions (see `/work/apps/archie-core/config.example.toml` and the `config.go` struct patterns), a `[nats]` block should:
|
||||
|
||||
- Match the two-level key style (e.g., `[forge]`, `[dispatch]`, `[web]`)
|
||||
- Use lowercase with underscores for field names
|
||||
- Support a `"off"` / empty-string sentinel for optional features
|
||||
- Be a new struct on the `Config` type, not nested under any existing section
|
||||
|
||||
Based on the existing patterns, the convention-compliant config block would look like:
|
||||
|
||||
```toml
|
||||
# NATS JetStream configuration for distributed task queue.
|
||||
# Remove or comment out these sections to run in single-process mode.
|
||||
[nats]
|
||||
url = "nats://localhost:4222" # NATS server URL
|
||||
# token = "$NATS_TOKEN" # or user/password for auth (use env var)
|
||||
# user = "archie"
|
||||
# password_env = "NATS_PASSWORD"
|
||||
|
||||
[nats.tls] # optional TLS section as a sub-table
|
||||
# cert = "/path/to/cert.pem"
|
||||
# key = "/path/to/key.pem"
|
||||
# ca = "/path/to/ca.pem"
|
||||
|
||||
[nats.jetstream] # JetStream-specific options
|
||||
# stream = "archie-tasks" # stream name (default: auto-created)
|
||||
# bucket = "archie-state" # KV bucket for task state (optional)
|
||||
# replicas = 3 # stream replication factor
|
||||
# max_deliver = 10 # max delivery attempts for a message
|
||||
# ack_wait = "5m" # ack wait timeout
|
||||
```
|
||||
|
||||
In Go, this would map to a struct like:
|
||||
|
||||
```go
|
||||
type NATS struct {
|
||||
URL string `toml:"url"`
|
||||
Token string `toml:"token"`
|
||||
User string `toml:"user"`
|
||||
PasswordEnv string `toml:"password_env"`
|
||||
TLS *NATSTLS `toml:"tls,omitempty"`
|
||||
JetStream *JetStream `toml:"jetstream,omitempty"`
|
||||
}
|
||||
|
||||
type NATSTLS struct {
|
||||
Cert string `toml:"cert"`
|
||||
Key string `toml:"key"`
|
||||
CA string `toml:"ca"`
|
||||
}
|
||||
|
||||
type JetStream struct {
|
||||
Stream string `toml:"stream"`
|
||||
Bucket string `toml:"bucket"`
|
||||
Replicas int `toml:"replicas"`
|
||||
MaxDeliver int `toml:"max_deliver"`
|
||||
AckWait Duration `toml:"ack_wait"`
|
||||
}
|
||||
```
|
||||
|
||||
And on `Config`:
|
||||
```go
|
||||
NATS *NATS `toml:"nats,omitempty"` // nil = no NATS, single-process mode
|
||||
```
|
||||
|
||||
Key style considerations:
|
||||
- Existing config uses `password_env` pattern (see `token_env`, `api_key_env`) for secrets that come from environment variables
|
||||
- The `Duration` type is already available for timer fields like `ack_wait`
|
||||
- Using a pointer (`*NATS`) keeps the "nil means not configured" semantics, consistent with the daemon's fallback to single-process operation
|
||||
- The `[nats.tls]` sub-table pattern mirrors how `[dispatch.labels]` is a sub-table under `[dispatch]`
|
||||
@@ -0,0 +1,707 @@
|
||||
# nats-design
|
||||
|
||||
I now have a thorough understanding of the entire codebase. Let me compile my implementation plan.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Plan: Phase 1 -- NATS Task Distribution for archie-core
|
||||
|
||||
### Overview
|
||||
|
||||
This phase adds optional NATS JetStream-based task distribution to `archied`. When the `[nats]` config block is present, newly discovered issues are published to NATS subjects rather than enqueued directly into SQLite. A pull consumer in the same daemon process receives those messages, stores them in SQLite (idempotent dedup via `ON CONFLICT DO NOTHING`), claims them, and runs the workflow. When NATS is absent, the existing SQLite-only flow (ClaimNext) continues unchanged.
|
||||
|
||||
---
|
||||
|
||||
### Step 1: Add NATS Go Dependency
|
||||
|
||||
**File(s):** `/work/apps/archie-core/go.mod`, `/work/apps/archie-core/go.sum`
|
||||
|
||||
**Changes:**
|
||||
- Add `github.com/nats-io/nats.go v1.42.0` (or latest stable) to `require` block
|
||||
- The JetStream API is now embedded in `nats.go` (no separate `nats.go/jetstream` module since v1.33+), so only one dependency line is needed
|
||||
- Run `go mod tidy` to resolve transitive deps
|
||||
|
||||
**Connection to existing code:** This is the only new external dependency. The current module has only `BurntSushi/toml`, `google/go-github`, `modernc.org/sqlite`, `ai-sdk`, and `traefik/yaegi`.
|
||||
|
||||
**Test/verification:** `go build ./...` succeeds. `go mod tidy` is clean.
|
||||
|
||||
---
|
||||
|
||||
### Step 2: Add `[nats]` Config Section
|
||||
|
||||
**File(s):** `/work/apps/archie-core/internal/config/config.go`, `/work/apps/archie-core/internal/config/config_test.go`, `/work/apps/archie-core/config.example.toml`
|
||||
|
||||
**New type in `config.go`:**
|
||||
```go
|
||||
// NATSConfig configures NATS JetStream for task distribution. When URL is
|
||||
// empty the existing SQLite ClaimNext flow is used.
|
||||
type NATSConfig struct {
|
||||
// URL is the NATS server address, e.g. "nats://localhost:4222".
|
||||
// Empty means NATS is not configured.
|
||||
URL string `toml:"url"`
|
||||
// TokenEnv optionally names an env var holding a NATS auth token/password.
|
||||
// When empty, no authentication is attempted.
|
||||
TokenEnv string `toml:"token_env"`
|
||||
}
|
||||
```
|
||||
|
||||
**New field in `Config` struct:**
|
||||
```go
|
||||
type Config struct {
|
||||
// ... all existing fields ...
|
||||
NATS NATSConfig `toml:"nats"`
|
||||
}
|
||||
```
|
||||
|
||||
**Validation in `Load()`:** No new validation errors needed. `cfg.NATS.URL == ""` is the disabled state. If `TokenEnv` is set but `URL` is empty, log a warning at startup (not a config error -- the token field is simply unused).
|
||||
|
||||
**Default behavior:** When the TOML has no `[nats]` block, `cfg.NATS.URL` remains `""` and NATS is not used. This is the nil-means-disabled semantics.
|
||||
|
||||
**Test in `config_test.go`:** Add `TestNATSDefaults` -- verify that (a) a config without `[nats]` has empty URL, (b) a config with `[nats]` but empty URL loads fine, (c) a config with a NATS URL parses correctly. Add to existing `TestExampleConfigLoads` so the example config stays valid.
|
||||
|
||||
**Config example in `config.example.toml`:**
|
||||
```toml
|
||||
[nats]
|
||||
# url = "nats://localhost:4222"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 3: Create `internal/nats` Package
|
||||
|
||||
**File(s) to create:** `/work/apps/archie-core/internal/nats/client.go`, `/work/apps/archie-core/internal/nats/client_test.go`, `/work/apps/archie-core/internal/nats/subjects.go`
|
||||
|
||||
#### 3a. Subject Constants (`subjects.go`)
|
||||
|
||||
```go
|
||||
package nats
|
||||
|
||||
import "strings"
|
||||
|
||||
// Task subject constants. The subject encodes the workflow type so that
|
||||
// future horizontal scaling can route tasks to workflow-specific consumers.
|
||||
const (
|
||||
SubjectTaskBug = "archie.task.bug"
|
||||
SubjectTaskFeature = "archie.task.feature"
|
||||
SubjectTaskDefault = "archie.task.default"
|
||||
SubjectTaskBootstrap = "archie.task.bootstrap"
|
||||
)
|
||||
|
||||
// SubjectForLabels picks the NATS subject based on issue labels, following
|
||||
// the same label-to-workflow mapping as workflow.Route.
|
||||
// - "bug" -> archie.task.bug
|
||||
// - "feature" -> archie.task.feature
|
||||
// - "bootstrap" -> archie.task.bootstrap
|
||||
// - default -> archie.task.default
|
||||
func SubjectForLabels(labels []string) string {
|
||||
for _, l := range labels {
|
||||
switch strings.TrimSpace(l) {
|
||||
case "bug":
|
||||
return SubjectTaskBug
|
||||
case "feature":
|
||||
return SubjectTaskFeature
|
||||
case "bootstrap":
|
||||
return SubjectTaskBootstrap
|
||||
}
|
||||
}
|
||||
return SubjectTaskDefault
|
||||
}
|
||||
```
|
||||
|
||||
**Tests:** Verify subject routing: `SubjectForLabels([]string{"bug"})` returns `SubjectTaskBug`; `SubjectForLabels([]string{"feature"})` returns `SubjectTaskFeature`; `SubjectForLabels([]string{"enhancement"})` returns `SubjectTaskDefault`; `SubjectForLabels([]string{"bug", "feature"})` returns `SubjectTaskBug` (first match wins, matching workflow.Route behavior).
|
||||
|
||||
#### 3b. Client (`client.go`)
|
||||
|
||||
```go
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
const (
|
||||
streamName = "ARCHIE_TASKS"
|
||||
consumerName = "archie-daemon"
|
||||
msgPrefix = "archie:" // for Msg-Id dedup
|
||||
dedupWindow = 2 * time.Minute
|
||||
pollTimeout = 2 * time.Second // Fetch wait time before returning nil
|
||||
maxFetchCount = 1
|
||||
)
|
||||
|
||||
// TaskMessage is the NATS payload for a discovered issue.
|
||||
type TaskMessage struct {
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Number int `json:"number"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Labels string `json:"labels"` // comma-separated, as seen at enqueue time
|
||||
}
|
||||
|
||||
// Client manages the NATS connection and JetStream resources.
|
||||
type Client struct {
|
||||
conn *nats.Conn
|
||||
js jetstream.JetStream
|
||||
stream jetstream.Stream
|
||||
consumer jetstream.Consumer
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// Connect dials url, sets up the JetStream stream and pull consumer.
|
||||
// The stream is created with WorkQueue retention (message removed after ack),
|
||||
// file storage, and the subject pattern archie.task.>.
|
||||
func Connect(ctx context.Context, url string, log *slog.Logger) (*Client, error) {
|
||||
nc, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nats connect: %w", err)
|
||||
}
|
||||
js, err := jetstream.New(nc)
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, fmt.Errorf("nats jetstream: %w", err)
|
||||
}
|
||||
|
||||
// Create or update stream
|
||||
stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
|
||||
Name: streamName,
|
||||
Subjects: []string{"archie.task.>"},
|
||||
Storage: jetstream.FileStorage,
|
||||
Retention: jetstream.WorkQueuePolicy,
|
||||
MaxMsgsPerSubject: 1, // at most one message per subject per task
|
||||
Duplicates: dedupWindow,
|
||||
})
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, fmt.Errorf("nats stream: %w", err)
|
||||
}
|
||||
|
||||
// Create or update pull consumer
|
||||
consumer, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
|
||||
Name: consumerName,
|
||||
Durable: consumerName,
|
||||
FilterSubject: "archie.task.>",
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
MaxDeliver: 3, // retry 3 times before parking
|
||||
AckWait: 5 * time.Minute, // ack within 5 mins of Fetch
|
||||
InactiveThreshold: 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, fmt.Errorf("nats consumer: %w", err)
|
||||
}
|
||||
|
||||
return &Client{conn: nc, js: js, stream: stream, consumer: consumer, log: log}, nil
|
||||
}
|
||||
|
||||
// Close drains and closes the NATS connection.
|
||||
func (c *Client) Close() { c.conn.Close() }
|
||||
|
||||
// PublishTask publishes a discovered issue to the appropriate NATS subject.
|
||||
// The Msg-Id header enables JetStream dedup within the dedup window.
|
||||
// Returns nil on success.
|
||||
func (c *Client) PublishTask(ctx context.Context, owner, repo string, number int, title, body, labels string) error {
|
||||
msg := TaskMessage{
|
||||
Owner: owner,
|
||||
Repo: repo,
|
||||
Number: number,
|
||||
Title: title,
|
||||
Body: body,
|
||||
Labels: labels,
|
||||
}
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
subject := SubjectForLabels(splitLabels(labels))
|
||||
headers := nats.Header{}
|
||||
msgID := fmt.Sprintf("%s%s/%s/%d", msgPrefix, owner, repo, number)
|
||||
headers.Set("Nats-Msg-Id", msgID)
|
||||
|
||||
publish, err := c.js.PublishMsg(ctx, &nats.Msg{
|
||||
Subject: subject,
|
||||
Data: data,
|
||||
Header: headers,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("nats publish: %w", err)
|
||||
}
|
||||
if publish == nil || publish.Sequence == 0 {
|
||||
// Duplicate suppressed by Msg-Id dedup window
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fetch retrieves one task message from the pull consumer. Returns the
|
||||
// message, or nil if the context is cancelled or the fetch times out.
|
||||
// The caller MUST Ack or Nak the message after processing.
|
||||
func (c *Client) Fetch(ctx context.Context) (jetstream.Msg, error) {
|
||||
msgs, err := c.consumer.Fetch(maxFetchCount, jetstream.FetchMaxWait(pollTimeout))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nats fetch: %w", err)
|
||||
}
|
||||
for msg := range msgs.Messages() {
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
if err := msgs.Error(); err != nil {
|
||||
return nil, fmt.Errorf("nats fetch error: %w", err)
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
return nil, nil // no message available
|
||||
}
|
||||
|
||||
// DecodeTask decodes a TaskMessage from a NATS message.
|
||||
func DecodeTask(msg jetstream.Msg) (TaskMessage, error) {
|
||||
var tm TaskMessage
|
||||
if err := json.Unmarshal(msg.Data(), &tm); err != nil {
|
||||
return tm, fmt.Errorf("nats decode: %w", err)
|
||||
}
|
||||
return tm, nil
|
||||
}
|
||||
|
||||
func splitLabels(labels string) []string {
|
||||
if labels == "" {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(labels, ",")
|
||||
}
|
||||
```
|
||||
|
||||
**Key design decisions in this struct:**
|
||||
- `DedupWindow: 2 minutes` -- matching the typical poll interval. A restarted daemon within 2 minutes won't get dupes.
|
||||
- `MaxDeliver: 3` -- retries before a message is placed on the NA pile (NATS moves it to a dead-letter state internally).
|
||||
- `AckWait: 5 minutes` -- generous for long-running workflows.
|
||||
- `WorkQueuePolicy` -- message removed from stream after ack.
|
||||
- `FilterSubject: "archie.task.>"` -- consumer receives all task subjects.
|
||||
|
||||
**Tests for `client_test.go`:**
|
||||
|
||||
The test needs an embedded NATS server. Use `nats-server` binary or the `github.com/nats-io/nats-server/v2/server` package in test mode.
|
||||
|
||||
```go
|
||||
func TestConnectAndPublish(t *testing.T) {
|
||||
// Start embedded NATS server on random port
|
||||
srv := startEmbeddedNATSServer(t)
|
||||
defer srv.Shutdown()
|
||||
|
||||
url := fmt.Sprintf("nats://localhost:%d", srv.Port())
|
||||
client, err := Connect(context.Background(), url, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
// Publish a task
|
||||
if err := client.PublishTask(ctx, "sam", "todo", 1, "fix bug", "body", "bug"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Fetch it back
|
||||
msg, err := client.Fetch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg == nil {
|
||||
t.Fatal("expected a message")
|
||||
}
|
||||
|
||||
tm, err := DecodeTask(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tm.Owner != "sam" || tm.Number != 1 {
|
||||
t.Fatalf("unexpected task: %+v", tm)
|
||||
}
|
||||
msg.Ack()
|
||||
}
|
||||
|
||||
func TestDedup(t *testing.T) {
|
||||
// Publish same task twice; second publish should be deduped
|
||||
// Verify by checking PublishTask returns no error both times
|
||||
// and only one message is consumable
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 4: Add `ClaimByIssue` to Store
|
||||
|
||||
**File(s):** `/work/apps/archie-core/internal/store/store.go`, `/work/apps/archie-core/internal/store/store_test.go`
|
||||
|
||||
**Changes to `store.go`:**
|
||||
|
||||
Add a new method that atomically claims a task by its issue identity rather than the oldest-queued:
|
||||
|
||||
```go
|
||||
// ClaimByIssue atomically claims a queued task by owner/repo/issue_number.
|
||||
// Returns nil if the task is not in queued state (already claimed, parked,
|
||||
// or completed). This is used by the NATS consumer path where the task
|
||||
// was just inserted via EnqueueIssue and needs to be claimed immediately.
|
||||
func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*Task, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
UPDATE tasks SET status='running', attempt=attempt+1, updated_at=datetime('now')
|
||||
WHERE owner=? AND repo=? AND issue_number=? AND status='queued'
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status,
|
||||
workflow, stage, branch, plan, notes, pr_number, tokens_used,
|
||||
iterations, attempt, park_reason`, owner, repo, number)
|
||||
t, err := scanTask(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
```
|
||||
|
||||
**Why a new method instead of reusing ClaimNext?** Because ClaimNext claims the *oldest* `queued` row. When multiple tasks are in the queue (e.g., after a daemon restart), claiming the one we just inserted is not guaranteed. ClaimByIssue targets the exact row.
|
||||
|
||||
**Test in `store_test.go`:**
|
||||
|
||||
Add `TestClaimByIssue`:
|
||||
```go
|
||||
func TestClaimByIssue(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Enqueue two tasks
|
||||
s.EnqueueIssue(ctx, "sam", "todo", 1, "t1", "", "bug")
|
||||
s.EnqueueIssue(ctx, "sam", "todo", 2, "t2", "", "feature")
|
||||
|
||||
// Claim task 2 by issue (not the oldest)
|
||||
task, err := s.ClaimByIssue(ctx, "sam", "todo", 2)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimByIssue = (%v, %v)", task, err)
|
||||
}
|
||||
if task.IssueNumber != 2 || task.Status != StatusRunning {
|
||||
t.Fatalf("unexpected task: %+v", task)
|
||||
}
|
||||
|
||||
// Claiming the same issue again should return nil
|
||||
task2, err := s.ClaimByIssue(ctx, "sam", "todo", 2)
|
||||
if err != nil || task2 != nil {
|
||||
t.Fatalf("second claim must return nil, got (%v, %v)", task2, err)
|
||||
}
|
||||
|
||||
// ClaimNext should now pick up task 1 (still queued)
|
||||
task3, _ := s.ClaimNext(ctx)
|
||||
if task3 == nil || task3.IssueNumber != 1 {
|
||||
t.Fatalf("expected task 1, got %+v", task3)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 5: Modify Daemon to Support NATS
|
||||
|
||||
**File(s):** `/work/apps/archie-core/internal/daemon/daemon.go`, `/work/apps/archie-core/internal/daemon/daemon_test.go`
|
||||
|
||||
#### 5a. Add NATS Field to Daemon
|
||||
|
||||
```go
|
||||
import (
|
||||
// ... existing imports ...
|
||||
"github.com/samcharles93/archie-core/internal/nats"
|
||||
)
|
||||
|
||||
type Daemon struct {
|
||||
// ... all existing fields ...
|
||||
Nats *nats.Client // nil means NATS not configured; use SQLite path
|
||||
}
|
||||
```
|
||||
|
||||
#### 5b. Modify `poll()` for NATS Publish Path
|
||||
|
||||
The `poll()` method needs a branch for NATS. When `d.Nats != nil`, publish to NATS instead of calling `Store.EnqueueIssue`. The ack reaction, state label setting, and event emission remain the same -- they reflect discovery, not storage.
|
||||
|
||||
Refactored `poll()`:
|
||||
```go
|
||||
func (d *Daemon) poll(ctx context.Context) {
|
||||
for _, repo := range d.Cfg.Repos {
|
||||
issues := d.pollIssues(ctx, repo)
|
||||
for _, is := range issues {
|
||||
inserted := d.tryPublish(ctx, repo, is)
|
||||
if !inserted {
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
continue
|
||||
}
|
||||
d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title)
|
||||
if ack := d.Cfg.Dispatch.AckReaction; ack != "" {
|
||||
if err := d.Forge.React(ctx, repo.Owner, repo.Name, is.Number, ack); err != nil {
|
||||
d.Log.Warn("ack reaction failed", "issue", is.Number, "err", err)
|
||||
}
|
||||
}
|
||||
d.Forge.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindTaskQueued, Repo: repo.FullName(),
|
||||
Issue: is.Number, Detail: is.Title,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tryPublish returns true if this issue was accepted (either enqueued in SQLite
|
||||
// or published to NATS) for the first time. False means it was already tracked.
|
||||
func (d *Daemon) tryPublish(ctx context.Context, repo config.Repo, is forge.Issue) bool {
|
||||
labels := strings.Join(is.Labels, ",")
|
||||
|
||||
if d.Nats != nil {
|
||||
// When NATS is configured, we must check if the issue is already known
|
||||
// before publishing -- we still need maybeRetryParked to work. The
|
||||
// NATS Msg-Id dedup prevents duplicate messages but we want to detect
|
||||
// the "already tracked" case here to allow retry-parked detection.
|
||||
existing, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
|
||||
if err != nil {
|
||||
d.Log.Error("check existing failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return false
|
||||
}
|
||||
if existing != nil {
|
||||
return false // already tracked
|
||||
}
|
||||
|
||||
if err := d.Nats.PublishTask(ctx, repo.Owner, repo.Name, is.Number, is.Title, is.Body, labels); err != nil {
|
||||
d.Log.Error("nats publish failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// SQLite path (unchanged logic, extracted for clarity)
|
||||
inserted, err := d.Store.EnqueueIssue(ctx,
|
||||
repo.Owner, repo.Name, is.Number, is.Title, is.Body, labels)
|
||||
if err != nil {
|
||||
d.Log.Error("enqueue failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return false
|
||||
}
|
||||
return inserted
|
||||
}
|
||||
```
|
||||
|
||||
Note: For the NATS path, we call `Store.TaskByIssue` first. This is a read-only check that only reads, never writes. The actual storage happens in the NATS consumer. This preserves the `maybeRetryParked` behavior.
|
||||
|
||||
#### 5c. Modify `Cycle()` for NATS Consumer
|
||||
|
||||
```go
|
||||
func (d *Daemon) Cycle(ctx context.Context) {
|
||||
d.poll(ctx)
|
||||
d.reconcilePRs(ctx)
|
||||
d.checkWaiting(ctx)
|
||||
if d.Nats != nil {
|
||||
d.drainNATS(ctx)
|
||||
} else {
|
||||
d.drainSQLite(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// drainSQLite processes queued tasks from SQLite (existing behavior).
|
||||
func (d *Daemon) drainSQLite(ctx context.Context) {
|
||||
for {
|
||||
task, err := d.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
d.Log.Error("claim failed", "err", err)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
return
|
||||
}
|
||||
d.process(ctx, task)
|
||||
}
|
||||
}
|
||||
|
||||
// drainNATS processes tasks from NATS, falling back to SQLite for
|
||||
// requeued tasks (waiting_human, retry-parked).
|
||||
func (d *Daemon) drainNATS(ctx context.Context) {
|
||||
for {
|
||||
// Try NATS first
|
||||
msg, err := d.Nats.Fetch(ctx)
|
||||
if err != nil {
|
||||
d.Log.Error("nats fetch failed", "err", err)
|
||||
return
|
||||
}
|
||||
if msg != nil {
|
||||
d.processNATSTask(ctx, msg)
|
||||
// After processing, try again immediately
|
||||
continue
|
||||
}
|
||||
|
||||
// Fall back to SQLite for requeued tasks that came via direct
|
||||
// calls to Store.Requeue (waiting_human approval, retry-parked).
|
||||
task, err := d.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
d.Log.Error("sqlite claim failed", "err", err)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
return
|
||||
}
|
||||
d.process(ctx, task)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** The dual-drain approach means newly discovered tasks come through NATS and requeued tasks (waiting_human approval, retry-parked) come through SQLite ClaimNext. This is clean and avoids needing to publish NATS messages for every requeue.
|
||||
|
||||
#### 5d. Add `processNATSTask`
|
||||
|
||||
```go
|
||||
func (d *Daemon) processNATSTask(ctx context.Context, msg jetstream.Msg) {
|
||||
// Decode
|
||||
tm, err := nats.DecodeTask(msg)
|
||||
if err != nil {
|
||||
d.Log.Error("nats decode failed", "err", err)
|
||||
msg.Ack() // bad message, don't retry
|
||||
return
|
||||
}
|
||||
|
||||
// Store in SQLite (idempotent — ON CONFLICT DO NOTHING)
|
||||
inserted, err := d.Store.EnqueueIssue(ctx, tm.Owner, tm.Repo, tm.Number, tm.Title, tm.Body, tm.Labels)
|
||||
if err != nil {
|
||||
d.Log.Error("nats enqueue failed", "err", err)
|
||||
msg.Nak()
|
||||
return
|
||||
}
|
||||
|
||||
// Claim the task by identity
|
||||
task, err := d.Store.ClaimByIssue(ctx, tm.Owner, tm.Repo, tm.Number)
|
||||
if err != nil {
|
||||
d.Log.Error("nats claim failed", "err", err)
|
||||
msg.Nak()
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
// Task already claimed by another consumer (multi-daemon scenario)
|
||||
// or in a terminal state. Ack and move on.
|
||||
msg.Ack()
|
||||
return
|
||||
}
|
||||
|
||||
// Process (this sets labels, runs workflow, records outcome)
|
||||
d.process(ctx, task)
|
||||
|
||||
// Ack after processing completes.
|
||||
// If the daemon crashes before ack, the NATS message is redelivered.
|
||||
// EnqueueIssue's idempotency + ClaimByIssue's nil-on-not-queued guard
|
||||
// prevents double-processing.
|
||||
msg.Ack()
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 6: Wire NATS in `cmd/archied/main.go`
|
||||
|
||||
**File(s):** `/work/apps/archie-core/cmd/archied/main.go`
|
||||
|
||||
**Changes:**
|
||||
|
||||
Add import for the nats package:
|
||||
```go
|
||||
"github.com/samcharles93/archie-core/internal/nats"
|
||||
```
|
||||
|
||||
Between store opening and daemon construction, add:
|
||||
```go
|
||||
// NATS client (optional)
|
||||
var natsClient *nats.Client
|
||||
if cfg.NATS.URL != "" {
|
||||
natsClient, err = nats.Connect(ctx, cfg.NATS.URL, log)
|
||||
if err != nil {
|
||||
log.Error("nats connect failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
defer natsClient.Close()
|
||||
log.Info("nats connected", "url", cfg.NATS.URL)
|
||||
}
|
||||
```
|
||||
|
||||
Add to Daemon construction:
|
||||
```go
|
||||
d := &daemon.Daemon{
|
||||
// ... all existing fields ...
|
||||
Nats: natsClient,
|
||||
}
|
||||
```
|
||||
|
||||
The `--once` flag path should still work: `d.Cycle(ctx)` handles both NATS and SQLite paths. When NATS is configured and `--once` is used, the Cycle does poll + drainNATS once. Since Fetch has a 2-second timeout, `drainNATS` will return after the timeout if no message is available, which is fine for the one-shot case.
|
||||
|
||||
---
|
||||
|
||||
### Step 7: Integration Verification
|
||||
|
||||
**Approach:** Manual end-to-end test with a local NATS server.
|
||||
|
||||
1. Start `nats-server` locally (or via Docker: `docker run -p 4222:4222 nats`)
|
||||
2. Create a `config.toml` with:
|
||||
```toml
|
||||
bot_user = "test-bot"
|
||||
[nats]
|
||||
url = "nats://localhost:4222"
|
||||
# ... other required fields
|
||||
```
|
||||
3. Run `archied --once`
|
||||
4. Verify:
|
||||
- `nats pub` / `nats sub` shows the task subject messages
|
||||
- NATS JetStream stream `ARCHIE_TASKS` exists (`nats stream list`)
|
||||
- The task appears in SQLite after the consumer processes it
|
||||
- Workflow completes normally
|
||||
|
||||
**Automated integration test (future, not Phase 1):** A test that starts an embedded NATS server, creates a daemon with NATS configured, simulates an issue poll, and verifies the full cycle. Phase 1 keeps tests at the unit level.
|
||||
|
||||
---
|
||||
|
||||
### Summary of All Changes
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| 1 | `go.mod`, `go.sum` | Add `github.com/nats-io/nats.go` |
|
||||
| 2 | `internal/config/config.go` | Add `NATSConfig` struct, `NATS` field to `Config` |
|
||||
| 2 | `internal/config/config_test.go` | Test NATS config loading |
|
||||
| 2 | `config.example.toml` | Add commented-out `[nats]` block |
|
||||
| 3a | `internal/nats/subjects.go` | Subject constants + `SubjectForLabels` |
|
||||
| 3b | `internal/nats/client.go` | `Client` struct, `Connect`, `Close`, `PublishTask`, `Fetch`, `DecodeTask` |
|
||||
| 3b | `internal/nats/client_test.go` | Unit tests with embedded NATS server |
|
||||
| 4 | `internal/store/store.go` | Add `ClaimByIssue` method |
|
||||
| 4 | `internal/store/store_test.go` | Test `ClaimByIssue` |
|
||||
| 5 | `internal/daemon/daemon.go` | Add `Nats` field, refactor `poll()`, add `drainNATS`/`drainSQLite`/`processNATSTask`, modify `Cycle()` |
|
||||
| 5 | `internal/daemon/daemon_test.go` | No changes needed for Phase 1 (existing tests unchanged) |
|
||||
| 6 | `cmd/archied/main.go` | Wire `nats.Connect`, pass client to Daemon |
|
||||
|
||||
### Design Decisions and Rationale
|
||||
|
||||
1. **Dual inner loop (NATS then SQLite) for Phase 1.** Rather than modifying `Requeue` to also publish NATS messages, the NATS drain falls back to ClaimNext for requeued tasks. Simple, works, and the fallback disappears in a later phase when requeue itself publishes NATS messages.
|
||||
|
||||
2. **Msg-Id dedup instead of SQL UNIQUE for NATS path.** The existing `EnqueueIssue` with `ON CONFLICT DO NOTHING` is the idempotency mechanism in the consumer. The NATS Msg-Id dedup is a first-line defense to avoid storing duplicate messages at all. Together they form a robust dedup chain.
|
||||
|
||||
3. **Workflow subject routing duplicates `Route()` logic.** The `SubjectForLabels` function mirrors `workflow.Route`'s label-to-workflow mapping. This is intentional -- the subject encodes the workflow type so future multi-daemon setups can filter by subject. The duplication is minimal (one small function) and is kept in the `nats` package to avoid a dependency on the `workflow` package.
|
||||
|
||||
4. **`ClaimByIssue` is a targeted query, not a general claim.** It only claims a task by the exact owner/repo/number triple and only when it's in `queued` status. This is safe for the NATS consumer where we just inserted the task. It also works as a lock: two consumers racing on the same message will see one succeed and one get nil.
|
||||
|
||||
5. **Three retries, 5-minute ack wait.** NATS JetStream redelivers unacked messages. With `MaxDeliver: 3`, a failing task is retried twice after the first attempt. After 3 failures, the message goes to the NA pile (JetStream's internal dead state for work queues). This is a safety net, not a permanent error -- eventually the operator checks the NATS dead-letter state or we add a dedicated handler.
|
||||
|
||||
6. **Ack after `process()` completes, even on error.** If the workflow parks the task, that's a successful outcome from the task distribution perspective -- the message is acked and removed from the stream. Only daemon crashes leave the message unacked.
|
||||
|
||||
### Potential Challenges
|
||||
|
||||
1. **Embedded NATS server for tests.** Go tests that need a real NATS server typically use `github.com/nats-io/nats-server/v2/server` embedded mode. This adds a test-only dependency. Alternative: use a `nats-server` binary in CI. For Phase 1, the test file should use an embedded server and note it in the build tag if the binary isn't available.
|
||||
|
||||
2. **`drainNATS` blocks on Fetch.** `Fetch` has a 2-second poll timeout before returning nil. When the queue is empty, the NATS drain exits (returns nil) and the Cycle ends, which is correct. The ticker in `Run()` creates a new Cycle on the next tick, so empty-queue idle detection is fine.
|
||||
|
||||
3. **`SubjectForLabels` vs `Route()` divergence risk.** If someone adds a new label-to-workflow mapping in `Route()`, they need to update `SubjectForLabels` too. Mitigation: keep both functions small, add a comment referencing the other, and add a cross-package test that verifies they stay in sync on the known label set.
|
||||
|
||||
---
|
||||
|
||||
### Critical Files for Implementation
|
||||
- `/work/apps/archie-core/internal/daemon/daemon.go` — Core changes: poll branching, Cycle splitting, NATS consumer logic, new helper methods
|
||||
- `/work/apps/archie-core/internal/config/config.go` — Add NATSConfig struct and NATS field to Config
|
||||
- `/work/apps/archie-core/internal/nats/client.go` — New package: NATS connection management, publish, consume, JetStream setup
|
||||
- `/work/apps/archie-core/internal/store/store.go` — Add ClaimByIssue for targeted task claiming
|
||||
- `/work/apps/archie-core/cmd/archied/main.go` — Wire NATS client startup and inject into Daemon
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/nats"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
@@ -106,6 +107,18 @@ func run() int {
|
||||
}()
|
||||
}
|
||||
|
||||
// NATS client (optional — SQLite flow unchanged when [nats] is absent).
|
||||
var natsClient *nats.Client
|
||||
if cfg.NATS.URL != "" {
|
||||
natsClient, err = nats.Connect(ctx, cfg.NATS.URL, log)
|
||||
if err != nil {
|
||||
log.Error("nats connect failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
defer natsClient.Close()
|
||||
log.Info("nats connected", "url", cfg.NATS.URL)
|
||||
}
|
||||
|
||||
providers := executionProviders(cfg)
|
||||
llm := agentexec.NewRuntime(providers)
|
||||
var agentRunner agentexec.Runner
|
||||
@@ -146,6 +159,7 @@ func run() int {
|
||||
},
|
||||
Log: log,
|
||||
CustomStages: wfeval.Discover,
|
||||
Nats: natsClient,
|
||||
}
|
||||
|
||||
if err := d.Startup(ctx); err != nil {
|
||||
|
||||
@@ -55,6 +55,12 @@ max_tokens = 400000
|
||||
wall_clock = "30m"
|
||||
gate_max_failures = 5
|
||||
|
||||
# NATS JetStream for distributed task queue. Remove or leave commented out
|
||||
# to run in single-process SQLite mode.
|
||||
# [nats]
|
||||
# url = "nats://localhost:4222"
|
||||
# token_env = "NATS_TOKEN"
|
||||
|
||||
[[repos]]
|
||||
owner = "samcharles93"
|
||||
name = "todo"
|
||||
|
||||
@@ -9,20 +9,31 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/minio/highwayhash v1.0.4 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.2 // indirect
|
||||
github.com/nats-io/nkeys v0.4.16 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/crypto v0.53.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
modernc.org/libc v1.74.1 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/nats-io/nats-server/v2 v2.14.3
|
||||
github.com/nats-io/nats.go v1.52.0
|
||||
github.com/samcharles93/ai-sdk v0.1.17
|
||||
github.com/traefik/yaegi v0.16.1
|
||||
)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
@@ -9,14 +11,30 @@ github.com/google/go-github/v78 v78.0.0 h1:b1tytzFE8i//lRVDx5Qh/EdJbtTPtSVD3nF7h
|
||||
github.com/google/go-github/v78 v78.0.0/go.mod h1:Uxvdzy82AkNlC6JQ57se9TqvmgBT7RF0ouHDNg2jd6g=
|
||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
||||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
||||
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/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
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/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
|
||||
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
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.14.3 h1:+xjydPt7rkit67G+04TN0mcO2n+8nveZE7tK/PPV53A=
|
||||
github.com/nats-io/nats-server/v2 v2.14.3/go.mod h1:5IlCtBzfwyzQzPMjmoJ9W2/LKmnJRtNyuOs/OT+NHDY=
|
||||
github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc=
|
||||
github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
@@ -25,14 +43,19 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
|
||||
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
|
||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@@ -224,10 +224,22 @@ type Config struct {
|
||||
Providers map[string]Provider `toml:"providers"`
|
||||
Agent Agent `toml:"agent"`
|
||||
|
||||
Budgets Budgets `toml:"budgets"`
|
||||
Web Web `toml:"web"`
|
||||
Notify Notify `toml:"notify"`
|
||||
Repos []Repo `toml:"repos"`
|
||||
Budgets Budgets `toml:"budgets"`
|
||||
Web Web `toml:"web"`
|
||||
Notify Notify `toml:"notify"`
|
||||
NATS NATSConfig `toml:"nats"`
|
||||
Repos []Repo `toml:"repos"`
|
||||
}
|
||||
|
||||
// NATSConfig configures NATS JetStream for task distribution. When URL is
|
||||
// empty the existing SQLite ClaimNext flow is used unchanged.
|
||||
type NATSConfig struct {
|
||||
// URL is the NATS server address, e.g. "nats://localhost:4222".
|
||||
// Empty means NATS is not configured.
|
||||
URL string `toml:"url"`
|
||||
// TokenEnv optionally names an env var holding a NATS auth token.
|
||||
// Empty means no authentication.
|
||||
TokenEnv string `toml:"token_env"`
|
||||
}
|
||||
|
||||
// Notify configures outbound notifications (n8n webhook → email etc.).
|
||||
|
||||
+138
-22
@@ -15,10 +15,13 @@ import (
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
arnats "github.com/samcharles93/archie-core/internal/nats"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
@@ -34,6 +37,9 @@ type Daemon struct {
|
||||
Bus *events.Bus
|
||||
Workflows workflow.Registry
|
||||
Log *slog.Logger
|
||||
// Nats is the optional NATS client for task distribution. Nil means
|
||||
// NATS is not configured; the existing SQLite ClaimNext flow is used.
|
||||
Nats *arnats.Client
|
||||
// CustomStages discovers a repo's per-repo Yaegi custom stages
|
||||
// (.archie/stages/*.go) from its prepared worktree. Set by the
|
||||
// composition root (cmd/archied) to wfeval.Discover; nil disables
|
||||
@@ -89,6 +95,15 @@ func (d *Daemon) Cycle(ctx context.Context) {
|
||||
d.poll(ctx)
|
||||
d.reconcilePRs(ctx)
|
||||
d.checkWaiting(ctx)
|
||||
if d.Nats != nil {
|
||||
d.drainNATS(ctx)
|
||||
} else {
|
||||
d.drainSQLite(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// drainSQLite processes queued tasks from SQLite (existing behaviour).
|
||||
func (d *Daemon) drainSQLite(ctx context.Context) {
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
@@ -105,37 +120,138 @@ func (d *Daemon) Cycle(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// drainNATS processes tasks from NATS, falling back to SQLite ClaimNext for
|
||||
// requeued tasks (waiting_human approval, retry-parked) that didn't come
|
||||
// through a NATS publish.
|
||||
func (d *Daemon) drainNATS(ctx context.Context) {
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
msg, err := d.Nats.Fetch(ctx)
|
||||
if err != nil {
|
||||
d.Log.Error("nats fetch failed", "err", err)
|
||||
return
|
||||
}
|
||||
if msg != nil {
|
||||
d.processNATSTask(ctx, msg)
|
||||
continue
|
||||
}
|
||||
// Fall back to SQLite for requeued tasks.
|
||||
task, err := d.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
d.Log.Error("sqlite claim failed", "err", err)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
return
|
||||
}
|
||||
d.process(ctx, task)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Daemon) poll(ctx context.Context) {
|
||||
for _, repo := range d.Cfg.Repos {
|
||||
issues := d.pollIssues(ctx, repo)
|
||||
for _, is := range issues {
|
||||
inserted, err := d.Store.EnqueueIssue(ctx,
|
||||
repo.Owner, repo.Name, is.Number, is.Title, is.Body, strings.Join(is.Labels, ","))
|
||||
if err != nil {
|
||||
d.Log.Error("enqueue failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
continue
|
||||
labels := strings.Join(is.Labels, ",")
|
||||
if d.Nats != nil {
|
||||
d.pollNATS(ctx, repo, is, labels)
|
||||
} else {
|
||||
d.pollSQLite(ctx, repo, is, labels)
|
||||
}
|
||||
if inserted {
|
||||
d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title)
|
||||
// Instant acknowledgement: the human sees pickup, not
|
||||
// silence until a PR appears.
|
||||
if ack := d.Cfg.Dispatch.AckReaction; ack != "" {
|
||||
if err := d.Forge.React(ctx, repo.Owner, repo.Name, is.Number, ack); err != nil {
|
||||
d.Log.Warn("ack reaction failed", "issue", is.Number, "err", err)
|
||||
}
|
||||
}
|
||||
d.Forge.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindTaskQueued, Repo: repo.FullName(),
|
||||
Issue: is.Number, Detail: is.Title,
|
||||
})
|
||||
continue
|
||||
}
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pollSQLite enqueues discovered issues directly into SQLite (existing flow).
|
||||
func (d *Daemon) pollSQLite(ctx context.Context, repo config.Repo, is forge.Issue, labels string) {
|
||||
inserted, err := d.Store.EnqueueIssue(ctx,
|
||||
repo.Owner, repo.Name, is.Number, is.Title, is.Body, labels)
|
||||
if err != nil {
|
||||
d.Log.Error("enqueue failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return
|
||||
}
|
||||
if inserted {
|
||||
d.acknowledge(ctx, repo, is)
|
||||
return
|
||||
}
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
}
|
||||
|
||||
// pollNATS publishes discovered issues to NATS (new flow).
|
||||
func (d *Daemon) pollNATS(ctx context.Context, repo config.Repo, is forge.Issue, labels string) {
|
||||
// Read-only existence check — needed for maybeRetryParked.
|
||||
existing, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
|
||||
if err != nil {
|
||||
d.Log.Error("task lookup failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return
|
||||
}
|
||||
if existing != nil {
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
return
|
||||
}
|
||||
if err := d.Nats.PublishTask(ctx, repo.Owner, repo.Name, is.Number, is.Title, is.Body, labels); err != nil {
|
||||
d.Log.Error("nats publish failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return
|
||||
}
|
||||
d.acknowledge(ctx, repo, is)
|
||||
}
|
||||
|
||||
// acknowledge posts the pickup reaction, state label, and queued event.
|
||||
func (d *Daemon) acknowledge(ctx context.Context, repo config.Repo, is forge.Issue) {
|
||||
d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title)
|
||||
if ack := d.Cfg.Dispatch.AckReaction; ack != "" {
|
||||
if err := d.Forge.React(ctx, repo.Owner, repo.Name, is.Number, ack); err != nil {
|
||||
d.Log.Warn("ack reaction failed", "issue", is.Number, "err", err)
|
||||
}
|
||||
}
|
||||
d.Forge.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindTaskQueued, Repo: repo.FullName(),
|
||||
Issue: is.Number, Detail: is.Title,
|
||||
})
|
||||
}
|
||||
|
||||
// processNATSTask decodes a NATS message, writes it to SQLite, claims it,
|
||||
// and runs the workflow. The message is ack'd on terminal (park is a valid
|
||||
// outcome). Nak on transient errors so NATS redelivers.
|
||||
func (d *Daemon) processNATSTask(ctx context.Context, msg jetstream.Msg) {
|
||||
tm, err := arnats.DecodeTask(msg)
|
||||
if err != nil {
|
||||
d.Log.Error("nats decode failed", "err", err)
|
||||
msg.Ack() // bad message, don't retry
|
||||
return
|
||||
}
|
||||
|
||||
inserted, err := d.Store.EnqueueIssue(ctx, tm.Owner, tm.Repo, tm.Number, tm.Title, tm.Body, tm.Labels)
|
||||
if err != nil {
|
||||
d.Log.Error("nats enqueue failed", "err", err)
|
||||
msg.Nak()
|
||||
return
|
||||
}
|
||||
if !inserted {
|
||||
// Already tracked — dedup. Ack and move on.
|
||||
msg.Ack()
|
||||
return
|
||||
}
|
||||
|
||||
task, err := d.Store.ClaimByIssue(ctx, tm.Owner, tm.Repo, tm.Number)
|
||||
if err != nil {
|
||||
d.Log.Error("nats claim failed", "err", err)
|
||||
msg.Nak()
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
// Claimed by another consumer, or task is not queued. Ack.
|
||||
msg.Ack()
|
||||
return
|
||||
}
|
||||
|
||||
d.process(ctx, task)
|
||||
msg.Ack()
|
||||
}
|
||||
|
||||
// pollIssues discovers work for one repo according to cfg.Dispatch.Trigger.
|
||||
func (d *Daemon) pollIssues(ctx context.Context, repo config.Repo) []forge.Issue {
|
||||
switch d.Cfg.Dispatch.Trigger {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
const (
|
||||
streamName = "ARCHIE_TASKS"
|
||||
consumerName = "archie-daemon"
|
||||
msgPrefix = "archie:" // for Nats-Msg-Id dedup
|
||||
dedupWindow = 2 * time.Minute
|
||||
pollTimeout = 2 * time.Second
|
||||
)
|
||||
|
||||
// TaskMessage is the NATS payload for a discovered issue.
|
||||
type TaskMessage struct {
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Number int `json:"number"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
Labels string `json:"labels"` // comma-separated
|
||||
}
|
||||
|
||||
// Client manages the NATS connection and JetStream resources.
|
||||
type Client struct {
|
||||
conn *nats.Conn
|
||||
js jetstream.JetStream
|
||||
stream jetstream.Stream
|
||||
consumer jetstream.Consumer
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// Connect dials url, sets up the JetStream stream and pull consumer.
|
||||
// The stream is created with WorkQueue retention and file storage.
|
||||
func Connect(ctx context.Context, url string, log *slog.Logger) (*Client, error) {
|
||||
nc, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nats connect: %w", err)
|
||||
}
|
||||
js, err := jetstream.New(nc)
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, fmt.Errorf("nats jetstream: %w", err)
|
||||
}
|
||||
|
||||
stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
|
||||
Name: streamName,
|
||||
Subjects: []string{"archie.task.>"},
|
||||
Storage: jetstream.FileStorage,
|
||||
Retention: jetstream.WorkQueuePolicy,
|
||||
Duplicates: dedupWindow,
|
||||
})
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, fmt.Errorf("nats stream: %w", err)
|
||||
}
|
||||
|
||||
consumer, err := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
|
||||
Name: consumerName,
|
||||
Durable: consumerName,
|
||||
FilterSubject: "archie.task.>",
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
MaxDeliver: 3,
|
||||
AckWait: 5 * time.Minute,
|
||||
InactiveThreshold: 24 * time.Hour,
|
||||
})
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, fmt.Errorf("nats consumer: %w", err)
|
||||
}
|
||||
|
||||
return &Client{conn: nc, js: js, stream: stream, consumer: consumer, log: log}, nil
|
||||
}
|
||||
|
||||
// Close drains and closes the NATS connection.
|
||||
func (c *Client) Close() { c.conn.Close() }
|
||||
|
||||
// PublishTask publishes a discovered issue to the appropriate NATS subject.
|
||||
// The Nats-Msg-Id header enables JetStream dedup within the dedup window.
|
||||
func (c *Client) PublishTask(ctx context.Context, owner, repo string, number int, title, body, labels string) error {
|
||||
msg := TaskMessage{
|
||||
Owner: owner,
|
||||
Repo: repo,
|
||||
Number: number,
|
||||
Title: title,
|
||||
Body: body,
|
||||
Labels: labels,
|
||||
}
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
subject := SubjectForLabels(splitLabels(labels))
|
||||
headers := nats.Header{}
|
||||
msgID := fmt.Sprintf("%s%s/%s/%d", msgPrefix, owner, repo, number)
|
||||
headers.Set("Nats-Msg-Id", msgID)
|
||||
|
||||
_, err = c.js.PublishMsg(ctx, &nats.Msg{
|
||||
Subject: subject,
|
||||
Data: data,
|
||||
Header: headers,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("nats publish: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fetch retrieves one task message from the pull consumer.
|
||||
// Returns nil if no message is available within the poll timeout.
|
||||
func (c *Client) Fetch(ctx context.Context) (jetstream.Msg, error) {
|
||||
batch, err := c.consumer.Fetch(1, jetstream.FetchMaxWait(pollTimeout))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nats fetch: %w", err)
|
||||
}
|
||||
for msg := range batch.Messages() {
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
if err := batch.Error(); err != nil {
|
||||
return nil, fmt.Errorf("nats fetch batch: %w", err)
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// DecodeTask decodes a TaskMessage from a NATS message.
|
||||
func DecodeTask(msg jetstream.Msg) (TaskMessage, error) {
|
||||
var tm TaskMessage
|
||||
if err := json.Unmarshal(msg.Data(), &tm); err != nil {
|
||||
return tm, fmt.Errorf("nats decode: %w", err)
|
||||
}
|
||||
return tm, nil
|
||||
}
|
||||
|
||||
// splitLabels splits a comma-separated label string into a slice.
|
||||
func splitLabels(labels string) []string {
|
||||
if labels == "" {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(labels, ",")
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
)
|
||||
|
||||
func startEmbedded(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natssrv.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
jsDir := t.TempDir()
|
||||
if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: jsDir}); err != nil {
|
||||
t.Fatalf("enable jetstream: %v", err)
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
func TestConnectAndPublish(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
ctx := context.Background()
|
||||
client, err := Connect(ctx, url, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
// Publish a task.
|
||||
if err := client.PublishTask(ctx, "sam", "todo", 1, "fix bug", "body text", "bug"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Fetch it back.
|
||||
msg, err := client.Fetch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg == nil {
|
||||
t.Fatal("expected a message")
|
||||
}
|
||||
|
||||
tm, err := DecodeTask(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tm.Owner != "sam" || tm.Repo != "todo" || tm.Number != 1 || tm.Title != "fix bug" || tm.Body != "body text" {
|
||||
t.Fatalf("unexpected task: %+v", tm)
|
||||
}
|
||||
msg.Ack()
|
||||
}
|
||||
|
||||
func TestDedup(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
ctx := context.Background()
|
||||
client, err := Connect(ctx, url, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
// Publish one task and verify it's consumable.
|
||||
if err := client.PublishTask(ctx, "acme", "app", 1, "first", "body", "bug"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
msg, err := client.Fetch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg == nil {
|
||||
t.Fatal("first message not received")
|
||||
}
|
||||
msg.Ack()
|
||||
|
||||
// Second publish with same Msg-Id should be deduped.
|
||||
if err := client.PublishTask(ctx, "acme", "app", 1, "second", "body-v2", "bug"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
msg2, err := client.Fetch(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg2 != nil {
|
||||
msg2.Ack()
|
||||
t.Fatal("expected no second message (dedup)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubjectRouting(t *testing.T) {
|
||||
tests := []struct {
|
||||
labels []string
|
||||
want string
|
||||
}{
|
||||
{[]string{"bug"}, SubjectTaskBug},
|
||||
{[]string{"enhancement"}, SubjectTaskDefault},
|
||||
{[]string{"feature"}, SubjectTaskFeature},
|
||||
{[]string{"bootstrap"}, SubjectTaskBootstrap},
|
||||
{[]string{"bug", "feature"}, SubjectTaskBug}, // first match wins
|
||||
{[]string{"enhancement", "bug"}, SubjectTaskBug},
|
||||
{nil, SubjectTaskDefault},
|
||||
{[]string{}, SubjectTaskDefault},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := SubjectForLabels(tt.labels)
|
||||
if got != tt.want {
|
||||
t.Errorf("SubjectForLabels(%v) = %q, want %q", tt.labels, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Package nats manages the NATS JetStream connection for task distribution.
|
||||
// When configured, the daemon publishes discovered issues to NATS subjects
|
||||
// and consumes them back via a JetStream pull consumer. When not configured
|
||||
// (nil client), the existing SQLite ClaimNext flow is used unchanged.
|
||||
package nats
|
||||
|
||||
import "strings"
|
||||
|
||||
// Task distribution subjects. Each subject encodes the workflow type so
|
||||
// future multi-daemon deployments can filter by workflow.
|
||||
const (
|
||||
SubjectTaskBug = "archie.task.bug"
|
||||
SubjectTaskFeature = "archie.task.feature"
|
||||
SubjectTaskDefault = "archie.task.default"
|
||||
SubjectTaskBootstrap = "archie.task.bootstrap"
|
||||
)
|
||||
|
||||
// SubjectForLabels picks the NATS subject based on issue labels, mirroring
|
||||
// the label-to-workflow mapping in workflow.Route.
|
||||
//
|
||||
// "bug" -> archie.task.bug
|
||||
// "feature" -> archie.task.feature
|
||||
// "bootstrap" -> archie.task.bootstrap
|
||||
// default -> archie.task.default
|
||||
func SubjectForLabels(labels []string) string {
|
||||
for _, l := range labels {
|
||||
switch strings.TrimSpace(l) {
|
||||
case "bug":
|
||||
return SubjectTaskBug
|
||||
case "feature":
|
||||
return SubjectTaskFeature
|
||||
case "bootstrap":
|
||||
return SubjectTaskBootstrap
|
||||
}
|
||||
}
|
||||
return SubjectTaskDefault
|
||||
}
|
||||
@@ -151,6 +151,24 @@ func scanTask(row *sql.Row) (*Task, error) {
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// ClaimByIssue atomically claims a queued task by owner/repo/issue_number.
|
||||
// Returns nil if the task is not in queued state (already claimed, parked,
|
||||
// or terminal). Used by the NATS consumer path where the task was just
|
||||
// inserted via EnqueueIssue and needs an immediate targeted claim.
|
||||
func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*Task, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
UPDATE tasks SET status='running', attempt=attempt+1, updated_at=datetime('now')
|
||||
WHERE owner=? AND repo=? AND issue_number=? AND status='queued'
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status,
|
||||
workflow, stage, branch, plan, notes, pr_number, tokens_used,
|
||||
iterations, attempt, park_reason`, owner, repo, number)
|
||||
t, err := scanTask(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
|
||||
// Transition moves a task to a new status, recording the change.
|
||||
func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
|
||||
Reference in new issue
Block a user