Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae53e83ff3 | ||
|
|
ef84e18f46
|
||
|
|
cf1be16763
|
||
|
|
cc8428643a
|
||
|
|
70251ff3ce | ||
|
|
76dc34a17c
|
||
|
|
a6a0c7c11e
|
||
|
|
f759387eb7
|
||
|
|
21b3591da1
|
||
|
|
e9937ded6b
|
||
|
|
bd1acdd0cc
|
||
|
|
a2c6341544
|
||
|
|
cb3372ac76
|
||
|
|
48e605a545
|
||
|
|
9a4e59f0e0
|
||
|
|
820beda72f
|
||
|
|
c6f70de82d
|
||
|
|
f37f6e2453
|
||
|
|
f7a999e317
|
||
|
|
45494d5b43
|
||
|
|
9ca9545847
|
||
|
|
fa14e7da80
|
||
|
|
12eea5eee3
|
||
|
|
ef623f6c68
|
||
|
|
ee2d19d011
|
||
|
|
53c6b3e413
|
||
|
|
d58125c0bc
|
||
|
|
029198ff61
|
||
|
|
0b08fc5242
|
||
|
|
93609c7ab3
|
||
|
|
461d3dc1f7
|
||
|
|
94f79177a2
|
||
|
|
9169e9db09
|
||
|
|
0d0cd09124
|
||
|
|
0dc5bf9a9b
|
||
|
|
ca107f6977
|
||
|
|
4dad1415e6
|
||
|
|
5bf0a696c6
|
||
|
|
7a8d948fcb
|
||
|
|
d90f7d48d0
|
||
|
|
c5a43f21aa
|
||
|
|
d3fbb0842f
|
||
|
|
dafd426316
|
||
|
|
bec374aa92
|
||
|
|
85b21578d8
|
||
|
|
03c25e7214
|
||
|
|
c30624a59e
|
||
|
|
3cf025fb4a
|
||
|
|
81b784876b
|
||
|
|
6c42f64bfa | ||
|
|
d74216c6b7
|
||
|
|
0b7ce448ab
|
||
|
|
2fb8c09a00
|
||
|
|
0442f1849f
|
||
|
|
cf049797b0
|
||
|
|
18e6fe6af6
|
||
|
|
e8a84d3e41
|
||
|
|
c5f4541cbf
|
||
|
|
369e5038ca
|
||
|
|
66862a1bab
|
||
|
|
25dcdb2d19
|
||
|
|
1830a89898
|
||
|
|
6e718e165a
|
||
|
|
0a37b551f5
|
||
|
|
864b87faa6
|
||
|
|
d55d8580cf
|
||
|
|
63229d1711
|
||
|
|
56044476fc | ||
|
|
796bfd0045
|
||
|
|
abcb72a76a
|
||
|
|
443a7a501b
|
||
|
|
88e86776e8
|
||
|
|
e10bb161fe
|
||
|
|
3b525b7482
|
||
|
|
c2cc10ebfa
|
||
|
|
2f8076d7f8
|
||
|
|
c180a2debb
|
||
|
|
5356745968
|
||
|
|
5b5059615b
|
||
|
|
bca1f3b412 | ||
|
|
3af96fd818
|
||
|
|
1043982529
|
||
|
|
6abfe32540 | ||
|
|
1f9807a99c
|
||
|
|
b2edf1fa8b
|
||
|
|
bb897e76b8 | ||
|
|
07062352b4 | ||
|
|
856c15858b
|
||
|
|
69a46249cc
|
||
|
|
6f10ecc04f
|
||
|
|
d6ca6a72a5
|
||
|
|
243832fee6
|
||
|
|
e8c2c844a8
|
||
|
|
6220387ed6
|
||
|
|
efd3eb2854
|
No files matched your search
@@ -1,7 +1,9 @@
|
||||
# Every 15 minutes, checks how the newest release on the `next` channel is
|
||||
# running on the canary host. If a hard check fails, the canary goes back to
|
||||
# the stable release straight away. If the release stays healthy for 24 hours,
|
||||
# it's promoted to stable. A rollback fails the run, so it shows up red.
|
||||
# Every 15 minutes, checks how the release installed on the canary host is
|
||||
# running, judged over the window counted from its install (-window, default
|
||||
# 24h; CANARY_WINDOW overrides it). If a hard check fails, the canary goes
|
||||
# back to the stable release straight away. If the release stays healthy for
|
||||
# the window, it's promoted to stable. A rollback fails the run, so it shows
|
||||
# up red.
|
||||
name: canary
|
||||
|
||||
on:
|
||||
@@ -33,9 +35,13 @@ jobs:
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
# The self-hosted runner keeps the Go caches on disk between jobs, and
|
||||
# archiving them for the Actions cache takes minutes.
|
||||
cache: false
|
||||
|
||||
- name: Build archied
|
||||
run: go build -o "$RUNNER_TEMP/archied" ./cmd/archied
|
||||
# The check never serves the dashboard, so the build leaves it out.
|
||||
run: go build -tags no_ui -o "$RUNNER_TEMP/archied" ./cmd/archied
|
||||
|
||||
# Promotion retags stable and the images' latest in the registry.
|
||||
- name: Log in to the Gitea registry
|
||||
@@ -44,6 +50,12 @@ jobs:
|
||||
- name: Judge the canary
|
||||
env:
|
||||
ARCHIE_CANARY_TOKEN: ${{ secrets.CANARY_TOKEN }}
|
||||
CANARY_WINDOW: ${{ vars.CANARY_WINDOW }}
|
||||
run: |
|
||||
window_args=()
|
||||
if [ -n "$CANARY_WINDOW" ]; then
|
||||
window_args=(-window "$CANARY_WINDOW")
|
||||
fi
|
||||
"$RUNNER_TEMP/archied" release canary check -dashboard "${{ vars.CANARY_URL }}" \
|
||||
"${window_args[@]}" \
|
||||
-latest git.catlow.cloud/sam/archied,git.catlow.cloud/sam/archie-agent
|
||||
@@ -59,6 +59,9 @@ jobs:
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
# The self-hosted runner keeps the Go caches on disk between jobs, and
|
||||
# archiving them for the Actions cache takes minutes.
|
||||
cache: false
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
@@ -96,13 +99,8 @@ jobs:
|
||||
- name: Pull test container images
|
||||
run: docker pull alpine:3
|
||||
|
||||
# One definition of the gate, in the Taskfile. This step used to inline
|
||||
# its own list, which drifted weaker than `task check`: it ran no
|
||||
# db:check, news:check or ui:check, so a release could ship stale
|
||||
# generated SQL, a stale ui/dist, or release notes that disagree with
|
||||
# CHANGELOG.md. It also ran the dashboard suite here rather than in the
|
||||
# gate, where test:ui runs it with the type check. TEST_FLAGS is the one
|
||||
# difference -- the release runs the whole suite, uncached and including
|
||||
# One definition of the gate, in the Taskfile. TEST_FLAGS is the one
|
||||
# difference: the release runs the whole suite, uncached and including
|
||||
# the Docker-backed tests -short skips. The diff after it asserts
|
||||
# `task fmt` changed nothing.
|
||||
- name: Quality gate
|
||||
@@ -292,6 +290,25 @@ jobs:
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
# The self-hosted runner keeps the Go caches on disk between jobs, and
|
||||
# archiving them for the Actions cache takes minutes.
|
||||
cache: false
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
package_json_file: ui/package.json
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
# archied and archie-ui embed the dashboard.
|
||||
- name: Build the dashboard
|
||||
working-directory: ui
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm run build
|
||||
|
||||
- name: Resolve archied version
|
||||
id: version
|
||||
@@ -401,8 +418,12 @@ jobs:
|
||||
"$api/repos/$repo/releases" >/dev/null
|
||||
echo "published release notes for $tag"
|
||||
|
||||
# The canary host follows the `next` channel. canary.yml then decides
|
||||
# whether this release is promoted to stable or the canary is rolled back.
|
||||
# The canary host follows the `next` channel. canary.yml then judges the
|
||||
# release installed on the canary and decides whether it is promoted to
|
||||
# stable or the canary is rolled back. The start is queue-safe: a release
|
||||
# published while the canary still judges a newer one is queued behind
|
||||
# it and picked up by the next check, so the running window isn't
|
||||
# restarted under a different release.
|
||||
- name: Install the release on the canary
|
||||
if: vars.CANARY_URL != ''
|
||||
env:
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Promotes the release the canary is running right now, without waiting out
|
||||
# the judging window: the canary's signals must show no hard failure and no
|
||||
# relative breach, otherwise the run refuses and fails. Dispatch it with the
|
||||
# version the canary runs (`archied release canary status` shows it).
|
||||
name: promote
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "release the canary is expected to run; must match what it runs"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: promote
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
promote:
|
||||
if: vars.CANARY_URL != ''
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
# The self-hosted runner keeps the Go caches on disk between jobs, and
|
||||
# archiving them for the Actions cache takes minutes.
|
||||
cache: false
|
||||
|
||||
- name: Build archied
|
||||
# The promote never serves the dashboard, so the build leaves it out.
|
||||
run: go build -tags no_ui -o "$RUNNER_TEMP/archied" ./cmd/archied
|
||||
|
||||
# Promotion retags stable and the images' latest in the registry.
|
||||
- name: Log in to the Gitea registry
|
||||
run: echo "${{ secrets.DEPLOY_TOKEN }}" | docker login git.catlow.cloud -u "${{ github.actor }}" --password-stdin
|
||||
|
||||
- name: Promote the canary's release
|
||||
env:
|
||||
ARCHIE_CANARY_TOKEN: ${{ secrets.CANARY_TOKEN }}
|
||||
run: |
|
||||
"$RUNNER_TEMP/archied" release canary promote -dashboard "${{ vars.CANARY_URL }}" \
|
||||
-version "${{ inputs.version }}" \
|
||||
-latest git.catlow.cloud/sam/archied,git.catlow.cloud/sam/archie-agent
|
||||
@@ -20,12 +20,11 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Verify extension namespace support
|
||||
run: |
|
||||
if [ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then
|
||||
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
fi
|
||||
unshare --user --map-root-user --net true
|
||||
# ripgrep and the unprivileged-userns sysctl are provisioned on the host.
|
||||
# A self-hosted runner should not need sudo, and installing a package on
|
||||
# every run is not the gate's job.
|
||||
- name: Verify unprivileged user namespaces
|
||||
run: unshare --user --map-root-user --net true
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
@@ -46,9 +45,6 @@ jobs:
|
||||
go install mvdan.cc/gofumpt@v0.11.0
|
||||
bash tools/proto.sh install
|
||||
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends ripgrep
|
||||
|
||||
- name: Ensure contract baseline ref
|
||||
run: |
|
||||
if ! git show-ref --verify --quiet refs/heads/main; then
|
||||
|
||||
@@ -21,6 +21,17 @@ jobs:
|
||||
cut:
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
# A mirror carries its own Actions secrets. An empty token checks out
|
||||
# fine and fails at the push instead, which reads as a broken release.
|
||||
- name: Check DEPLOY_TOKEN is configured
|
||||
env:
|
||||
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$DEPLOY_TOKEN" ]; then
|
||||
echo "::error::DEPLOY_TOKEN is not set for this repository, so the release cannot push its commit and tag. Set the secret here, or dispatch the release from the Gitea primary."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# DEPLOY_TOKEN rather than the job token: a push made with the job token
|
||||
# doesn't start workflows, and the tag push must start deploy.yml.
|
||||
- name: Checkout
|
||||
@@ -34,6 +45,9 @@ jobs:
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
# The self-hosted runner keeps the Go caches on disk between jobs, and
|
||||
# archiving them for the Actions cache takes minutes.
|
||||
cache: false
|
||||
|
||||
- name: Install Task
|
||||
run: go install github.com/go-task/task/v3/cmd/task@v3.48.0
|
||||
|
||||
+2
-1
@@ -25,7 +25,7 @@ config.production.toml
|
||||
/ui/node_modules/
|
||||
/ui/.vite/
|
||||
/ui/*.tsbuildinfo
|
||||
# ui/dist IS committed: the Go build must not need a Node toolchain.
|
||||
/ui/dist/
|
||||
|
||||
# air live-reload
|
||||
/.air/
|
||||
@@ -47,3 +47,4 @@ __pycache__/
|
||||
|
||||
# Local symlink to the archipelago marketplace repo
|
||||
/archipelago
|
||||
.agents-run/
|
||||
@@ -5,6 +5,61 @@ release's per-component sections are labelled beneath its heading.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.61.1] - 2026-11-07
|
||||
|
||||
### archie-gateway
|
||||
|
||||
- An image or voice attachment that arrives as a link is now checked against what the link serves, the same as an uploaded one. A link whose content is not the declared type, or that cannot be read, is refused.
|
||||
|
||||
### archie-ui
|
||||
|
||||
- A workflow created on the canvas now saves the agent it runs as, so it runs instead of parking with "declares no identity to run as".
|
||||
|
||||
### archie-state-store
|
||||
|
||||
- A workflow that no longer validates after an upgrade (for example it names a step type that was removed) is repaired at startup instead of breaking every workflow. A shipped workflow is restored from this release's copy; a workflow you created is removed and logged, and its earlier revision stays in the resource history. Valid workflows you created or edited are kept.
|
||||
|
||||
## [1.61.0] - 2026-11-07
|
||||
|
||||
### archied
|
||||
|
||||
- A `workflow.handoff` now finishes its run and starts a separate, linked run of the next workflow on the same issue, instead of continuing as another attempt. The task page links each run to the one before and after it; attempts count only retries of one run.
|
||||
|
||||
- A task no longer fails to prepare its worktree with "some refs were not updated" after a tag or branch moves on the forge.
|
||||
|
||||
### archie-ui
|
||||
|
||||
- The task page no longer flashes its loading state on every live update while a task runs.
|
||||
|
||||
### archie-state-store
|
||||
|
||||
- The extension catalogue lists and installs again. Its default signing key has changed; an instance that set its own catalogue signing key in Extension settings keeps using that key.
|
||||
|
||||
## [1.60.0] - 2026-11-02
|
||||
|
||||
### archied
|
||||
|
||||
- Curators can list a repository's open issues and file new ones with the `issue_list` and `issue_create` tools, which reach the forge through the daemon. A curator files only when its definition declares `issue_create`; the shipped self-intake example runs in dry run with `issue_list` for deduplication. Listing every open issue needs the forge extensions from the archipelago release after 1.2.0.
|
||||
|
||||
## [1.59.0] - 2026-11-02
|
||||
|
||||
### archied
|
||||
|
||||
- Forge extensions can open issues: the forge surface gains `CreateIssue` alongside list, comment and close, and the bundled Gitea and GitHub extensions implement it.
|
||||
|
||||
## [1.58.1] - 2026-11-01
|
||||
|
||||
### archied
|
||||
|
||||
- The systemd watchdog now also watches the task intake loop, and its warning names the loop that stalled.
|
||||
- archied no longer restarts about a minute after it starts. Under systemd, the watchdog never saw a poll pass and killed it on every start since 1.56.0.
|
||||
|
||||
## [1.58.0] - 2026-11-01
|
||||
|
||||
### archied
|
||||
|
||||
- Running `install.sh` over an install whose services are already running now restarts them, so they run the new binaries.
|
||||
|
||||
## [1.57.0] - 2026-10-31
|
||||
|
||||
### archied
|
||||
|
||||
@@ -105,7 +105,7 @@ When sources disagree, the higher one wins:
|
||||
- If a fix fails twice, throw the block away and rewrite it simply.
|
||||
- Comments say why, briefly. No migration history, phase names or issue
|
||||
narration in code.
|
||||
- Generated files (`ui/dist/`, protobuf, sqlc) are regenerated and committed
|
||||
- Generated files (protobuf, sqlc) are regenerated and committed
|
||||
with the change that caused them, never hand-edited.
|
||||
|
||||
## Tests
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
# archied — the archie daemon
|
||||
# Run via docker compose alongside NATS.
|
||||
|
||||
FROM node:24-trixie-slim AS dashboard
|
||||
WORKDIR /src/ui
|
||||
RUN corepack enable
|
||||
COPY ui/package.json ui/pnpm-lock.yaml ui/pnpm-workspace.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY ui/ ./
|
||||
RUN pnpm run build
|
||||
|
||||
FROM golang:1.27-trixie AS builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
COPY --from=dashboard /src/ui/dist ./ui/dist
|
||||
ARG GATEWAY_VERSION=dev
|
||||
ARG RUNTIME_VERSION=dev
|
||||
RUN CGO_ENABLED=0 go build \
|
||||
|
||||
+137
-20
@@ -47,6 +47,21 @@ then pushes `main` and the tag atomically with `DEPLOY_TOKEN`. A push made with
|
||||
the job token wouldn't start other workflows, so the user token is what lets
|
||||
the tag start the deploy.
|
||||
|
||||
Every workflow that reaches the registry or the canary reads its credentials
|
||||
from Actions secrets, so a mirror of this repository carries its own set:
|
||||
|
||||
| Name | Kind | Used by |
|
||||
|---|---|---|
|
||||
| `DEPLOY_TOKEN` | secret | release, deploy, canary, promote — the registry push, the tag push, and the package links |
|
||||
| `RELEASE_SIGNING_KEY` | secret | deploy — signs the release statement |
|
||||
| `CANARY_TOKEN` | secret | deploy, canary, promote — the canary's dashboard API |
|
||||
| `CANARY_URL` | variable | deploy, canary, promote — where that dashboard is |
|
||||
| `CANARY_WINDOW` | variable | canary — the judged window; empty means the default |
|
||||
|
||||
A mirror missing them fails at its first login or push; `release.yml` names the
|
||||
missing `DEPLOY_TOKEN` before it checks out, so the run doesn't read as a broken
|
||||
release.
|
||||
|
||||
After a release, pull `main` before committing on it again: CI has added the
|
||||
release commit.
|
||||
|
||||
@@ -78,27 +93,64 @@ release rather than committing the fix on top of a tagged one.
|
||||
|
||||
The canary is the production host, following `next`. Every quarter hour
|
||||
`canary.yml` runs `archied release canary check`, which reads the canary
|
||||
through its dashboard API and judges the release on `next`:
|
||||
through its dashboard API and judges **the release the canary actually runs**,
|
||||
not the moving `next` tag:
|
||||
|
||||
| Signal | Source | Fails when |
|
||||
| --- | --- | --- |
|
||||
| Install outcome | `GET /api/chat/update` | the canary doesn't run the release (the watchdog rolled it back) |
|
||||
| Install outcome | `GET /api/chat/update` | the canary doesn't run the judged release (the watchdog rolled it back) |
|
||||
| Readiness | `GET /health/detailed` | the rollup isn't `ok` |
|
||||
| Alerts | `GET /api/alerts` | an open `action` alert was first raised after the release was issued |
|
||||
| Error log | `GET /api/logs?level=error` | error lines per day exceed `2 × baseline + 10` |
|
||||
| Alerts | `GET /api/alerts` | an open `action` alert was first raised after the release was installed |
|
||||
| Error log | `GET /api/logs?level=error` | error lines per window exceed `2 × baseline + 10` |
|
||||
| Task outcomes | `GET /api/tasks` | the share of finished tasks that parked or died rose more than 10 points |
|
||||
|
||||
- **Control.** The canary's own 24 hours before the release was issued. With
|
||||
- **Control.** The canary's own window before the release was installed. With
|
||||
one production host there's no simultaneous control.
|
||||
- **Window.** 24 hours from issue, one cycle of schedules and traffic. The
|
||||
first 30 minutes are for the install and restart.
|
||||
- **Window.** 24 hours counted from the **install** on the canary, not from
|
||||
the release's issue time: the host records it in `installed.json`
|
||||
(`committed_at`) and reports it as `installed_at` in `GET /api/chat/update`.
|
||||
One cycle of schedules and traffic. The first 30 minutes are for the install
|
||||
and restart. `canary.yml` passes `-window` when the `CANARY_WINDOW` Actions
|
||||
variable is set; the flag defaults to 24h. A host that doesn't report an
|
||||
install time degrades to the release statement's issue time.
|
||||
- **Hard signals** (install, readiness, alerts) roll back at any check after
|
||||
that. **Relative signals** (errors, tasks) are judged at the end of the
|
||||
window.
|
||||
that. **Relative signals** (errors, tasks) are judged against the baseline
|
||||
whenever both windows carry enough data, so a breach rolls the release back
|
||||
even mid-window; a full window with no failure promotes it.
|
||||
- **Too little data skips a signal** rather than failing it: fewer than 5
|
||||
finished tasks in the window, or an error log that reaches back less than an
|
||||
hour into the baseline. A log read that stops short of a window is scaled to
|
||||
a full day from what it covers.
|
||||
a full window from what it covers.
|
||||
|
||||
### Queueing
|
||||
|
||||
`deploy.yml` installs each new release on the canary with
|
||||
`archied release canary start -version V`, which first points the canary back
|
||||
at `next` (clearing any rollback pin) and then installs `V` — unless the
|
||||
canary is already judging a release newer than stable that isn't `V`, in which
|
||||
case `V` is **queued** behind it and the canary keeps running what it judges.
|
||||
`-force` installs regardless. A `check` that promotes (or finds nothing to
|
||||
judge) installs the newer `next` in the same run, so a queue drains one
|
||||
release per promotion.
|
||||
|
||||
### Subcommands
|
||||
|
||||
```
|
||||
archied release canary status read-only: channel/pin, installed release and
|
||||
installed_at, stable/next, window progress, and
|
||||
the verdict the current signals would give
|
||||
archied release canary start point the canary at next and install -version,
|
||||
queued behind a release being judged (-force to
|
||||
override)
|
||||
archied release canary check judge the installed release over -window
|
||||
(default 24h): promote, pick up a newer next,
|
||||
or roll back; a held canary is reported, and a
|
||||
held pin that is no longer installable fails
|
||||
the run red
|
||||
archied release canary promote promote the installed release now if its
|
||||
signals pass; refuses with exit 1 otherwise
|
||||
archied release canary unpin return the canary to next from any pin
|
||||
```
|
||||
|
||||
### Promote
|
||||
|
||||
@@ -106,32 +158,97 @@ A release that passes the window is promoted: `stable` is retagged to the
|
||||
`v<version>` manifest. The signature covers the statement, not the tag, so the
|
||||
retag needs no signing key. The `archied` and `archie-agent` images' `:latest`
|
||||
move to their `:v<version>` first, and the agent image must be the digest the
|
||||
statement pins. Promotion refuses a prerelease and a release issued
|
||||
before the one `stable` names, the same replay rule hosts enforce. The decision
|
||||
and its reasons are in the `canary` run log.
|
||||
statement pins. Promotion refuses a prerelease and a release issued before the
|
||||
one `stable` names, the same replay rule hosts enforce. The decision and its
|
||||
reasons are in the `canary` run log.
|
||||
|
||||
Early promotion is a dispatch away: the **promote** workflow
|
||||
(`.github/workflows/promote.yml`) takes a `version` input and runs
|
||||
`archied release canary promote -version V` on the canary. It judges the
|
||||
release the canary runs — the window doesn't matter for the decision — and
|
||||
refuses (red run) on any hard failure or relative breach with enough data.
|
||||
|
||||
### Roll back
|
||||
|
||||
`stable` stays put, and the run turns red. The canary is pinned to the `stable`
|
||||
version through its update settings and reinstalled through its dashboard.
|
||||
`stable` stays put, and the run turns red. Before the canary is pinned to
|
||||
`stable`, `check` verifies `stable` is actually installable — its statement's
|
||||
zip blob must still be in the release repository and its pinned agent image
|
||||
must still resolve (`releaseupdate.Installable`). If it isn't, the run fails
|
||||
loudly and the canary stays on `next` rather than being stranded on a pin.
|
||||
Otherwise the canary is pinned to the `stable` version through its update
|
||||
settings and reinstalled through its dashboard.
|
||||
|
||||
A release whose migrations differ from `stable`'s can't go back without
|
||||
restoring the pre-update database snapshot, which loses every write since. The
|
||||
canary is held on the failed release instead (pinned to it) and the fix goes
|
||||
forward in the next release. The next release's deploy points the canary back at
|
||||
`next`.
|
||||
forward in the next release. The next release's deploy points the canary back
|
||||
at `next`.
|
||||
|
||||
A pinned canary isn't judged, so a rollback is decided once.
|
||||
A pinned canary isn't judged, so a rollback is decided once — but `check`
|
||||
verifies the pin is still installable every run, so a stranded pin shows red
|
||||
instead of green. `archied release canary unpin` returns the canary to `next`
|
||||
by hand.
|
||||
|
||||
### Configuration
|
||||
|
||||
| Name | Kind | Holds |
|
||||
| --- | --- | --- |
|
||||
| `CANARY_URL` | Actions variable | the canary's dashboard URL; unset disables the canary steps |
|
||||
| `CANARY_TOKEN` | Actions secret | a personal API token on the canary with instance admin |
|
||||
| `DEPLOY_TOKEN` | Actions secret | registry and repository write, for publishing, promoting and the release push |
|
||||
| `CANARY_TOKEN` | Actions secret | an API token bound to a dedicated `service_account` identity on the canary, carrying only the canary grant policy (see below) — never instance admin |
|
||||
| `CANARY_WINDOW` | Actions variable | optional `-window` override for `canary check`; unset is 24h |
|
||||
| `DEPLOY_TOKEN` | Actions secret | registry and repository write, for publishing, promoting and the release push; stays CI-only, promotion runs in CI and never on the host |
|
||||
| `RELEASE_SIGNING_KEY` | Actions secret | the release signing seed |
|
||||
|
||||
#### Setting up `CANARY_TOKEN` once
|
||||
|
||||
`CANARY_TOKEN` is a bearer token for a dedicated service-account identity in
|
||||
the system org whose only grant is the canary policy
|
||||
(`access.CanaryGrantPolicy`): read the signal endpoints (`GET /api/chat/update`,
|
||||
`GET /api/alerts`, `GET /api/logs`, `GET /api/tasks`), read and write the
|
||||
`update-settings` resource, and trigger an update install
|
||||
(`POST /api/chat/update/install`). It carries no other rights, and instance
|
||||
admin is never needed. With an instance-admin token (for example the operator
|
||||
session), run against the canary host:
|
||||
|
||||
```bash
|
||||
# 1. Create the service-account identity in the system org.
|
||||
curl -X POST "$CANARY_URL/api/identities" -H "Authorization: Bearer $ADMIN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"kind":"service_account","display_name":"ci-canary"}'
|
||||
# -> {"id":"<canary-identity-id>", ...}
|
||||
|
||||
# 2. Issue its token (shown exactly once).
|
||||
curl -X POST "$CANARY_URL/api/identities/<canary-identity-id>/tokens" \
|
||||
-H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' \
|
||||
-d '{"name":"ci-canary","days":90}'
|
||||
# -> {"id":"<token-hash>","token":"archie_pat_..."} -- store the token value as the CANARY_TOKEN secret
|
||||
|
||||
# 3. Install the grant pair, scoped to that identity. The policies' org is
|
||||
# pinned to the caller's org (org-sys for the instance admin), so the
|
||||
# bodies need no org field. The permit alone is not enough: service
|
||||
# accounts created through the API are assigned the developer role, so a
|
||||
# matching forbid (installed second) negates everything outside the
|
||||
# permit's surface for that identity.
|
||||
curl -X PUT "$CANARY_URL/api/access/policies" -H "Authorization: Bearer $ADMIN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"id":"org-canary-grant","level":"org","text":"permit(principal, action, resource) when {\n resource.org == principal.org &&\n principal == Archie::Identity::\"<canary-identity-id>\" &&\n (\n (action == Archie::Action::\"read\" && [\"dashboard\", \"task\"].contains(resource.kind)) ||\n (action == Archie::Action::\"read\" && resource == Archie::Object::\"update-settings\") ||\n (action == Archie::Action::\"update\" && resource == Archie::Object::\"update\") ||\n (action == Archie::Action::\"manage_identities\" && resource == Archie::Object::\"update-settings\")\n )\n};"}'
|
||||
```
|
||||
|
||||
The second policy forbids the canary identity from everything the permit does
|
||||
not name, so its developer role cannot widen the grant:
|
||||
|
||||
```bash
|
||||
curl -X PUT "$CANARY_URL/api/access/policies" -H "Authorization: Bearer $ADMIN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"id":"org-canary-grant-forbid","level":"org","text":"forbid(principal, action, resource) when {\\n resource.org == principal.org &&\\n principal == Archie::Identity::\\\"<canary-identity-id>\\\" &&\\n !(\\n (action == Archie::Action::\\\"read\\\" && [\\\"dashboard\\\", \\\"task\\\"].contains(resource.kind)) ||\\n (action == Archie::Action::\\\"read\\\" && resource == Archie::Object::\\\"update-settings\\\") ||\\n (action == Archie::Action::\\\"update\\\" && resource == Archie::Object::\\\"update\\\") ||\\n (action == Archie::Action::\\\"manage_identities\\\" && resource == Archie::Object::\\\"update-settings\\\")\\n )\\n};"}'
|
||||
```
|
||||
|
||||
The policy texts are exactly `access.CanaryGrantPolicy` and
|
||||
`access.CanaryGrantForbidPolicy` from `internal/domain/access/canary.go` with
|
||||
the identity id filled in. The canary needs no other rights: `GET
|
||||
/health/detailed` is unauthenticated, and every other call it makes is covered
|
||||
by the grant pair.
|
||||
|
||||
The runner must reach `CANARY_URL`. Without a canary a release stays on `next`
|
||||
until promoted by hand, under the same refusals:
|
||||
|
||||
|
||||
+14
-12
@@ -100,18 +100,12 @@ tasks:
|
||||
- pnpm install --frozen-lockfile
|
||||
|
||||
ui:
|
||||
desc: Build the dashboard into ui/dist (committed; the Go build embeds it)
|
||||
desc: Build the dashboard into ui/dist, which the Go build embeds
|
||||
dir: ui
|
||||
deps: [ui:deps]
|
||||
cmds:
|
||||
- pnpm run build
|
||||
|
||||
ui:check:
|
||||
desc: Rebuild the dashboard into a temporary directory and reject a stale ui/dist
|
||||
deps: [ui:deps]
|
||||
cmds:
|
||||
- bash tools/uidist.sh check
|
||||
|
||||
test:ui:
|
||||
desc: Test and type-check the dashboard
|
||||
dir: ui
|
||||
@@ -227,8 +221,16 @@ tasks:
|
||||
cmds:
|
||||
- node e2e/run.cjs {{.CLI_ARGS}}
|
||||
|
||||
canary:rehearse:
|
||||
# Local rehearsal only: spins up its own registry, database and host, and
|
||||
# is deliberately absent from check and CI.
|
||||
desc: Rehearse the release-canary loop on a throwaway local host (needs docker; never part of the gate)
|
||||
cmds:
|
||||
- sh tools/canary-rehearse.sh
|
||||
|
||||
build:
|
||||
desc: Build archie services and agent binaries
|
||||
deps: [ui]
|
||||
vars:
|
||||
GATEWAY_VERSION: '{{.GATEWAY_VERSION | default .VERSION}}'
|
||||
RUNTIME_VERSION: '{{.RUNTIME_VERSION | default .VERSION}}'
|
||||
@@ -278,13 +280,14 @@ tasks:
|
||||
desc: Run the full quality gate
|
||||
# Finish mutations before starting parallel checks.
|
||||
cmds:
|
||||
# Node packages land under ui/, which `go test ./...` walks: installing
|
||||
# them while the parallel checks scan the tree makes a lockfile update
|
||||
# delete Go sources mid-walk. Install first, then fan out. Every Go step
|
||||
# embeds ui/dist, so the dashboard is built before any of them.
|
||||
- task: ui
|
||||
- task: fmt
|
||||
- task: proto:check
|
||||
- task: db:check
|
||||
# Node packages land under ui/, which `go test ./...` walks: installing
|
||||
# them while the parallel checks scan the tree makes a lockfile update
|
||||
# delete Go sources mid-walk. Install first, then fan out.
|
||||
- task: ui:deps
|
||||
- task: check:readonly
|
||||
|
||||
check:readonly:
|
||||
@@ -297,7 +300,6 @@ tasks:
|
||||
- task: build
|
||||
- task: test
|
||||
- task: test:ui
|
||||
- task: ui:check
|
||||
|
||||
release:
|
||||
desc: "Turn [Unreleased] into a release, then commit and tag it (RELEASE=major|minor|patch|1.2.3)"
|
||||
|
||||
@@ -156,6 +156,15 @@ _needs a repository._
|
||||
| `push` | bool | Push the branch after committing. |
|
||||
| `reference` | `Fixes` \| `Implements` \| `Refs` | How the commit links to the task issue. |
|
||||
|
||||
Hooks never run. The commit is created by go-git, which ignores `.git/hooks`
|
||||
and `core.hooksPath`, and the agent never runs git, so `pre-commit`,
|
||||
`commit-msg` and `prepare-commit-msg` in the checkout are inert files. A
|
||||
repository whose rules live only in a hook — a formatter, a secret scanner,
|
||||
commitlint, a DCO trailer — gets a commit that does not satisfy them: the run
|
||||
reports success and the pull request fails the check afterwards. Put the same
|
||||
commands in `command.run` or the repository gate, which both run in the task
|
||||
container before this step.
|
||||
|
||||
### `repo.open-pr`
|
||||
|
||||
_needs a repository._
|
||||
|
||||
@@ -94,3 +94,20 @@ target = "127.0.0.1:9090"
|
||||
# releases_key = "base64 public key"
|
||||
# catalogue = "registry.example/owner/archipelago/catalogue"
|
||||
# catalogue_key = "base64 public key"
|
||||
|
||||
# Long-running agent loops that maintain memory, skills and — in dry run —
|
||||
# file follow-up issues from recent runs. Definitions are data: the server
|
||||
# validates them and the gateway applies them live.
|
||||
# [[curators]]
|
||||
# name = "self-intake"
|
||||
# interval = "1h"
|
||||
# tools = ["run_list", "run_events", "issue_list"]
|
||||
# instructions = """
|
||||
# You are archie's self-intake curator, in dry run. Each pass: list recent
|
||||
# task runs with run_list, inspect anything parked or failed with run_events,
|
||||
# check issue_list for each repo so nothing already open is repeated, then
|
||||
# report candidate follow-up issues, each tied to the run that produced it.
|
||||
# Do not create issues.
|
||||
# """
|
||||
# To let it file: add "issue_create" to tools and tell it to file each
|
||||
# candidate (citing the run) instead of only reporting it.
|
||||
@@ -45,3 +45,14 @@ listen = "127.0.0.1:8585"
|
||||
[services.daemon]
|
||||
target = "127.0.0.1:8587"
|
||||
listen = "127.0.0.1:8587"
|
||||
|
||||
# Dry-run self-intake curator (#1770): surveys recent runs and reports
|
||||
# candidate follow-up issues as pass summaries; declares no issue-creating
|
||||
# tool, so it cannot file. Needs a chat model configured to run at all.
|
||||
[[curators]]
|
||||
name = "self-intake"
|
||||
interval = "1h"
|
||||
tools = ["run_list", "run_events", "issue_list"]
|
||||
instructions = """
|
||||
You are archie's self-intake curator, in dry run. Each pass: list recent task runs with run_list, inspect anything parked or failed with run_events, check issue_list for each repo so nothing already open is repeated, then report candidate follow-up issues — concrete, each tied to the run that produced it. Do not create issues; this pass reports only (no issue-creating tool is declared, so it cannot). End your reply with the report.
|
||||
"""
|
||||
@@ -86,7 +86,13 @@
|
||||
"/news/archie/1.55.0/": "/news/1.55.0/",
|
||||
"/news/archie/1.56.0/": "/news/1.56.0/",
|
||||
"/news/archie/1.57.0/": "/news/1.57.0/",
|
||||
"/news/archie/1.58.0/": "/news/1.58.0/",
|
||||
"/news/archie/1.58.1/": "/news/1.58.1/",
|
||||
"/news/archie/1.59.0/": "/news/1.59.0/",
|
||||
"/news/archie/1.6.0/": "/news/1.6.0/",
|
||||
"/news/archie/1.60.0/": "/news/1.60.0/",
|
||||
"/news/archie/1.61.0/": "/news/1.61.0/",
|
||||
"/news/archie/1.61.1/": "/news/1.61.1/",
|
||||
"/news/archie/1.7.0/": "/news/1.7.0/",
|
||||
"/news/archie/1.8.0/": "/news/1.8.0/",
|
||||
"/news/archie/1.9.0/": "/news/1.9.0/",
|
||||
@@ -188,7 +194,13 @@
|
||||
"/news/archied/1.55.0/": "/news/1.55.0/",
|
||||
"/news/archied/1.56.0/": "/news/1.56.0/",
|
||||
"/news/archied/1.57.0/": "/news/1.57.0/",
|
||||
"/news/archied/1.58.0/": "/news/1.58.0/",
|
||||
"/news/archied/1.58.1/": "/news/1.58.1/",
|
||||
"/news/archied/1.59.0/": "/news/1.59.0/",
|
||||
"/news/archied/1.6.0/": "/news/1.6.0/",
|
||||
"/news/archied/1.60.0/": "/news/1.60.0/",
|
||||
"/news/archied/1.61.0/": "/news/1.61.0/",
|
||||
"/news/archied/1.61.1/": "/news/1.61.1/",
|
||||
"/news/archied/1.7.0/": "/news/1.7.0/",
|
||||
"/news/archied/1.8.0/": "/news/1.8.0/",
|
||||
"/news/archied/1.9.0/": "/news/1.9.0/",
|
||||
|
||||
@@ -1,4 +1,34 @@
|
||||
[
|
||||
{
|
||||
"version": "1.61.1",
|
||||
"date": "2026-11-07",
|
||||
"body": "### archie-gateway\n\n- An image or voice attachment that arrives as a link is now checked against what the link serves, the same as an uploaded one. A link whose content is not the declared type, or that cannot be read, is refused.\n\n### archie-ui\n\n- A workflow created on the canvas now saves the agent it runs as, so it runs instead of parking with \"declares no identity to run as\".\n\n### archie-state-store\n\n- A workflow that no longer validates after an upgrade (for example it names a step type that was removed) is repaired at startup instead of breaking every workflow. A shipped workflow is restored from this release's copy; a workflow you created is removed and logged, and its earlier revision stays in the resource history. Valid workflows you created or edited are kept."
|
||||
},
|
||||
{
|
||||
"version": "1.61.0",
|
||||
"date": "2026-11-07",
|
||||
"body": "### archied\n\n- A `workflow.handoff` now finishes its run and starts a separate, linked run of the next workflow on the same issue, instead of continuing as another attempt. The task page links each run to the one before and after it; attempts count only retries of one run.\n\n- A task no longer fails to prepare its worktree with \"some refs were not updated\" after a tag or branch moves on the forge.\n\n### archie-ui\n\n- The task page no longer flashes its loading state on every live update while a task runs.\n\n### archie-state-store\n\n- The extension catalogue lists and installs again. Its default signing key has changed; an instance that set its own catalogue signing key in Extension settings keeps using that key."
|
||||
},
|
||||
{
|
||||
"version": "1.60.0",
|
||||
"date": "2026-11-02",
|
||||
"body": "### archied\n\n- Curators can list a repository's open issues and file new ones with the `issue_list` and `issue_create` tools, which reach the forge through the daemon. A curator files only when its definition declares `issue_create`; the shipped self-intake example runs in dry run with `issue_list` for deduplication. Listing every open issue needs the forge extensions from the archipelago release after 1.2.0."
|
||||
},
|
||||
{
|
||||
"version": "1.59.0",
|
||||
"date": "2026-11-02",
|
||||
"body": "### archied\n\n- Forge extensions can open issues: the forge surface gains `CreateIssue` alongside list, comment and close, and the bundled Gitea and GitHub extensions implement it."
|
||||
},
|
||||
{
|
||||
"version": "1.58.1",
|
||||
"date": "2026-11-01",
|
||||
"body": "### archied\n\n- The systemd watchdog now also watches the task intake loop, and its warning names the loop that stalled.\n- archied no longer restarts about a minute after it starts. Under systemd, the watchdog never saw a poll pass and killed it on every start since 1.56.0."
|
||||
},
|
||||
{
|
||||
"version": "1.58.0",
|
||||
"date": "2026-11-01",
|
||||
"body": "### archied\n\n- Running `install.sh` over an install whose services are already running now restarts them, so they run the new binaries."
|
||||
},
|
||||
{
|
||||
"version": "1.57.0",
|
||||
"date": "2026-10-31",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Self-development loop: archie develops its own codebase
|
||||
|
||||
**Status:** Decided, not yet built (2026-11-03, sam) **Scope:** how archie
|
||||
persistently takes on development of archie-core itself. This file records a
|
||||
desired state, not an implementation or a product: nothing below exists unless
|
||||
the "Built today" section says so. The plan is tracked as epic #1769 with child
|
||||
issues #1770–#1775. This file is a record, not a mechanism: agents only see
|
||||
what is in their context, so verify every claim here against the code before
|
||||
acting on it — where they disagree, the code wins. The boundary below is
|
||||
load-bearing only where it is enforced (the gate, access control, the daemon's
|
||||
git monopoly) and stated in `AGENTS.md`; everywhere else this file is a pointer.
|
||||
|
||||
## Built today
|
||||
|
||||
The machinery the loop will reuse exists: shipped triage/implement/pr-review
|
||||
workflows, the adversarial self-review stage before a PR opens (epic #1348,
|
||||
closed), the prbench judge for review quality with its acceptance bar, canary
|
||||
releases judged on the installed release (releaseupdate), and the curator
|
||||
engine. What does not exist is the loop itself: no self-intake curator, no
|
||||
approved-issue auto-run, no judge for diffs, no outcome distillation, no
|
||||
canary routing specific to self-directed changes.
|
||||
|
||||
## Decision
|
||||
|
||||
Archie improves its own codebase through a closed loop, built in stages:
|
||||
|
||||
1. **Self-intake** (#1770): a curator pass reads run outcomes, step transcripts,
|
||||
gate failures and alerts, dedupes against open issues, and files new issues.
|
||||
Archie files its own work; the maintainer approves priority.
|
||||
2. **Approved-issue loop** (#1771): an approved issue runs the shipped
|
||||
triage/implement workflows end to end — read-only plan, gated build,
|
||||
adversarial self-review, daemon commits and opens a green PR. The maintainer
|
||||
still merges at this stage.
|
||||
3. **Implementation judge** (#1772): the prbench judge pattern scores diffs,
|
||||
calibrated against the maintainer's merge decisions; auto-merge applies only
|
||||
when the gate is green, the review stage is clean, and the judge is above the
|
||||
calibrated bar.
|
||||
4. **Outcome distillation** (#1773): a curator turns merged-run postmortems into
|
||||
proposals for the repo's agent instructions, each added only because it
|
||||
changes a decision; rules that stop changing decisions are removed.
|
||||
5. **Canary** (#1774): self-directed changes ship through the canary release
|
||||
window and are judged on the installed release before promotion. Rollback is
|
||||
a plain revert, because every self-directed change is one gated commit.
|
||||
|
||||
## Boundary
|
||||
|
||||
Enforcement lives in the harness, never in the prompt (#1775). Changes to the
|
||||
commit gate, the invariants in `AGENTS.md`, access control and grant scoping,
|
||||
the daemon-only git path, and webhook HMAC verification may be proposed by
|
||||
archie but are never merged by archie — they require a maintainer merge.
|
||||
Everything else (workflows, curators, memory, docs, the dashboard) is fair game
|
||||
for the loop.
|
||||
|
||||
## Why
|
||||
|
||||
Self-improvement degrades when it relies on the model choosing to follow rules.
|
||||
Gates, scoped grants and the daemon's monopoly on git cannot be argued with; a
|
||||
prompt can. Keeping quality measurable — a judge bar and a canary verdict as
|
||||
numbers, tests guarding the protected seams — is what lets the loop widen
|
||||
without turning the codebase to garbage.
|
||||
|
||||
## Consequences
|
||||
|
||||
- One issue → one small PR applies doubly to self-directed work: past about 100
|
||||
lines or any new mechanism, the change stops and reassesses.
|
||||
- Every self-directed commit cites the issue that authorized it.
|
||||
- Rule proposals from the distillation curator must name the run that triggered
|
||||
them, and `AGENTS.md` stays short enough to read in full every session.
|
||||
@@ -1,9 +1,14 @@
|
||||
// Keyboard and phone access: the task dialog fits and tabs in order, pages
|
||||
// title correctly, the skip link and palette focus main content, and
|
||||
// query-only tab switches keep focus where it is.
|
||||
// query-only tab switches keep focus where it is. Then the audit's two
|
||||
// static sweeps (#1767): no unnamed controls on any route, and every keyboard
|
||||
// focus stop's indicator clears 3:1 against the background behind it.
|
||||
const assert = require('node:assert/strict');
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, settled }) => {
|
||||
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await go('/tasks');
|
||||
await page.getByRole('button', { name: 'Jump to', exact: true }).click();
|
||||
@@ -35,7 +40,7 @@ module.exports = async ({ page, go, shot, settled }) => {
|
||||
assert.ok(await skip.evaluate(el => el === document.activeElement), 'Skip link is not the first keyboard stop');
|
||||
await page.keyboard.press('Enter');
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content');
|
||||
await page.getByRole('button', { name: 'Sections', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Toggle Sidebar', exact: true }).click();
|
||||
await page.getByRole('navigation', { name: 'Sections', exact: true }).getByRole('link', { name: 'Tasks', exact: true }).click();
|
||||
await page.waitForFunction(() => document.activeElement?.id === 'main-content', null, { timeout: 5000 }).catch(() => {});
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content', 'route navigation did not focus main');
|
||||
@@ -50,4 +55,122 @@ module.exports = async ({ page, go, shot, settled }) => {
|
||||
const tab = page.getByRole('tab', { name: /^Map/ });
|
||||
await tab.click();
|
||||
assert.ok(await tab.evaluate(el => el === document.activeElement), 'query-only navigation stole focus');
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
|
||||
// Unnamed controls: every visible input, textarea, select, button or
|
||||
// widget role on each static route needs an accessible name (accname
|
||||
// order: labelledby, label, content, value, placeholder, title).
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
const unnamed = await page.evaluate(() => {
|
||||
const name = (el) => {
|
||||
const by = el.getAttribute('aria-labelledby');
|
||||
if (by) {
|
||||
const t = by.split(/\s+/).map((id) => (document.getElementById(id)?.textContent || '')).join(' ').trim();
|
||||
if (t) return t;
|
||||
}
|
||||
const al = el.getAttribute('aria-label');
|
||||
if (al && al.trim()) return al.trim();
|
||||
if (el.id) {
|
||||
const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
|
||||
if (l && l.textContent.trim()) return l.textContent.trim();
|
||||
}
|
||||
const wrap = el.closest('label');
|
||||
if (wrap && wrap.textContent.trim()) return wrap.textContent.trim();
|
||||
if (el.tagName === 'BUTTON' || el.getAttribute('role') === 'button' || el.getAttribute('role') === 'tab' || el.getAttribute('role') === 'switch') return el.textContent.trim();
|
||||
if (el.tagName === 'INPUT') {
|
||||
const t = (el.getAttribute('type') || 'text').toLowerCase();
|
||||
if (t === 'submit' || t === 'button' || t === 'reset') return el.value.trim();
|
||||
if (t === 'image') return (el.getAttribute('alt') || '').trim();
|
||||
}
|
||||
return (el.getAttribute('placeholder') || el.getAttribute('title') || '').trim();
|
||||
};
|
||||
return [...document.querySelectorAll('button, input, textarea, select, [role="button"], [role="tab"], [role="switch"], [role="checkbox"]')]
|
||||
.filter((el) => el.type !== 'hidden' && el.getClientRects().length)
|
||||
.filter((el) => !name(el))
|
||||
.map((el) => `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}: ${el.outerHTML.slice(0, 120)}`);
|
||||
});
|
||||
for (const u of unnamed) fail(`unnamed control on ${r}: ${u}`);
|
||||
}
|
||||
|
||||
// Focus contrast: Tab through each static route; the focused element's
|
||||
// outline or ring must clear 3:1 against the effective background behind it.
|
||||
const focusProbe = () => page.evaluate(() => {
|
||||
const el = document.activeElement;
|
||||
if (!el || el === document.body || el === document.documentElement) return null;
|
||||
const cs = getComputedStyle(el);
|
||||
const parse = (c) => {
|
||||
c = String(c).trim();
|
||||
let m = c.match(/rgba?\(([^)]+)\)/);
|
||||
if (m) {
|
||||
const p = m[1].split(',').map(Number);
|
||||
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
|
||||
}
|
||||
m = c.match(/^#([0-9a-f]{3,8})$/i);
|
||||
if (m) {
|
||||
let h = m[1];
|
||||
if (h.length === 3 || h.length === 4) h = [...h].map((x) => x + x).join('');
|
||||
const n = parseInt(h.slice(0, 6), 16);
|
||||
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1 };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const bgBehind = (start) => {
|
||||
for (let n = start; n; n = n.parentElement) {
|
||||
const c = parse(getComputedStyle(n).backgroundColor);
|
||||
if (c && c.a > 0) return c;
|
||||
}
|
||||
return { r: 255, g: 255, b: 255, a: 1 };
|
||||
};
|
||||
// An outer ring or outline is painted over the parent's background; an
|
||||
// inset one over the element's own. Score against whichever is higher.
|
||||
const bgSelf = bgBehind(el);
|
||||
const bgParent = bgBehind(el.parentElement);
|
||||
const over = (fg, bg) => {
|
||||
const a = fg.a + bg.a * (1 - fg.a);
|
||||
if (a === 0) return { r: 0, g: 0, b: 0 };
|
||||
return { r: (fg.r * fg.a + bg.r * bg.a * (1 - fg.a)) / a, g: (fg.g * fg.a + bg.g * bg.a * (1 - fg.a)) / a, b: (fg.b * fg.a + bg.b * bg.a * (1 - fg.a)) / a };
|
||||
};
|
||||
const lum = (c) => {
|
||||
const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
|
||||
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
|
||||
};
|
||||
const ratio = (c1, c2) => {
|
||||
const l1 = lum(c1), l2 = lum(c2);
|
||||
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||
};
|
||||
let fg = null;
|
||||
// The ring lives in --tw-ring-shadow on :focus-visible; read the var
|
||||
// directly, then fall back to outline, any shadow layer, focus border.
|
||||
if (el.matches(':focus-visible')) {
|
||||
const m = cs.getPropertyValue('--tw-ring-shadow').match(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/i);
|
||||
if (m) { const c = parse(m[0]); if (c && c.a > 0) fg = c; }
|
||||
}
|
||||
if (!fg && cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) fg = parse(cs.outlineColor === 'currentcolor' ? cs.color : cs.outlineColor);
|
||||
if (!fg && cs.boxShadow && cs.boxShadow !== 'none') {
|
||||
for (const m of cs.boxShadow.matchAll(/rgba?\([^)]+\)|#[0-9a-f]{3,8}\b/gi)) {
|
||||
const c = parse(m[0]);
|
||||
if (c && c.a > 0) { fg = c; break; }
|
||||
}
|
||||
}
|
||||
if (!fg && el.matches(':focus-visible') && parseFloat(cs.borderTopWidth) > 0) {
|
||||
const c = parse(cs.borderTopColor);
|
||||
if (c && c.a > 0) fg = c;
|
||||
}
|
||||
const sig = `${el.tagName}#${el.id}:${(el.textContent || '').trim().slice(0, 30)}`;
|
||||
if (!fg) return { sig, ratio: 0 };
|
||||
return { sig, ratio: Math.max(ratio(over(fg, bgSelf), bgSelf), ratio(over(fg, bgParent), bgParent)) };
|
||||
});
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
let prev = '';
|
||||
for (let i = 0; i < 40; i++) {
|
||||
await page.keyboard.press('Tab');
|
||||
const info = await focusProbe();
|
||||
if (!info || info.sig === prev) break;
|
||||
prev = info.sig;
|
||||
if (info.ratio < 3) fail(`focus indicator under 3:1 on ${r} at ${info.sig} (ratio ${info.ratio.toFixed(2)})`);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
// The dashboard's static routes, read from the router source so a new page is
|
||||
// swept automatically. Parameterised and redirect routes are skipped.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function staticRoutes() {
|
||||
const src = fs.readFileSync(path.join(__dirname, '../../../ui/src/router/index.ts'), 'utf8');
|
||||
const out = [];
|
||||
for (const line of src.split('\n')) {
|
||||
if (/redirect:/.test(line)) continue;
|
||||
const m = line.match(/path: "([^"]*)"/);
|
||||
if (!m || m[1].includes(':')) continue;
|
||||
if (m[1].startsWith('/')) out.push(m[1]);
|
||||
else if (m[1]) out.push('/org/' + m[1]);
|
||||
}
|
||||
return [...new Set(out)];
|
||||
}
|
||||
|
||||
module.exports = { staticRoutes };
|
||||
@@ -1,5 +1,7 @@
|
||||
const assert=require('node:assert/strict');
|
||||
module.exports=async({page,go,shot})=>{
|
||||
module.exports=async({page,go,shot,tolerate})=>{
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.route('**/api/access/policies',async route=>{await new Promise(r=>setTimeout(r,2200));await route.continue()});
|
||||
await go('/access/policies');
|
||||
assert.equal(await page.getByText('No policies yet.',{exact:true}).count(),0);
|
||||
@@ -16,4 +18,19 @@ module.exports=async({page,go,shot})=>{
|
||||
await page.getByRole('button',{name:'Retry runs',exact:true}).click();
|
||||
await page.getByRole('alert').filter({hasText:'Could not load recent runs'}).waitFor({state:'hidden'});
|
||||
await shot('recovered');
|
||||
// A failed list read is an error, never the empty state (#1767): force each
|
||||
// page's list API to 500 and check its empty-state copy stays hidden.
|
||||
const failList = async (pattern,path,emptyTexts,errorSel='[role=alert]')=>{
|
||||
await page.route(pattern,route=>route.fulfill({status:200,contentType:'application/json',body:'unreadable response'}));
|
||||
await go(path);
|
||||
await page.locator(errorSel).first().waitFor();
|
||||
for(const text of emptyTexts) assert.equal(await page.getByText(text,{exact:true}).count(),0,`${path} shows its empty state ("${text}") while the list read fails`);
|
||||
await page.unroute(pattern);
|
||||
};
|
||||
await failList('**/api/tasks*','/tasks',['No tasks yet'],'text=Archie is not responding');
|
||||
await failList('**/api/captures*','/events',['No captures yet']);
|
||||
await failList('**/api/event-types*','/events',['No event types yet']);
|
||||
await failList('**/api/tokens*','/account',['No tokens yet']);
|
||||
await failList('**/api/access/policies*','/org/policies',['No policies yet']);
|
||||
await shot('failed-reads-show-errors');
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
// The topbar org selector: choosing a member org reloads the dashboard into it,
|
||||
// The sidebar org switcher: choosing a member org reloads the dashboard into it,
|
||||
// Tasks and Workflows then show only that org's work, and the API refuses an
|
||||
// org the caller is not a member of.
|
||||
const assert = require('node:assert/strict');
|
||||
@@ -8,11 +8,12 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
|
||||
tolerate(ABSENT);
|
||||
await go('/tasks');
|
||||
await page.getByText('Fix flaky login test').first().waitFor();
|
||||
const picker = page.getByRole('combobox', { name: 'Organisation' });
|
||||
const picker = page.getByRole('button', { name: /^Organisation: / });
|
||||
await picker.waitFor();
|
||||
const offered = await (async () => {
|
||||
await picker.click();
|
||||
const names = await page.getByRole('option').allInnerTexts();
|
||||
await page.getByRole('menuitem').first().waitFor();
|
||||
const names = (await page.getByRole('menuitem').allInnerTexts()).map(t => t.trim().split('\n').pop().trim());
|
||||
await page.keyboard.press('Escape');
|
||||
return names;
|
||||
})();
|
||||
@@ -22,9 +23,9 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
|
||||
await shot('home-org-workflows');
|
||||
|
||||
await picker.click();
|
||||
await Promise.all([page.waitForEvent('load'), page.getByRole('option', { name: 'Beta', exact: true }).click()]);
|
||||
await Promise.all([page.waitForEvent('load'), page.getByRole('menuitem', { name: 'Beta' }).click()]);
|
||||
await settled('/workflows');
|
||||
await page.getByRole('combobox', { name: 'Organisation' }).waitFor();
|
||||
await page.getByRole('button', { name: /^Organisation: / }).waitFor();
|
||||
assert.equal(await page.getByText('Parked', { exact: true }).count(), 0, 'workflow run counts leaked across orgs');
|
||||
await shot('beta-workflows');
|
||||
await go('/tasks');
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// Phone-width sweep of the views the November audit flagged (#1757): at
|
||||
// 390x844 each must fit without horizontal scroll or clipped controls. The
|
||||
// topbar (with its instance badge) is on every page; /account holds the
|
||||
// token form, /org/agents the agent rows and the grants card, /events the
|
||||
// sources table, the event-type rule editor and the mapping editor dialog.
|
||||
const assert = require('node:assert/strict');
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail, settled, tolerate }) => {
|
||||
// The extension catalogue 502 is a stack-environment issue, not this check.
|
||||
tolerate(/extensions\/catalogue/);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
|
||||
const assertNoOverflow = async (label) => {
|
||||
const { scrollWidth, innerWidth } = await page.evaluate(() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
innerWidth: window.innerWidth,
|
||||
}));
|
||||
if (scrollWidth > innerWidth) {
|
||||
fail(`${label} overflows 390px: scrollWidth=${scrollWidth} > innerWidth=${innerWidth}`);
|
||||
}
|
||||
};
|
||||
|
||||
const visit = async (path, label, waitFor) => {
|
||||
await go(path);
|
||||
if (waitFor) await settled(waitFor);
|
||||
await assertNoOverflow(label);
|
||||
await shot(label);
|
||||
};
|
||||
|
||||
await visit('/account', 'account-tokens', 'text=API tokens');
|
||||
await visit('/org/agents', 'org-agents', 'text=Credential grants');
|
||||
|
||||
await go('/events');
|
||||
await settled('[role=tab]');
|
||||
await assertNoOverflow('events');
|
||||
await shot('events');
|
||||
|
||||
// The seeded event type's rule editor (RuleEditor's condition row) opens
|
||||
// from the Edit button on its row.
|
||||
const editType = page.locator('button[aria-label^="Edit "]').first();
|
||||
if (await editType.count()) {
|
||||
await editType.click();
|
||||
await page.getByRole('dialog').first().waitFor();
|
||||
await settled();
|
||||
await assertNoOverflow('event-type rule editor');
|
||||
await shot('rule-editor');
|
||||
await page.keyboard.press('Escape');
|
||||
await settled();
|
||||
}
|
||||
|
||||
// The mappings tab's editor dialog carries the payload tree.
|
||||
await page.getByRole('tab', { name: 'Map' }).click();
|
||||
await settled('text=New mapping');
|
||||
await assertNoOverflow('mappings list');
|
||||
const editMapping = page.locator('button', { hasText: 'Edit' }).first();
|
||||
if (await editMapping.count()) {
|
||||
await editMapping.click();
|
||||
await page.getByRole('dialog').first().waitFor();
|
||||
await settled();
|
||||
await assertNoOverflow('mapping editor dialog');
|
||||
await shot('mapping-editor');
|
||||
}
|
||||
|
||||
// Every static route fits 390px (#1767): horizontal scroll fails.
|
||||
for (const r of staticRoutes()) {
|
||||
await visit(r, `route ${r}`, null);
|
||||
}
|
||||
};
|
||||
+2
-16
@@ -1,24 +1,10 @@
|
||||
// Every static route loads without errors, renders, and shows no text with
|
||||
// stray leading, trailing or doubled spaces.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function routes() {
|
||||
const src = fs.readFileSync(path.join(__dirname, '../../ui/src/router/index.ts'), 'utf8');
|
||||
const out = [];
|
||||
for (const line of src.split('\n')) {
|
||||
if (/redirect:/.test(line)) continue;
|
||||
const m = line.match(/path: "([^"]*)"/);
|
||||
if (!m || m[1].includes(':')) continue;
|
||||
if (m[1].startsWith('/')) out.push(m[1]);
|
||||
else if (m[1]) out.push('/org/' + m[1]);
|
||||
}
|
||||
return [...new Set(out)];
|
||||
}
|
||||
const { staticRoutes } = require('./helpers/routes.cjs');
|
||||
|
||||
module.exports = async ({ page, go, shot, fail }) => {
|
||||
const stray = new Map();
|
||||
for (const r of routes()) {
|
||||
for (const r of staticRoutes()) {
|
||||
await go(r);
|
||||
await shot(r);
|
||||
// Log lines are data, not copy.
|
||||
|
||||
+4
-2
@@ -475,10 +475,12 @@ EOF
|
||||
fi
|
||||
|
||||
# Auto-enable and start the services, the store first so a fresh boot does
|
||||
# not race a dial it depends on.
|
||||
# not race a dial it depends on. Restart rather than start, because a
|
||||
# reinstall over running services would otherwise leave the old binaries
|
||||
# running.
|
||||
if [ "${AUTO_START}" = true ]; then
|
||||
echo "==> Enabling and starting Archie services..."
|
||||
systemctl --user enable --now $INSTANCE_UNITS ||
|
||||
{ systemctl --user enable $INSTANCE_UNITS && systemctl --user restart $INSTANCE_UNITS; } ||
|
||||
echo " Notice: Could not start every service automatically. Check: systemctl --user status ${INSTANCE_UNITS}"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -52,7 +52,7 @@ type HarnessStages struct {
|
||||
Spec agentrun.HarnessSpec
|
||||
}
|
||||
|
||||
func (r HarnessStages) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) {
|
||||
func (r HarnessStages) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
|
||||
spec := r.Spec
|
||||
req.Harness = &spec
|
||||
return r.Runner.Run(ctx, workspace, req, report)
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestHarnessRequiresMCPInitialization(t *testing.T) {
|
||||
if !central {
|
||||
req.CaptureTools = []agentrun.CaptureTool{{Name: "capture_result", Parameters: json.RawMessage(`{"type":"object"}`)}}
|
||||
}
|
||||
result, err := NewHarnessRunner(nil).Run(t.Context(), workspace, req, nil)
|
||||
result, err := NewHarnessRunner(nil).Run(t.Context(), workspace, req, agentrun.Reporter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func newClaudeCodeHarnessOutput() *claudeCodeHarnessOutput {
|
||||
}
|
||||
}
|
||||
|
||||
func (o *claudeCodeHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
|
||||
func (o *claudeCodeHarnessOutput) Line(line []byte, report agentrun.Reporter) {
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
SessionID string `json:"session_id"`
|
||||
@@ -55,7 +55,7 @@ func (o *claudeCodeHarnessOutput) Line(line []byte, report agentrun.ToolCallRepo
|
||||
}
|
||||
}
|
||||
|
||||
func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ agentrun.ToolCallReporter) {
|
||||
func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ agentrun.Reporter) {
|
||||
var message struct {
|
||||
ID string `json:"id"`
|
||||
Usage json.RawMessage `json:"usage"`
|
||||
@@ -79,7 +79,7 @@ func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ agentrun.Tool
|
||||
}
|
||||
}
|
||||
|
||||
func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.ToolCallReporter) {
|
||||
func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.Reporter) {
|
||||
var message struct {
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
@@ -100,12 +100,10 @@ func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.Tool
|
||||
continue
|
||||
}
|
||||
delete(o.pending, block.ToolUseID)
|
||||
if report != nil {
|
||||
report(agentrun.ToolCallReport{
|
||||
Tool: tool, Detail: ClipToolCallDetail(claudeResultContent(block.Content)),
|
||||
Failed: block.IsError,
|
||||
})
|
||||
}
|
||||
report.ReportToolCall(agentrun.ToolCallReport{
|
||||
Tool: tool, Detail: ClipToolCallDetail(claudeResultContent(block.Content)),
|
||||
Failed: block.IsError,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ type codexHarnessOutput struct {
|
||||
usage agentrun.Usage
|
||||
}
|
||||
|
||||
func (o *codexHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
|
||||
func (o *codexHarnessOutput) Line(line []byte, report agentrun.Reporter) {
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
ThreadID string `json:"thread_id"`
|
||||
@@ -43,8 +43,8 @@ func (o *codexHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter)
|
||||
})
|
||||
}
|
||||
case "item.completed":
|
||||
if call, ok := event.Item.report(); ok && report != nil {
|
||||
report(call)
|
||||
if call, ok := event.Item.report(); ok {
|
||||
report.ReportToolCall(call)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ func newCopilotHarnessOutput() *copilotHarnessOutput {
|
||||
return &copilotHarnessOutput{pending: make(map[string]string)}
|
||||
}
|
||||
|
||||
func (o *copilotHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
|
||||
func (o *copilotHarnessOutput) Line(line []byte, report agentrun.Reporter) {
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
SessionID string `json:"sessionId"`
|
||||
@@ -52,9 +52,7 @@ func (o *copilotHarnessOutput) Line(line []byte, report agentrun.ToolCallReporte
|
||||
return
|
||||
}
|
||||
delete(o.pending, event.Data.ToolCallID)
|
||||
if report != nil {
|
||||
report(agentrun.ToolCallReport{Tool: tool, Detail: ClipToolCallDetail(event.Data.Result.Content), Failed: !event.Data.Success})
|
||||
}
|
||||
report.ReportToolCall(agentrun.ToolCallReport{Tool: tool, Detail: ClipToolCallDetail(event.Data.Result.Content), Failed: !event.Data.Success})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ type piHarnessOutput struct {
|
||||
usage agentrun.Usage
|
||||
}
|
||||
|
||||
func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
|
||||
func (o *piHarnessOutput) Line(line []byte, report agentrun.Reporter) {
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
@@ -49,7 +49,7 @@ func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
|
||||
o.usage = addUsage(o.usage, usageFromFields(u.Input, u.Output, u.CacheRead, u.CacheWrite))
|
||||
}
|
||||
case "tool_execution_end":
|
||||
if event.ToolName == "" || report == nil {
|
||||
if event.ToolName == "" {
|
||||
return
|
||||
}
|
||||
texts := make([]string, 0, len(event.Result.Content))
|
||||
@@ -58,7 +58,7 @@ func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
|
||||
texts = append(texts, block.Text)
|
||||
}
|
||||
}
|
||||
report(agentrun.ToolCallReport{Tool: event.ToolName, Detail: ClipToolCallDetail(strings.Join(texts, "\n")), Failed: event.IsError})
|
||||
report.ReportToolCall(agentrun.ToolCallReport{Tool: event.ToolName, Detail: ClipToolCallDetail(strings.Join(texts, "\n")), Failed: event.IsError})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ const (
|
||||
// knows its CLI's stream format; it reports tool calls as they complete and
|
||||
// the session to resume.
|
||||
type HarnessOutput interface {
|
||||
Line(line []byte, report agentrun.ToolCallReporter)
|
||||
Line(line []byte, report agentrun.Reporter)
|
||||
SessionID() string
|
||||
Usage() agentrun.Usage
|
||||
}
|
||||
@@ -67,7 +67,7 @@ func NewHarnessRunner(newOutput func() HarnessOutput) *HarnessRunner {
|
||||
return &HarnessRunner{newOutput: newOutput}
|
||||
}
|
||||
|
||||
func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) {
|
||||
func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
|
||||
if err := validateHarness(req); err != nil {
|
||||
return agentrun.Result{}, err
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (r *HarnessRunner) run(ctx context.Context, workspace string, req agentrun.Request, mcpConfig string, report agentrun.ToolCallReporter) (agentrun.Result, error) {
|
||||
func (r *HarnessRunner) run(ctx context.Context, workspace string, req agentrun.Request, mcpConfig string, report agentrun.Reporter) (agentrun.Result, error) {
|
||||
res := agentrun.Result{Version: agentrun.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, Stage: req.Stage}
|
||||
before, err := snapshotRepo(workspace)
|
||||
if err != nil {
|
||||
@@ -244,7 +244,7 @@ func resumeVerb(h *agentrun.HarnessSpec, sessionID string) []string {
|
||||
// invoke runs one harness invocation in its own process group, feeding
|
||||
// stdout to out line by line. Cancelling ctx kills the whole group, so a
|
||||
// CLI's children cannot outlive the step.
|
||||
func invoke(ctx context.Context, workspace string, h *agentrun.HarnessSpec, argv []string, out HarnessOutput, report agentrun.ToolCallReporter) error {
|
||||
func invoke(ctx context.Context, workspace string, h *agentrun.HarnessSpec, argv []string, out HarnessOutput, report agentrun.Reporter) error {
|
||||
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
|
||||
cmd.Dir = workspace
|
||||
cmd.WaitDelay = killGrace
|
||||
@@ -467,9 +467,9 @@ func policyViolation(before, after repoState, changes []string, req agentrun.Req
|
||||
|
||||
type silentOutput struct{}
|
||||
|
||||
func (silentOutput) Line([]byte, agentrun.ToolCallReporter) {}
|
||||
func (silentOutput) SessionID() string { return "" }
|
||||
func (silentOutput) Usage() agentrun.Usage { return agentrun.Usage{} }
|
||||
func (silentOutput) Line([]byte, agentrun.Reporter) {}
|
||||
func (silentOutput) SessionID() string { return "" }
|
||||
func (silentOutput) Usage() agentrun.Usage { return agentrun.Usage{} }
|
||||
|
||||
// tailBuffer keeps the last stderrTailBytes written to it.
|
||||
type tailBuffer struct{ buf bytes.Buffer }
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestHarnessLiveOutput(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
user = "65534"
|
||||
}
|
||||
err := invoke(t.Context(), "/tmp", &agentrun.HarnessSpec{User: user}, []string{"sh", "-c", `printf '%s\n' '{"type":"thread.started","thread_id":"live-thread"}'; printf '%s\n' 'live diagnostic' >&2`}, adapter, nil)
|
||||
err := invoke(t.Context(), "/tmp", &agentrun.HarnessSpec{User: user}, []string{"sh", "-c", `printf '%s\n' '{"type":"thread.started","thread_id":"live-thread"}'; printf '%s\n' 'live diagnostic' >&2`}, adapter, agentrun.Reporter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func NewLoopRunner(
|
||||
// work on the chat workspace and bypass ReadOnly and ProtectPaths.
|
||||
const workspaceToolset = "workspace"
|
||||
|
||||
func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) {
|
||||
func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return agentrun.Result{}, err
|
||||
}
|
||||
@@ -67,12 +67,18 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
|
||||
notes := &memoryNotes{initial: req.Notes}
|
||||
captures := make(map[string][]json.RawMessage)
|
||||
toolOpts := r.Limits.Options(workspaceToolset)
|
||||
toolOpts.OnToolCall = report
|
||||
toolOpts.OnToolCall = report.ToolCall
|
||||
centralTools, err := BuildToolSet(r.tools, toolOpts)
|
||||
if err != nil {
|
||||
return agentrun.Result{}, fmt.Errorf("build central tool set: %w", err)
|
||||
}
|
||||
captureTools := captureToolSet(req.CaptureTools, captures)
|
||||
var modelHooks []core.ModelHook
|
||||
var toolHooks []core.ToolHook
|
||||
if report.Transcript != nil {
|
||||
recorder := newTranscript(report.Transcript)
|
||||
modelHooks, toolHooks = []core.ModelHook{recorder}, []core.ToolHook{recorder}
|
||||
}
|
||||
res, err := r.run(ctx, agentloop.Config{
|
||||
Runtime: r.runtime,
|
||||
ModelRef: req.Model,
|
||||
@@ -101,7 +107,9 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
|
||||
allowedTools(centralTools, r.AllowTools),
|
||||
captureTools,
|
||||
),
|
||||
Logger: r.logger(req),
|
||||
ModelHooks: modelHooks,
|
||||
ToolHooks: toolHooks,
|
||||
Logger: r.logger(req),
|
||||
})
|
||||
result := resultFromRun(req, res, notes.appended, captures)
|
||||
if cause := context.Cause(ctx); cause != nil {
|
||||
|
||||
@@ -74,7 +74,7 @@ type ToolSetOptions struct {
|
||||
// OnToolCall, when non-nil, is notified once per completed tool call.
|
||||
// LoopRunner populates it so a workflow stage can surface tool activity on
|
||||
// the task timeline. Nil means no one is listening.
|
||||
OnToolCall agentrun.ToolCallReporter
|
||||
OnToolCall func(agentrun.ToolCallReport)
|
||||
}
|
||||
|
||||
// reportToolCallCompletion notifies opts.OnToolCall, if set, of one
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package modelloop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
// transcriptFieldLimit caps each recorded text field, in bytes.
|
||||
const transcriptFieldLimit = 32 << 10
|
||||
|
||||
// compactionPrefix starts the instruction agentloop sends to summarise the
|
||||
// history, which marks a model call as a compaction rather than a step.
|
||||
const compactionPrefix = "Compact the conversation history above"
|
||||
|
||||
// transcript records one agent run's conversation through agentloop's model
|
||||
// and tool hooks. Tool hooks run concurrently, so entries are numbered and
|
||||
// reported under one lock to keep their order.
|
||||
type transcript struct {
|
||||
report func(agentrun.TranscriptEntry)
|
||||
|
||||
mu sync.Mutex
|
||||
seq int
|
||||
prompted bool
|
||||
lastUser string
|
||||
started map[string]time.Time
|
||||
}
|
||||
|
||||
func newTranscript(report func(agentrun.TranscriptEntry)) *transcript {
|
||||
return &transcript{report: report, started: map[string]time.Time{}}
|
||||
}
|
||||
|
||||
func (t *transcript) add(entry agentrun.TranscriptEntry) {
|
||||
t.seq++
|
||||
entry.Seq = t.seq
|
||||
t.report(entry)
|
||||
}
|
||||
|
||||
func (t *transcript) ModelCallStarted(context.Context, chat.Request) {}
|
||||
|
||||
func (t *transcript) ModelCallFinished(_ context.Context, req chat.Request, resp *chat.Response, err error, latency time.Duration, usage *chat.Usage) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
entry := agentrun.TranscriptEntry{Kind: agentrun.TranscriptModel, LatencyMS: latency.Milliseconds(), Usage: transcriptUsage(usage)}
|
||||
if isCompaction(req) {
|
||||
entry.Kind = agentrun.TranscriptCompaction
|
||||
} else {
|
||||
t.recordInput(req.Messages)
|
||||
}
|
||||
if err != nil {
|
||||
entry.Error = clip(err.Error(), nil)
|
||||
}
|
||||
if resp != nil {
|
||||
entry.Text = clip(resp.Content, &entry.TextBytes)
|
||||
entry.Reasoning = clip(reasoning(resp.Parts), &entry.ReasoningBytes)
|
||||
entry.FinishReason = resp.FinishReason
|
||||
for _, call := range resp.ToolCalls {
|
||||
recorded := agentrun.TranscriptToolCall{ID: call.ID, Name: call.Name}
|
||||
recorded.Args = clipArgs(call.Arguments, &recorded.ArgsBytes)
|
||||
entry.ToolCalls = append(entry.ToolCalls, recorded)
|
||||
}
|
||||
}
|
||||
t.add(entry)
|
||||
}
|
||||
|
||||
// recordInput records the prompt on the first call, and after that each user
|
||||
// message the loop appended since the model last answered: gate feedback,
|
||||
// recovery nudges. Assistant and tool messages are recorded from the response
|
||||
// and the tool hooks instead.
|
||||
func (t *transcript) recordInput(messages []chat.Message) {
|
||||
if !t.prompted {
|
||||
t.prompted = true
|
||||
for _, message := range messages {
|
||||
t.recordMessage(message)
|
||||
}
|
||||
return
|
||||
}
|
||||
start := len(messages)
|
||||
for start > 0 && messages[start-1].Role == chat.RoleUser {
|
||||
start--
|
||||
}
|
||||
for _, message := range messages[start:] {
|
||||
if message.Content != t.lastUser {
|
||||
t.recordMessage(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *transcript) recordMessage(message chat.Message) {
|
||||
kind := agentrun.TranscriptUser
|
||||
switch message.Role {
|
||||
case chat.RoleSystem:
|
||||
kind = agentrun.TranscriptSystem
|
||||
case chat.RoleUser:
|
||||
t.lastUser = message.Content
|
||||
default:
|
||||
return
|
||||
}
|
||||
entry := agentrun.TranscriptEntry{Kind: kind}
|
||||
entry.Text = clip(message.Content, &entry.TextBytes)
|
||||
t.add(entry)
|
||||
}
|
||||
|
||||
func (t *transcript) BeforeToolExecute(_ context.Context, call *core.ToolCall) (*core.Skip, error) {
|
||||
t.mu.Lock()
|
||||
t.started[call.ToolCallID] = time.Now()
|
||||
t.mu.Unlock()
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (t *transcript) AfterToolExecute(_ context.Context, call core.ToolCall, result *core.ToolResult) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
entry := agentrun.TranscriptEntry{Kind: agentrun.TranscriptTool, CallID: call.ToolCallID, Tool: call.ToolName}
|
||||
if started, ok := t.started[call.ToolCallID]; ok {
|
||||
entry.LatencyMS = time.Since(started).Milliseconds()
|
||||
delete(t.started, call.ToolCallID)
|
||||
}
|
||||
entry.Args = clipArgs(call.Input, &entry.ArgsBytes)
|
||||
entry.Output = clip(result.Output, &entry.OutputBytes)
|
||||
entry.Error = clip(result.Error, nil)
|
||||
t.add(entry)
|
||||
}
|
||||
|
||||
func reasoning(parts chat.Parts) string {
|
||||
var texts []string
|
||||
for _, part := range parts {
|
||||
if thought, ok := part.(chat.ReasoningPart); ok && thought.Text != "" {
|
||||
texts = append(texts, thought.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(texts, "\n\n")
|
||||
}
|
||||
|
||||
func isCompaction(req chat.Request) bool {
|
||||
n := len(req.Messages)
|
||||
return n > 0 && req.Messages[n-1].Role == chat.RoleUser && strings.HasPrefix(req.Messages[n-1].Content, compactionPrefix)
|
||||
}
|
||||
|
||||
func transcriptUsage(usage *chat.Usage) *agentrun.Usage {
|
||||
if usage == nil {
|
||||
return nil
|
||||
}
|
||||
return &agentrun.Usage{
|
||||
PromptTokens: usage.PromptTokens,
|
||||
CompletionTokens: usage.CompletionTokens,
|
||||
TotalTokens: usage.TotalTokens,
|
||||
CachedTokens: usage.CachedTokens,
|
||||
CacheCreationTokens: usage.CacheCreationTokens,
|
||||
}
|
||||
}
|
||||
|
||||
// clipArgs redacts tool arguments by key when they are JSON, then clips them.
|
||||
func clipArgs(args string, full *int) string {
|
||||
if json.Valid([]byte(args)) {
|
||||
if redacted, err := webhookguard.RedactPayload([]byte(args)); err == nil {
|
||||
args = string(redacted)
|
||||
}
|
||||
}
|
||||
return clip(args, full)
|
||||
}
|
||||
|
||||
// clip redacts secret-shaped spans and cuts text to transcriptFieldLimit on a
|
||||
// rune boundary, storing the original size in full when it cuts.
|
||||
func clip(text string, full *int) string {
|
||||
text = webhookguard.RedactText(text)
|
||||
if len(text) <= transcriptFieldLimit {
|
||||
return text
|
||||
}
|
||||
if full != nil {
|
||||
*full = len(text)
|
||||
}
|
||||
cut := transcriptFieldLimit
|
||||
for cut > 0 && !utf8.RuneStart(text[cut]) {
|
||||
cut--
|
||||
}
|
||||
return text[:cut]
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package modelloop
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
)
|
||||
|
||||
func TestTranscriptToolEntryRedactsAndClips(t *testing.T) {
|
||||
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhcmNoaWUifQ.c2lnbmF0dXJlc2lnbmF0dXJl"
|
||||
const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEow\n-----END RSA PRIVATE KEY-----"
|
||||
long := strings.Repeat("x", transcriptFieldLimit+10)
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
output string
|
||||
wantArgs string
|
||||
wantOutput string
|
||||
wantBytes int
|
||||
}{
|
||||
{
|
||||
name: "secret key in arguments, token inside output",
|
||||
input: `{"path":"a.txt","api_key":"plain-value"}`,
|
||||
output: "curl -H 'Authorization: Bearer " + jwt + "' done",
|
||||
wantArgs: `{"api_key":"[redacted]","path":"a.txt"}`,
|
||||
wantOutput: "curl -H 'Authorization: Bearer [redacted]' done",
|
||||
},
|
||||
{
|
||||
name: "private key block inside output",
|
||||
input: `{}`,
|
||||
output: "before\n" + pem + "\nafter",
|
||||
wantArgs: `{}`,
|
||||
wantOutput: "before\n[redacted]\nafter",
|
||||
},
|
||||
{
|
||||
name: "oversized output keeps its full size",
|
||||
input: `{}`,
|
||||
output: long,
|
||||
wantArgs: `{}`,
|
||||
wantOutput: long[:transcriptFieldLimit],
|
||||
wantBytes: len(long),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var got []agentrun.TranscriptEntry
|
||||
recorder := newTranscript(func(entry agentrun.TranscriptEntry) { got = append(got, entry) })
|
||||
call := core.ToolCall{ToolCallID: "c1", ToolName: "shell", Input: tt.input}
|
||||
if _, err := recorder.BeforeToolExecute(t.Context(), &call); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recorder.AfterToolExecute(t.Context(), call, &core.ToolResult{Output: tt.output})
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("entries = %d, want 1", len(got))
|
||||
}
|
||||
entry := got[0]
|
||||
if entry.Args != tt.wantArgs {
|
||||
t.Errorf("args = %q, want %q", entry.Args, tt.wantArgs)
|
||||
}
|
||||
if entry.Output != tt.wantOutput {
|
||||
t.Errorf("output = %q, want %q", entry.Output, tt.wantOutput)
|
||||
}
|
||||
if entry.OutputBytes != tt.wantBytes {
|
||||
t.Errorf("output bytes = %d, want %d", entry.OutputBytes, tt.wantBytes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func readProjectMemory(path string) (string, error) {
|
||||
return "Project memory from earlier sessions:\n" + strings.Join(entries, "\n"), nil
|
||||
}
|
||||
|
||||
func (r persistentRunner) Run(ctx context.Context, workspace string, request agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) {
|
||||
func (r persistentRunner) Run(ctx context.Context, workspace string, request agentrun.Request, report agentrun.Reporter) (agentrun.Result, error) {
|
||||
if !r.enabled {
|
||||
return r.Runner.Run(ctx, workspace, request, report)
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/extension"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/issuerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/logrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
|
||||
@@ -587,9 +588,30 @@ func (b *boot) registerNATSRPC() error {
|
||||
return err
|
||||
}
|
||||
b.addCleanup(unsubscribeTaskActions)
|
||||
|
||||
unsubscribeIssues, err := (&issuerpc.Server{Forge: b.issueForge, Allowed: b.managedRepository, Log: log}).Register(coreConn)
|
||||
if err != nil {
|
||||
log.Error("issue RPC register failed", "err", err)
|
||||
return err
|
||||
}
|
||||
b.addCleanup(unsubscribeIssues)
|
||||
return nil
|
||||
}
|
||||
|
||||
// issueForge is the instance forge, or nil while none is configured.
|
||||
func (b *boot) issueForge() forge.IssueForge {
|
||||
if b.forgeClient == nil {
|
||||
return nil
|
||||
}
|
||||
return b.forgeClient
|
||||
}
|
||||
|
||||
// managedRepository refuses a repository the organisation has not added.
|
||||
func (b *boot) managedRepository(ctx context.Context, owner, repo string) error {
|
||||
_, err := b.repositoryBinding(ctx, owner, repo)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *boot) buildDaemon() {
|
||||
log := b.log
|
||||
b.d = &daemon.Daemon{
|
||||
|
||||
@@ -19,8 +19,11 @@ const releaseUsage = `usage: archied release <command>
|
||||
keygen -seed FILE write a new signing key's seed to FILE and print its public key
|
||||
publish sign a release and push it to a release source's next channel
|
||||
promote -version V point stable at a published release by hand
|
||||
canary start point the canary at next and install a release on it
|
||||
canary check judge the release on next and promote it or roll the canary back`
|
||||
canary status show the canary's channel, installed release, window and verdict (read-only)
|
||||
canary start point the canary at next and install a release on it, queued behind one being judged
|
||||
canary check judge the release the canary runs: promote it, pick up a newer next, or roll back
|
||||
canary promote promote the release the canary runs now, if its signals pass
|
||||
canary unpin return the canary to the next channel from any pin`
|
||||
|
||||
// RunRelease is the publisher's side of a release source: it makes the key
|
||||
// a source signs with and pushes signed releases to it.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
@@ -8,6 +9,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"oras.land/oras-go/v2/errdef"
|
||||
@@ -25,136 +27,630 @@ const canaryInstallWait = 20 * time.Minute
|
||||
const migrationsDir = "internal/infrastructure/postgres/migrations"
|
||||
|
||||
func runReleaseCanary(args []string, out, stderr io.Writer) int {
|
||||
if len(args) == 0 || (args[0] != "start" && args[0] != "check") {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprintln(stderr, releaseUsage)
|
||||
return 2
|
||||
}
|
||||
flags := flag.NewFlagSet("release canary "+args[0], flag.ContinueOnError)
|
||||
switch args[0] {
|
||||
case "status":
|
||||
return runCanaryStatus(args[1:], out, stderr)
|
||||
case "start":
|
||||
return runCanaryStart(args[1:], out, stderr)
|
||||
case "check":
|
||||
return runCanaryCheck(args[1:], out, stderr)
|
||||
case "promote":
|
||||
return runCanaryPromote(args[1:], out, stderr)
|
||||
case "unpin":
|
||||
return runCanaryUnpin(args[1:], out, stderr)
|
||||
default:
|
||||
fmt.Fprintln(stderr, releaseUsage)
|
||||
return 2
|
||||
}
|
||||
}
|
||||
|
||||
// addCanaryFlags registers the flags every canary subcommand takes.
|
||||
func addCanaryFlags(flags *flag.FlagSet) (dashboardURL, tokenEnv *string) {
|
||||
dashboardURL = flags.String("dashboard", "", "canary dashboard URL")
|
||||
tokenEnv = flags.String("token-env", "ARCHIE_CANARY_TOKEN", "environment variable holding a dashboard API token for the canary")
|
||||
return dashboardURL, tokenEnv
|
||||
}
|
||||
|
||||
// addSourceFlags registers the flags naming the release source.
|
||||
func addSourceFlags(flags *flag.FlagSet) (reference, key *string) {
|
||||
reference = flags.String("source", "", "OCI repository releases are published to; blank is the official releases")
|
||||
key = flags.String("key", "", "base64 ed25519 public key the source signs with")
|
||||
return reference, key
|
||||
}
|
||||
|
||||
func canaryDashboard(url, tokenEnv string) (releaseupdate.CanaryDashboard, error) {
|
||||
if url == "" {
|
||||
return releaseupdate.CanaryDashboard{}, errors.New("-dashboard is required")
|
||||
}
|
||||
return releaseupdate.CanaryDashboard{URL: url, Token: os.Getenv(tokenEnv)}, nil
|
||||
}
|
||||
|
||||
func canarySource(reference, key string) (distribution.Source, error) {
|
||||
return distribution.Parse(reference, key, distribution.DefaultReleases())
|
||||
}
|
||||
|
||||
// fetchChannel fetches a channel tag; found is false when the channel has no
|
||||
// release yet.
|
||||
func fetchChannel(ctx context.Context, source distribution.Source, tag string) (release releaseupdate.Release, found bool, err error) {
|
||||
release, err = releaseupdate.Fetch(ctx, source, tag)
|
||||
if errors.Is(err, errdef.ErrNotFound) {
|
||||
return releaseupdate.Release{}, false, nil
|
||||
}
|
||||
return release, err == nil, err
|
||||
}
|
||||
|
||||
// publishedChannels are the releases the source currently publishes.
|
||||
type publishedChannels struct {
|
||||
next, stable releaseupdate.Release
|
||||
hasNext, hasStable bool
|
||||
}
|
||||
|
||||
func fetchChannels(ctx context.Context, source distribution.Source) (publishedChannels, error) {
|
||||
var channels publishedChannels
|
||||
var err error
|
||||
if channels.next, channels.hasNext, err = fetchChannel(ctx, source, "next"); err != nil {
|
||||
return channels, err
|
||||
}
|
||||
if channels.stable, channels.hasStable, err = fetchChannel(ctx, source, "stable"); err != nil {
|
||||
return channels, err
|
||||
}
|
||||
return channels, nil
|
||||
}
|
||||
|
||||
// canaryRun is the release the canary actually runs: its version, when it was
|
||||
// installed and its fetched release statement.
|
||||
type canaryRun struct {
|
||||
version string
|
||||
installedAt time.Time
|
||||
release releaseupdate.Release
|
||||
found bool
|
||||
}
|
||||
|
||||
// readCanaryRun reads what the canary runs. A host that doesn't record install
|
||||
// times (it updated before they were tracked) degrades to the release
|
||||
// statement's issue time.
|
||||
func readCanaryRun(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source) (canaryRun, error) {
|
||||
var run canaryRun
|
||||
version, installedAt, _, err := dashboard.Installed(ctx)
|
||||
if err != nil {
|
||||
return run, err
|
||||
}
|
||||
run.version, run.installedAt = version, installedAt
|
||||
release, found, err := fetchChannel(ctx, source, releaseupdate.Tag("exact-pin", version))
|
||||
if err != nil {
|
||||
return run, err
|
||||
}
|
||||
run.release, run.found = release, found
|
||||
if run.installedAt.IsZero() && found {
|
||||
run.installedAt = release.Statement.IssuedAt
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
// newerIssued reports whether release a was issued after b. IssuedAt, not
|
||||
// semver order: Promote refuses a release issued before the one stable names,
|
||||
// so the judge must agree with that replay rule.
|
||||
func newerIssued(a, b releaseupdate.Release) bool {
|
||||
return a.Statement.IssuedAt.After(b.Statement.IssuedAt)
|
||||
}
|
||||
|
||||
func displayVersion(version string) string {
|
||||
if version == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
func displayRelease(release releaseupdate.Release, found bool) string {
|
||||
if !found {
|
||||
return "none"
|
||||
}
|
||||
return release.Statement.Version
|
||||
}
|
||||
|
||||
func printVerdict(out io.Writer, version string, verdict releaseupdate.CanaryVerdict) {
|
||||
fmt.Fprintf(out, "%s: %s\n", displayVersion(version), verdict.Decision)
|
||||
for _, reason := range verdict.Reasons {
|
||||
fmt.Fprintf(out, " %s\n", reason)
|
||||
}
|
||||
}
|
||||
|
||||
func runCanaryStatus(args []string, out, stderr io.Writer) int {
|
||||
flags := flag.NewFlagSet("release canary status", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
dashboardURL := flags.String("dashboard", "", "canary dashboard URL")
|
||||
tokenEnv := flags.String("token-env", "ARCHIE_CANARY_TOKEN", "environment variable holding a dashboard API token for the canary")
|
||||
version := flags.String("version", "", "release to install (start)")
|
||||
reference := flags.String("source", "", "OCI repository releases are published to; blank is the official releases (check)")
|
||||
key := flags.String("key", "", "base64 ed25519 public key the source signs with (check)")
|
||||
latest := flags.String("latest", "", "comma-separated image repositories whose v<version> tag becomes latest on promotion (check)")
|
||||
checkout := flags.String("checkout", ".", "repository checkout with release tags, to see whether a release migrated the database (check)")
|
||||
if err := flags.Parse(args[1:]); err != nil {
|
||||
dashboardURL, tokenEnv := addCanaryFlags(flags)
|
||||
reference, key := addSourceFlags(flags)
|
||||
window := flags.Duration("window", releaseupdate.CanaryWindow, "window a release is judged over, counted from its install")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
dashboard := releaseupdate.CanaryDashboard{URL: *dashboardURL, Token: os.Getenv(*tokenEnv)}
|
||||
if *dashboardURL == "" {
|
||||
fmt.Fprintln(stderr, "release canary: -dashboard is required")
|
||||
return 2
|
||||
}
|
||||
ctx := context.Background()
|
||||
if args[0] == "start" {
|
||||
if *version == "" {
|
||||
fmt.Fprintln(stderr, "release canary start: -version is required")
|
||||
return 2
|
||||
}
|
||||
if err := startCanary(ctx, dashboard, *version); err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(out, "canary follows next and runs %s\n", *version)
|
||||
return 0
|
||||
}
|
||||
source, err := distribution.Parse(*reference, *key, distribution.DefaultReleases())
|
||||
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary check:", err)
|
||||
fmt.Fprintln(stderr, "release canary status:", err)
|
||||
return 2
|
||||
}
|
||||
rolledBack, err := checkCanary(ctx, dashboard, source, splitList(*latest), *checkout, out)
|
||||
source, err := canarySource(*reference, *key)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return 1
|
||||
fmt.Fprintln(stderr, "release canary status:", err)
|
||||
return 2
|
||||
}
|
||||
if rolledBack {
|
||||
if err := printCanaryStatus(context.Background(), dashboard, source, *window, out); err != nil {
|
||||
fmt.Fprintln(stderr, "release canary status:", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func startCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, version string) error {
|
||||
if err := dashboard.Follow(ctx, "next", ""); err != nil {
|
||||
return fmt.Errorf("point the canary at next: %w", err)
|
||||
}
|
||||
return dashboard.Install(ctx, version, canaryInstallWait)
|
||||
}
|
||||
|
||||
// checkCanary judges the release on the next channel once and acts on the
|
||||
// result. It reports rolledBack so that the caller can fail the run.
|
||||
func checkCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, latest []string, checkout string, out io.Writer) (rolledBack bool, err error) {
|
||||
next, err := releaseupdate.Fetch(ctx, source, "next")
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
stable, err := releaseupdate.Fetch(ctx, source, "stable")
|
||||
hasStable := err == nil
|
||||
if err != nil && !errors.Is(err, errdef.ErrNotFound) {
|
||||
return false, err
|
||||
}
|
||||
release := next.Statement
|
||||
if release.Prerelease || (hasStable && !release.IssuedAt.After(stable.Statement.IssuedAt)) {
|
||||
fmt.Fprintf(out, "nothing to judge: next is %s and isn't a newer release than stable\n", release.Version)
|
||||
return false, nil
|
||||
}
|
||||
// printCanaryStatus reports the canary's channel, installed release, the
|
||||
// published channels, window progress and the verdict the current signals
|
||||
// would give, without acting on anything.
|
||||
func printCanaryStatus(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, window time.Duration, out io.Writer) error {
|
||||
channel, pin, err := dashboard.Channel(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return err
|
||||
}
|
||||
if channel != "next" {
|
||||
fmt.Fprintf(out, "nothing to judge: the canary is held on %s %s\n", channel, pin)
|
||||
return false, nil
|
||||
channels, err := fetchChannels(ctx, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
run, err := readCanaryRun(ctx, dashboard, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printCanaryState(out, channel, pin, run, channels, window)
|
||||
return printCanaryVerdict(ctx, dashboard, run, window, out)
|
||||
}
|
||||
|
||||
func printCanaryState(out io.Writer, channel, pin string, run canaryRun, channels publishedChannels, window time.Duration) {
|
||||
fmt.Fprintf(out, "channel: %s\n", channelDisplay(channel, pin))
|
||||
fmt.Fprintf(out, "installed: %s", displayVersion(run.version))
|
||||
if run.installedAt.IsZero() {
|
||||
fmt.Fprintln(out, " (installed_at not reported)")
|
||||
} else {
|
||||
fmt.Fprintf(out, " since %s\n", run.installedAt.Format(time.RFC3339))
|
||||
}
|
||||
fmt.Fprintf(out, "stable: %s\n", displayRelease(channels.stable, channels.hasStable))
|
||||
fmt.Fprintf(out, "next: %s\n", displayRelease(channels.next, channels.hasNext))
|
||||
if run.installedAt.IsZero() {
|
||||
fmt.Fprintln(out, "window: unknown, no install time to count from")
|
||||
} else {
|
||||
elapsed := time.Since(run.installedAt)
|
||||
fmt.Fprintf(out, "window: %s of %s elapsed since the install\n", elapsed.Round(time.Minute), window)
|
||||
}
|
||||
}
|
||||
|
||||
func printCanaryVerdict(ctx context.Context, dashboard releaseupdate.CanaryDashboard, run canaryRun, window time.Duration, out io.Writer) error {
|
||||
if run.installedAt.IsZero() {
|
||||
fmt.Fprintln(out, "verdict: unknown, no install time to judge from")
|
||||
return nil
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
signals, err := dashboard.Signals(ctx, release.IssuedAt, now)
|
||||
signals, err := dashboard.Signals(ctx, run.installedAt, now, window)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("read canary signals: %w", err)
|
||||
return fmt.Errorf("read canary signals: %w", err)
|
||||
}
|
||||
verdict := releaseupdate.JudgeCanary(release.Version, now.Sub(release.IssuedAt), signals)
|
||||
fmt.Fprintf(out, "%s: %s\n", release.Version, verdict.Decision)
|
||||
printSignals(out, signals)
|
||||
verdict := releaseupdate.JudgeCanary(run.version, run.installedAt, now, window, signals)
|
||||
fmt.Fprintf(out, "verdict on %s: %s (read-only)\n", displayVersion(run.version), verdict.Decision)
|
||||
for _, reason := range verdict.Reasons {
|
||||
fmt.Fprintf(out, " %s\n", reason)
|
||||
}
|
||||
switch verdict.Decision {
|
||||
case releaseupdate.CanaryPromote:
|
||||
if _, err := releaseupdate.Promote(ctx, source.Reference, source.Key, release.Version, latest); err != nil {
|
||||
return false, fmt.Errorf("promote %s: %w", release.Version, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
func printSignals(out io.Writer, s releaseupdate.CanarySignals) {
|
||||
fmt.Fprintf(out, "signals: runs %q, ready=%t, new action alerts=%d\n", s.Installed, s.Ready, len(s.NewActionAlerts))
|
||||
fmt.Fprintf(out, " tasks finished %d, parked or died %d (baseline %d, %d)\n",
|
||||
s.Canary.Finished, s.Canary.Bad, s.Baseline.Finished, s.Baseline.Bad)
|
||||
fmt.Fprintf(out, " error lines %d, log covers %s (baseline %d, covers %s)\n",
|
||||
s.Canary.Errors, s.Canary.Covered.Round(time.Minute), s.Baseline.Errors, s.Baseline.Covered.Round(time.Minute))
|
||||
}
|
||||
|
||||
func channelDisplay(channel, pin string) string {
|
||||
if pin != "" {
|
||||
return channel + " (pinned to " + pin + ")"
|
||||
}
|
||||
return channel
|
||||
}
|
||||
|
||||
func runCanaryStart(args []string, out, stderr io.Writer) int {
|
||||
flags := flag.NewFlagSet("release canary start", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
dashboardURL, tokenEnv := addCanaryFlags(flags)
|
||||
reference, key := addSourceFlags(flags)
|
||||
version := flags.String("version", "", "release to install on the canary")
|
||||
force := flags.Bool("force", false, "install even when the canary is still judging a newer release")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary start:", err)
|
||||
return 2
|
||||
}
|
||||
if *version == "" {
|
||||
fmt.Fprintln(stderr, "release canary start: -version is required")
|
||||
return 2
|
||||
}
|
||||
source, err := canarySource(*reference, *key)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary start:", err)
|
||||
return 2
|
||||
}
|
||||
if err := startCanary(context.Background(), dashboard, source, *version, *force, out); err != nil {
|
||||
fmt.Fprintln(stderr, "release canary start:", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// startCanary points the canary at next — clearing any rollback pin — and
|
||||
// installs version on it. A release published while the canary still judges a
|
||||
// newer one queues behind it, so the running window isn't restarted under a
|
||||
// different release.
|
||||
func startCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, version string, force bool, out io.Writer) error {
|
||||
// The channel is read before following next: a canary already on next is
|
||||
// judging the release it runs, and a new release queues behind that one.
|
||||
channel, _, err := dashboard.Channel(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dashboard.Follow(ctx, "next", ""); err != nil {
|
||||
return fmt.Errorf("point the canary at next: %w", err)
|
||||
}
|
||||
if !force {
|
||||
queued, err := queuedBehind(ctx, dashboard, source, channel, version, out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(out, "stable is %s\n", release.Version)
|
||||
if queued {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := dashboard.Install(ctx, version, canaryInstallWait); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(out, "the canary follows next and runs %s\n", version)
|
||||
return nil
|
||||
}
|
||||
|
||||
// queuedBehind reports whether version must wait: the canary already follows
|
||||
// next and is still judging the release it runs (a judgeable one), which is a
|
||||
// different release from version.
|
||||
func queuedBehind(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, channel, version string, out io.Writer) (bool, error) {
|
||||
if channel != "next" {
|
||||
return false, nil
|
||||
case releaseupdate.CanaryRollBack:
|
||||
return true, rollBackCanary(ctx, dashboard, release.Version, stable.Statement.Version, hasStable, checkout, out)
|
||||
}
|
||||
run, err := readCanaryRun(ctx, dashboard, source)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if run.version == version {
|
||||
return false, nil
|
||||
}
|
||||
channels, err := fetchChannels(ctx, source)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if judgeable(run, channels) {
|
||||
fmt.Fprintf(out, "%s is queued behind %s, which the canary is still judging\n", version, run.version)
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// rollBackCanary pins the canary to the stable release and reinstalls it.
|
||||
// Going back past a migration needs the pre-update database snapshot, which
|
||||
// loses every write since, so a release that migrated is held instead.
|
||||
func rollBackCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, failed, stable string, hasStable bool, checkout string, out io.Writer) error {
|
||||
if !hasStable || migrated(ctx, checkout, stable, failed) {
|
||||
if err := dashboard.Follow(ctx, "exact-pin", failed); err != nil {
|
||||
return fmt.Errorf("hold the canary on %s: %w", failed, err)
|
||||
func runCanaryCheck(args []string, out, stderr io.Writer) int {
|
||||
flags := flag.NewFlagSet("release canary check", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
dashboardURL, tokenEnv := addCanaryFlags(flags)
|
||||
reference, key := addSourceFlags(flags)
|
||||
latest := flags.String("latest", "", "comma-separated image repositories whose v<version> tag becomes latest on promotion")
|
||||
checkout := flags.String("checkout", ".", "repository checkout with release tags, to see whether a release migrated the database")
|
||||
window := flags.Duration("window", releaseupdate.CanaryWindow, "window the installed release is judged over, counted from its install")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary check:", err)
|
||||
return 2
|
||||
}
|
||||
source, err := canarySource(*reference, *key)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary check:", err)
|
||||
return 2
|
||||
}
|
||||
code, err := checkCanary(context.Background(), dashboard, source, splitList(*latest), *checkout, *window, out)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary check:", err)
|
||||
return 1
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// checkCanary judges the release the canary actually runs — not the moving
|
||||
// next tag — and acts on the verdict. The exit code is 1 when the run should
|
||||
// show red: a rollback happened, or the canary is held on a pin that can no
|
||||
// longer be installed.
|
||||
func checkCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, latest []string, checkout string, window time.Duration, out io.Writer) (int, error) {
|
||||
channels, err := fetchChannels(ctx, source)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
channel, pin, err := dashboard.Channel(ctx)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if channel != "next" {
|
||||
return heldCanary(ctx, source, channel, pin, out)
|
||||
}
|
||||
run, err := readCanaryRun(ctx, dashboard, source)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if !judgeable(run, channels) {
|
||||
fmt.Fprintf(out, "nothing to judge: the canary runs %s\n", displayVersion(run.version))
|
||||
return pickupNext(ctx, dashboard, channels, run.version, out)
|
||||
}
|
||||
return judgeInstalled(ctx, dashboard, source, run, channels, latest, checkout, window, out)
|
||||
}
|
||||
|
||||
// judgeable reports whether the installed release is one the canary judges: a
|
||||
// published, non-prerelease release issued after stable's.
|
||||
func judgeable(run canaryRun, channels publishedChannels) bool {
|
||||
if !run.found || run.release.Statement.Prerelease {
|
||||
return false
|
||||
}
|
||||
return !channels.hasStable || newerIssued(run.release, channels.stable)
|
||||
}
|
||||
|
||||
func judgeInstalled(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, run canaryRun, channels publishedChannels, latest []string, checkout string, window time.Duration, out io.Writer) (int, error) {
|
||||
now := time.Now().UTC()
|
||||
signals, err := dashboard.Signals(ctx, run.installedAt, now, window)
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("read canary signals: %w", err)
|
||||
}
|
||||
verdict := releaseupdate.JudgeCanary(run.version, run.installedAt, now, window, signals)
|
||||
printVerdict(out, run.version, verdict)
|
||||
switch verdict.Decision {
|
||||
case releaseupdate.CanaryPromote:
|
||||
return 0, promoteJudged(ctx, dashboard, source, run, channels, latest, out)
|
||||
case releaseupdate.CanaryRollBack:
|
||||
return 1, rollBackCanary(ctx, dashboard, source, run, channels, checkout, out)
|
||||
default:
|
||||
return 0, nil
|
||||
}
|
||||
}
|
||||
|
||||
// promoteJudged moves stable to the judged release, then picks up a newer next
|
||||
// queued behind it.
|
||||
func promoteJudged(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, run canaryRun, channels publishedChannels, latest []string, out io.Writer) error {
|
||||
if _, err := releaseupdate.Promote(ctx, source.Reference, source.Key, run.version, latest); err != nil {
|
||||
return fmt.Errorf("promote %s: %w", run.version, err)
|
||||
}
|
||||
fmt.Fprintf(out, "stable is %s\n", run.version)
|
||||
fresh := channels
|
||||
fresh.stable, fresh.hasStable = run.release, true
|
||||
_, err := pickupNext(ctx, dashboard, fresh, run.version, out)
|
||||
return err
|
||||
}
|
||||
|
||||
// pickupNext installs the next release when it is newer than stable and the
|
||||
// canary doesn't already run it.
|
||||
func pickupNext(ctx context.Context, dashboard releaseupdate.CanaryDashboard, channels publishedChannels, installed string, out io.Writer) (int, error) {
|
||||
if !channels.hasNext || channels.next.Statement.Version == installed {
|
||||
return 0, nil
|
||||
}
|
||||
if channels.hasStable && !newerIssued(channels.next, channels.stable) {
|
||||
return 0, nil
|
||||
}
|
||||
if err := dashboard.Install(ctx, channels.next.Statement.Version, canaryInstallWait); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
fmt.Fprintf(out, "the canary picks up %s from next\n", channels.next.Statement.Version)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// heldCanary reports a canary that isn't following next. Its pin must still be
|
||||
// installable: a stranded pin fails the run instead of looking green.
|
||||
func heldCanary(ctx context.Context, source distribution.Source, channel, pin string, out io.Writer) (int, error) {
|
||||
if pin != "" {
|
||||
err := checkPin(ctx, source, pin)
|
||||
if errors.Is(err, errStrandedPin) {
|
||||
fmt.Fprintf(out, "ERROR: the canary is held on %s %s, which is stranded: %v; unpin it or republish the release\n", channel, pin, err)
|
||||
return 1, nil
|
||||
}
|
||||
fmt.Fprintf(out, "%s changed the database schema or there's no stable release to return to: the canary is held on %s and stable is unchanged; fix forward\n", failed, failed)
|
||||
return nil
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
fmt.Fprintf(out, "held on %s %s, nothing to judge\n", channel, pin)
|
||||
return 0, nil
|
||||
}
|
||||
if err := dashboard.Follow(ctx, "exact-pin", stable); err != nil {
|
||||
return fmt.Errorf("pin the canary to %s: %w", stable, err)
|
||||
fmt.Fprintf(out, "held on %s, nothing to judge\n", channel)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// errStrandedPin marks a held pin that can no longer be installed.
|
||||
var errStrandedPin = errors.New("pin is stranded")
|
||||
|
||||
// checkPin fails when a held pin can no longer be installed: the release is
|
||||
// gone from the source, or its artifacts are.
|
||||
func checkPin(ctx context.Context, source distribution.Source, pin string) error {
|
||||
release, found, err := fetchChannel(ctx, source, releaseupdate.Tag("exact-pin", pin))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dashboard.Install(ctx, stable, canaryInstallWait); err != nil {
|
||||
return fmt.Errorf("return the canary to %s: %w", stable, err)
|
||||
if !found {
|
||||
return fmt.Errorf("%w: no release %s in the source", errStrandedPin, releaseupdate.Tag("exact-pin", pin))
|
||||
}
|
||||
if err := releaseupdate.Installable(ctx, source, release); err != nil {
|
||||
return fmt.Errorf("%w: %w", errStrandedPin, err)
|
||||
}
|
||||
fmt.Fprintf(out, "the canary is back on %s and stable is unchanged\n", stable)
|
||||
return nil
|
||||
}
|
||||
|
||||
// rollBackCanary returns the canary to stable after a failed verdict. stable
|
||||
// is checked installable before the canary is pinned to it: a pin whose
|
||||
// artifacts are gone would strand the canary, so the run fails loudly and the
|
||||
// canary stays on next. A release that changed the migrations is held on the
|
||||
// failed version instead, because going back past a migration needs the
|
||||
// pre-update database snapshot.
|
||||
func rollBackCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, run canaryRun, channels publishedChannels, checkout string, out io.Writer) error {
|
||||
failed := run.version
|
||||
if !channels.hasStable {
|
||||
return holdCanary(ctx, dashboard, failed, "there's no stable release to return to", out)
|
||||
}
|
||||
stable := channels.stable
|
||||
if err := releaseupdate.Installable(ctx, source, stable); err != nil {
|
||||
return fmt.Errorf("stable %s is not installable, the canary stays on next: %w", stable.Statement.Version, err)
|
||||
}
|
||||
changed, err := migrated(ctx, checkout, stable.Statement.Version, failed)
|
||||
if err != nil {
|
||||
return holdCanary(ctx, dashboard, failed, err.Error(), out)
|
||||
}
|
||||
if changed {
|
||||
return holdCanary(ctx, dashboard, failed, failed+" changed the database schema", out)
|
||||
}
|
||||
if err := dashboard.Follow(ctx, "exact-pin", stable.Statement.Version); err != nil {
|
||||
return fmt.Errorf("pin the canary to %s: %w", stable.Statement.Version, err)
|
||||
}
|
||||
if err := dashboard.Install(ctx, stable.Statement.Version, canaryInstallWait); err != nil {
|
||||
return fmt.Errorf("return the canary to %s: %w", stable.Statement.Version, err)
|
||||
}
|
||||
fmt.Fprintf(out, "the canary is back on %s and stable is unchanged\n", stable.Statement.Version)
|
||||
return nil
|
||||
}
|
||||
|
||||
func holdCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, version, why string, out io.Writer) error {
|
||||
if err := dashboard.Follow(ctx, "exact-pin", version); err != nil {
|
||||
return fmt.Errorf("hold the canary on %s: %w", version, err)
|
||||
}
|
||||
fmt.Fprintf(out, "%s: the canary is held on %s and stable is unchanged; fix forward\n", why, version)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runGitDiff runs git diff --quiet between two release tags and reports its
|
||||
// exit code and stderr. It is a variable so tests can drive the three
|
||||
// outcomes without a repository.
|
||||
var runGitDiff = func(ctx context.Context, checkout, from, to string) (int, string, error) {
|
||||
cmd := exec.CommandContext(ctx, "git", "-C", checkout, "diff", "--quiet", "v"+from, "v"+to, "--", migrationsDir)
|
||||
var buf bytes.Buffer
|
||||
cmd.Stderr = &buf
|
||||
err := cmd.Run()
|
||||
if err == nil {
|
||||
return 0, "", nil
|
||||
}
|
||||
if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
|
||||
return exitErr.ExitCode(), buf.String(), err
|
||||
}
|
||||
return -1, buf.String(), err
|
||||
}
|
||||
|
||||
// migrated reports whether the migrations differ between two release tags.
|
||||
// If it can't tell, it says they differ, so the canary is held rather than
|
||||
// rolled back.
|
||||
func migrated(ctx context.Context, checkout, from, to string) bool {
|
||||
err := exec.CommandContext(ctx, "git", "-C", checkout, "diff", "--quiet", "v"+from, "v"+to, "--", migrationsDir).Run()
|
||||
return err != nil
|
||||
// It returns true, nil when they differ, false, nil when they are identical,
|
||||
// and true, err when git could not answer, with the reason in err. Every
|
||||
// non-identical outcome holds the canary rather than rolls it back.
|
||||
func migrated(ctx context.Context, checkout, from, to string) (bool, error) {
|
||||
code, stderr, runErr := runGitDiff(ctx, checkout, from, to)
|
||||
switch code {
|
||||
case 0:
|
||||
return false, nil
|
||||
case 1:
|
||||
return true, nil
|
||||
}
|
||||
reason := strings.TrimSpace(stderr)
|
||||
if reason == "" && runErr != nil {
|
||||
reason = runErr.Error()
|
||||
}
|
||||
return true, fmt.Errorf("could not tell whether %s changed the database schema: %s", to, reason)
|
||||
}
|
||||
|
||||
func runCanaryPromote(args []string, out, stderr io.Writer) int {
|
||||
flags := flag.NewFlagSet("release canary promote", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
dashboardURL, tokenEnv := addCanaryFlags(flags)
|
||||
reference, key := addSourceFlags(flags)
|
||||
latest := flags.String("latest", "", "comma-separated image repositories whose v<version> tag becomes latest on promotion")
|
||||
version := flags.String("version", "", "release expected on the canary; must match what it runs")
|
||||
window := flags.Duration("window", releaseupdate.CanaryWindow, "window the signals are read over, counted from the install")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary promote:", err)
|
||||
return 2
|
||||
}
|
||||
source, err := canarySource(*reference, *key)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary promote:", err)
|
||||
return 2
|
||||
}
|
||||
code, err := promoteCanaryNow(context.Background(), dashboard, source, *version, splitList(*latest), *window, out)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary promote:", err)
|
||||
return 1
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// promoteCanaryNow promotes the release the canary runs right now, without
|
||||
// waiting out the window: the signals must show no hard failure and no
|
||||
// relative breach. It refuses, with exit 1, when anything fails.
|
||||
func promoteCanaryNow(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, expectVersion string, latest []string, window time.Duration, out io.Writer) (int, error) {
|
||||
run, err := readCanaryRun(ctx, dashboard, source)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
channel, pin, err := dashboard.Channel(ctx)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
fmt.Fprintf(out, "channel: %s\n", channelDisplay(channel, pin))
|
||||
if expectVersion != "" && expectVersion != run.version {
|
||||
return 1, fmt.Errorf("the canary runs %s, not %s", displayVersion(run.version), expectVersion)
|
||||
}
|
||||
if !run.found {
|
||||
return 1, fmt.Errorf("no release %s in the source to promote", displayVersion(run.version))
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
signals, err := dashboard.Signals(ctx, run.installedAt, now, window)
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("read canary signals: %w", err)
|
||||
}
|
||||
verdict := releaseupdate.JudgeCanaryNow(run.version, now, window, signals)
|
||||
printVerdict(out, run.version, verdict)
|
||||
if verdict.Decision == releaseupdate.CanaryRollBack {
|
||||
fmt.Fprintln(out, "refusing to promote: the canary's signals fail")
|
||||
return 1, nil
|
||||
}
|
||||
if _, err := releaseupdate.Promote(ctx, source.Reference, source.Key, run.version, latest); err != nil {
|
||||
return 1, fmt.Errorf("promote %s: %w", run.version, err)
|
||||
}
|
||||
fmt.Fprintf(out, "stable is %s\n", run.version)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func runCanaryUnpin(args []string, out, stderr io.Writer) int {
|
||||
flags := flag.NewFlagSet("release canary unpin", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
dashboardURL, tokenEnv := addCanaryFlags(flags)
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "release canary unpin:", err)
|
||||
return 2
|
||||
}
|
||||
if err := dashboard.Follow(context.Background(), "next", ""); err != nil {
|
||||
fmt.Fprintln(stderr, "release canary unpin:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintln(out, "the canary follows next again, with no pin")
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMigrated(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
code int
|
||||
stderr string
|
||||
wantChanged bool
|
||||
wantErr bool
|
||||
wantSubstr string
|
||||
}{
|
||||
{
|
||||
name: "identical migrations",
|
||||
code: 0,
|
||||
wantChanged: false,
|
||||
},
|
||||
{
|
||||
name: "migrations differ",
|
||||
code: 1,
|
||||
wantChanged: true,
|
||||
},
|
||||
{
|
||||
name: "git cannot answer",
|
||||
code: 128,
|
||||
stderr: "fatal: bad revision 'v1.0.0'\n",
|
||||
wantChanged: true,
|
||||
wantErr: true,
|
||||
wantSubstr: "fatal: bad revision 'v1.0.0'",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
old := runGitDiff
|
||||
runGitDiff = func(context.Context, string, string, string) (int, string, error) {
|
||||
return tt.code, tt.stderr, nil
|
||||
}
|
||||
t.Cleanup(func() { runGitDiff = old })
|
||||
|
||||
changed, err := migrated(context.Background(), ".", "1.0.0", "1.1.0")
|
||||
if changed != tt.wantChanged {
|
||||
t.Fatalf("changed = %v, want %v", changed, tt.wantChanged)
|
||||
}
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("err = %v, want err %v", err, tt.wantErr)
|
||||
}
|
||||
if tt.wantErr && !strings.Contains(err.Error(), tt.wantSubstr) {
|
||||
t.Fatalf("err = %q, want substring %q", err, tt.wantSubstr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
// because archie-messaging, a separate process that cannot import this
|
||||
// package, is the next process that must be able to announce itself.
|
||||
// What stays here is what is the daemon's own: which
|
||||
// marker counts as progress (daemon.LastPollAt) and how long the loop may go
|
||||
// marker counts as progress (daemon.StalestLoop) and how long a loop may go
|
||||
// without beginning a poll pass.
|
||||
//
|
||||
// Nothing here is fatal -- a process with no NOTIFY_SOCKET (a plain terminal,
|
||||
@@ -53,7 +53,7 @@ func (b *boot) startWatchdog(ctx context.Context) {
|
||||
sampler := sdnotify.Watchdog{
|
||||
Interval: interval,
|
||||
Cadence: b.loopCadence,
|
||||
Progress: b.d.LastPollAt,
|
||||
Progress: b.d.StalestLoop,
|
||||
Beat: func() { n.Send(sdnotify.WatchdogState) },
|
||||
Log: b.log,
|
||||
}
|
||||
|
||||
@@ -77,6 +77,13 @@ func (b *boot) removeTaskWorktree(task *taskactions.Task) error {
|
||||
if b.d == nil {
|
||||
return nil
|
||||
}
|
||||
// A run that handed off shares the work item's worktree with its
|
||||
// successor; archiving the old run must not remove it.
|
||||
if current, err := b.stateStore.TaskByIssue(context.Background(), task.Owner, task.Repo, task.IssueNumber); err != nil {
|
||||
return err
|
||||
} else if current != nil && current.ID != task.ID {
|
||||
return nil
|
||||
}
|
||||
return b.d.RemoveWorktree(&workflow.Task{Owner: task.Owner, Repo: task.Repo, Identity: task.Identity, IssueNumber: task.IssueNumber, Org: task.Org})
|
||||
}
|
||||
|
||||
|
||||
@@ -295,10 +295,7 @@ func hasConfigSection(document map[string]any, section string) bool {
|
||||
}
|
||||
|
||||
func updateStateDir() string {
|
||||
if dir := os.Getenv("ARCHIE_UPDATE_STATE_DIR"); dir != "" {
|
||||
return dir
|
||||
}
|
||||
return configuration.DefaultUpdateStateDir()
|
||||
return configuration.UpdateStateDir()
|
||||
}
|
||||
|
||||
// resumeUpdate hands an interrupted transaction to the frozen watchdog and
|
||||
|
||||
@@ -12,7 +12,9 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/usage"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
|
||||
@@ -40,7 +42,7 @@ func (b *server) setupCurators(ctx context.Context) bool {
|
||||
MemoryEngines: b.memEngines,
|
||||
Skills: skillcurator.NewStore(skillsRoot),
|
||||
Conversations: sessioncurator.NewAdapter(b.chatSessionStore, b.cfg.BotUser),
|
||||
LLM: curatorLLMRunner{llm: b.chatLLM, outcomes: b.providerOutcomes, usage: b.usage},
|
||||
LLM: actingPrincipalRunner{inner: curatorLLMRunner{llm: b.chatLLM, outcomes: b.providerOutcomes, usage: b.usage}, resolve: b.actingPrincipal},
|
||||
Model: model,
|
||||
})
|
||||
|
||||
@@ -95,6 +97,42 @@ func (s curatorEventSink) Emit(kind, detail string, data map[string]any) {
|
||||
s.b.Publish(context.Background(), events.Event{Kind: kind, Detail: detail, Data: data})
|
||||
}
|
||||
|
||||
// actingPrincipal resolves the identity the instance acts as for automated
|
||||
// work (the default chat identity, falling back to the bot user), so curator
|
||||
// passes authorize guarded tools exactly as that identity would.
|
||||
func (b *server) actingPrincipal(ctx context.Context) (access.Principal, error) {
|
||||
name := b.defaultChatIdentity
|
||||
if name == "" {
|
||||
name = b.cfg.BotUser
|
||||
}
|
||||
if name == "" {
|
||||
return access.Principal{}, fmt.Errorf("no acting identity configured (chat identity or bot user)")
|
||||
}
|
||||
idn, err := b.stateStore.ResolveLegacyName(ctx, name)
|
||||
if err != nil {
|
||||
return access.Principal{}, fmt.Errorf("resolve acting identity %q: %w", name, err)
|
||||
}
|
||||
return b.stateStore.PrincipalFor(ctx, idn.ID)
|
||||
}
|
||||
|
||||
// actingPrincipalRunner attaches the acting principal to every curator model
|
||||
// call. Tool handlers run in the call's context, so guarded tools see the
|
||||
// curator as the instance's identity, never as an anonymous or caller-supplied
|
||||
// one; a pass that cannot resolve the principal fails closed.
|
||||
type actingPrincipalRunner struct {
|
||||
inner curator.LLMRunner
|
||||
resolve func(context.Context) (access.Principal, error)
|
||||
}
|
||||
|
||||
func (r actingPrincipalRunner) Chat(ctx context.Context, req curator.ChatRequest) (curator.ChatResult, error) {
|
||||
p, err := r.resolve(ctx)
|
||||
if err != nil {
|
||||
return curator.ChatResult{}, fmt.Errorf("curator pass: %w", err)
|
||||
}
|
||||
ctx = org.WithScope(org.WithOrg(access.WithPrincipal(ctx, p), p.Org), p.Org)
|
||||
return r.inner.Chat(ctx, req)
|
||||
}
|
||||
|
||||
// curatorLLMRunner adapts the shared ai-sdk runtime to the curator
|
||||
// family's narrow LLMRunner contract: one model reference, plain
|
||||
// messages, and the declared tool set -- no streaming. Tools are built
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/issuerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
@@ -109,6 +110,14 @@ func (b *server) registerWorkflowTools(ctx context.Context) {
|
||||
authz := infraaccess.StartLive(ctx, b.stateStore.ListPolicies, b.stateStore.PoliciesVersion, b.log)
|
||||
workflows := controlplanerpc.NewWorkflows(b.stateStore.ControlPlane())
|
||||
entries := append(gateway.WorkflowTools(workflows, authz), gateway.IntegrationTools(integrationSource{Workflows: workflows, store: b.stateStore}, authz)...)
|
||||
// Run-inspection tools back long-running curators (self-intake first);
|
||||
// the State Store client satisfies the source directly.
|
||||
entries = append(entries, gateway.RunTools(b.stateStore, authz)...)
|
||||
// Issue tools reach the forge through the daemon, which alone holds its
|
||||
// credentials; without the broker connection they are not registered.
|
||||
if b.taskActionsConn != nil {
|
||||
entries = append(entries, gateway.IssueTools(issuerpc.Client{Conn: b.taskActionsConn, Timeout: 30 * time.Second}, authz)...)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if err := b.toolReg.Register(entry); err != nil {
|
||||
b.log.WarnContext(ctx, "workflow tool registration failed", "tool", entry.Name, "err", err)
|
||||
|
||||
@@ -202,6 +202,11 @@ func (b *server) seedAndValidatePolicies(ctx context.Context) error {
|
||||
// not to the sequence that triggers it.
|
||||
func (b *server) reportUnseededResources(skipped []controlplanestore.SeedSkip) {
|
||||
for _, skip := range skipped {
|
||||
if len(skip.Removed) > 0 {
|
||||
b.log.Warn("removed stored entries that no longer validate; their earlier revision is in the resource history",
|
||||
"kind", skip.Kind, "removed", skip.Removed)
|
||||
continue
|
||||
}
|
||||
b.log.Error("control-plane resource not seeded; the kind stays absent and the file's value is the one in effect",
|
||||
"kind", skip.Kind, "err", skip.Err)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -23,6 +23,7 @@ const (
|
||||
ForgeService_AssignedIssues_FullMethodName = "/forge.v1.ForgeService/AssignedIssues"
|
||||
ForgeService_IssuesWithLabel_FullMethodName = "/forge.v1.ForgeService/IssuesWithLabel"
|
||||
ForgeService_Comment_FullMethodName = "/forge.v1.ForgeService/Comment"
|
||||
ForgeService_CreateIssue_FullMethodName = "/forge.v1.ForgeService/CreateIssue"
|
||||
ForgeService_CloseIssue_FullMethodName = "/forge.v1.ForgeService/CloseIssue"
|
||||
ForgeService_React_FullMethodName = "/forge.v1.ForgeService/React"
|
||||
ForgeService_SetStateLabel_FullMethodName = "/forge.v1.ForgeService/SetStateLabel"
|
||||
@@ -60,6 +61,7 @@ type ForgeServiceClient interface {
|
||||
AssignedIssues(ctx context.Context, in *AssignedIssuesRequest, opts ...grpc.CallOption) (*AssignedIssuesResponse, error)
|
||||
IssuesWithLabel(ctx context.Context, in *IssuesWithLabelRequest, opts ...grpc.CallOption) (*IssuesWithLabelResponse, error)
|
||||
Comment(ctx context.Context, in *CommentRequest, opts ...grpc.CallOption) (*CommentResponse, error)
|
||||
CreateIssue(ctx context.Context, in *CreateIssueRequest, opts ...grpc.CallOption) (*CreateIssueResponse, error)
|
||||
CloseIssue(ctx context.Context, in *CloseIssueRequest, opts ...grpc.CallOption) (*CloseIssueResponse, error)
|
||||
React(ctx context.Context, in *ReactRequest, opts ...grpc.CallOption) (*ReactResponse, error)
|
||||
SetStateLabel(ctx context.Context, in *SetStateLabelRequest, opts ...grpc.CallOption) (*SetStateLabelResponse, error)
|
||||
@@ -132,6 +134,16 @@ func (c *forgeServiceClient) Comment(ctx context.Context, in *CommentRequest, op
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *forgeServiceClient) CreateIssue(ctx context.Context, in *CreateIssueRequest, opts ...grpc.CallOption) (*CreateIssueResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(CreateIssueResponse)
|
||||
err := c.cc.Invoke(ctx, ForgeService_CreateIssue_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *forgeServiceClient) CloseIssue(ctx context.Context, in *CloseIssueRequest, opts ...grpc.CallOption) (*CloseIssueResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(CloseIssueResponse)
|
||||
@@ -338,6 +350,7 @@ type ForgeServiceServer interface {
|
||||
AssignedIssues(context.Context, *AssignedIssuesRequest) (*AssignedIssuesResponse, error)
|
||||
IssuesWithLabel(context.Context, *IssuesWithLabelRequest) (*IssuesWithLabelResponse, error)
|
||||
Comment(context.Context, *CommentRequest) (*CommentResponse, error)
|
||||
CreateIssue(context.Context, *CreateIssueRequest) (*CreateIssueResponse, error)
|
||||
CloseIssue(context.Context, *CloseIssueRequest) (*CloseIssueResponse, error)
|
||||
React(context.Context, *ReactRequest) (*ReactResponse, error)
|
||||
SetStateLabel(context.Context, *SetStateLabelRequest) (*SetStateLabelResponse, error)
|
||||
@@ -382,6 +395,9 @@ func (UnimplementedForgeServiceServer) IssuesWithLabel(context.Context, *IssuesW
|
||||
func (UnimplementedForgeServiceServer) Comment(context.Context, *CommentRequest) (*CommentResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method Comment not implemented")
|
||||
}
|
||||
func (UnimplementedForgeServiceServer) CreateIssue(context.Context, *CreateIssueRequest) (*CreateIssueResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method CreateIssue not implemented")
|
||||
}
|
||||
func (UnimplementedForgeServiceServer) CloseIssue(context.Context, *CloseIssueRequest) (*CloseIssueResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method CloseIssue not implemented")
|
||||
}
|
||||
@@ -529,6 +545,24 @@ func _ForgeService_Comment_Handler(srv interface{}, ctx context.Context, dec fun
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ForgeService_CreateIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(CreateIssueRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ForgeServiceServer).CreateIssue(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ForgeService_CreateIssue_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ForgeServiceServer).CreateIssue(ctx, req.(*CreateIssueRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ForgeService_CloseIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(CloseIssueRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -869,6 +903,10 @@ var ForgeService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "Comment",
|
||||
Handler: _ForgeService_Comment_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "CreateIssue",
|
||||
Handler: _ForgeService_CreateIssue_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "CloseIssue",
|
||||
Handler: _ForgeService_CloseIssue_Handler,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -38,6 +38,7 @@ const (
|
||||
AccountService_AddPersonalToken_FullMethodName = "/state.v1.AccountService/AddPersonalToken"
|
||||
AccountService_ListPersonalTokens_FullMethodName = "/state.v1.AccountService/ListPersonalTokens"
|
||||
AccountService_RevokePersonalToken_FullMethodName = "/state.v1.AccountService/RevokePersonalToken"
|
||||
AccountService_BindIdentityPersonalToken_FullMethodName = "/state.v1.AccountService/BindIdentityPersonalToken"
|
||||
)
|
||||
|
||||
// AccountServiceClient is the client API for AccountService service.
|
||||
@@ -65,6 +66,12 @@ type AccountServiceClient interface {
|
||||
AddPersonalToken(ctx context.Context, in *AddPersonalTokenRequest, opts ...grpc.CallOption) (*AddPersonalTokenResponse, error)
|
||||
ListPersonalTokens(ctx context.Context, in *ListPersonalTokensRequest, opts ...grpc.CallOption) (*ListPersonalTokensResponse, error)
|
||||
RevokePersonalToken(ctx context.Context, in *RevokePersonalTokenRequest, opts ...grpc.CallOption) (*RevokePersonalTokenResponse, error)
|
||||
// BindIdentityPersonalToken binds a personal token to a NAMED identity
|
||||
// instead of the caller's principal, which is how a service account gets
|
||||
// its bearer credential. Only non-user targets are accepted: a person's
|
||||
// token comes from AddPersonalToken. The audit actor is the caller's
|
||||
// principal, never a request field.
|
||||
BindIdentityPersonalToken(ctx context.Context, in *BindIdentityPersonalTokenRequest, opts ...grpc.CallOption) (*BindIdentityPersonalTokenResponse, error)
|
||||
}
|
||||
|
||||
type accountServiceClient struct {
|
||||
@@ -265,6 +272,16 @@ func (c *accountServiceClient) RevokePersonalToken(ctx context.Context, in *Revo
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *accountServiceClient) BindIdentityPersonalToken(ctx context.Context, in *BindIdentityPersonalTokenRequest, opts ...grpc.CallOption) (*BindIdentityPersonalTokenResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(BindIdentityPersonalTokenResponse)
|
||||
err := c.cc.Invoke(ctx, AccountService_BindIdentityPersonalToken_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AccountServiceServer is the server API for AccountService service.
|
||||
// All implementations must embed UnimplementedAccountServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -290,6 +307,12 @@ type AccountServiceServer interface {
|
||||
AddPersonalToken(context.Context, *AddPersonalTokenRequest) (*AddPersonalTokenResponse, error)
|
||||
ListPersonalTokens(context.Context, *ListPersonalTokensRequest) (*ListPersonalTokensResponse, error)
|
||||
RevokePersonalToken(context.Context, *RevokePersonalTokenRequest) (*RevokePersonalTokenResponse, error)
|
||||
// BindIdentityPersonalToken binds a personal token to a NAMED identity
|
||||
// instead of the caller's principal, which is how a service account gets
|
||||
// its bearer credential. Only non-user targets are accepted: a person's
|
||||
// token comes from AddPersonalToken. The audit actor is the caller's
|
||||
// principal, never a request field.
|
||||
BindIdentityPersonalToken(context.Context, *BindIdentityPersonalTokenRequest) (*BindIdentityPersonalTokenResponse, error)
|
||||
mustEmbedUnimplementedAccountServiceServer()
|
||||
}
|
||||
|
||||
@@ -357,6 +380,9 @@ func (UnimplementedAccountServiceServer) ListPersonalTokens(context.Context, *Li
|
||||
func (UnimplementedAccountServiceServer) RevokePersonalToken(context.Context, *RevokePersonalTokenRequest) (*RevokePersonalTokenResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RevokePersonalToken not implemented")
|
||||
}
|
||||
func (UnimplementedAccountServiceServer) BindIdentityPersonalToken(context.Context, *BindIdentityPersonalTokenRequest) (*BindIdentityPersonalTokenResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method BindIdentityPersonalToken not implemented")
|
||||
}
|
||||
func (UnimplementedAccountServiceServer) mustEmbedUnimplementedAccountServiceServer() {}
|
||||
func (UnimplementedAccountServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -720,6 +746,24 @@ func _AccountService_RevokePersonalToken_Handler(srv interface{}, ctx context.Co
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AccountService_BindIdentityPersonalToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(BindIdentityPersonalTokenRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AccountServiceServer).BindIdentityPersonalToken(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AccountService_BindIdentityPersonalToken_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AccountServiceServer).BindIdentityPersonalToken(ctx, req.(*BindIdentityPersonalTokenRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// AccountService_ServiceDesc is the grpc.ServiceDesc for AccountService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -803,6 +847,10 @@ var AccountService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "RevokePersonalToken",
|
||||
Handler: _AccountService_RevokePersonalToken_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "BindIdentityPersonalToken",
|
||||
Handler: _AccountService_BindIdentityPersonalToken_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "state/v1/account.proto",
|
||||
|
||||
@@ -2163,6 +2163,110 @@ func (x *EnqueueCallTaskRequest) GetCallKey() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
type HandoffTaskRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
|
||||
Workflow string `protobuf:"bytes,2,opt,name=workflow,proto3" json:"workflow,omitempty"`
|
||||
Detail string `protobuf:"bytes,3,opt,name=detail,proto3" json:"detail,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) Reset() {
|
||||
*x = HandoffTaskRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HandoffTaskRequest) ProtoMessage() {}
|
||||
|
||||
func (x *HandoffTaskRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HandoffTaskRequest.ProtoReflect.Descriptor instead.
|
||||
func (*HandoffTaskRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{41}
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) GetTaskId() int64 {
|
||||
if x != nil {
|
||||
return x.TaskId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) GetWorkflow() string {
|
||||
if x != nil {
|
||||
return x.Workflow
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *HandoffTaskRequest) GetDetail() string {
|
||||
if x != nil {
|
||||
return x.Detail
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type HandoffTaskResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HandoffTaskResponse) Reset() {
|
||||
*x = HandoffTaskResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HandoffTaskResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HandoffTaskResponse) ProtoMessage() {}
|
||||
|
||||
func (x *HandoffTaskResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HandoffTaskResponse.ProtoReflect.Descriptor instead.
|
||||
func (*HandoffTaskResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{42}
|
||||
}
|
||||
|
||||
func (x *HandoffTaskResponse) GetTask() *Task {
|
||||
if x != nil {
|
||||
return x.Task
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type EnqueueCallTaskResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"`
|
||||
@@ -2173,7 +2277,7 @@ type EnqueueCallTaskResponse struct {
|
||||
|
||||
func (x *EnqueueCallTaskResponse) Reset() {
|
||||
*x = EnqueueCallTaskResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2185,7 +2289,7 @@ func (x *EnqueueCallTaskResponse) String() string {
|
||||
func (*EnqueueCallTaskResponse) ProtoMessage() {}
|
||||
|
||||
func (x *EnqueueCallTaskResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[41]
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2198,7 +2302,7 @@ func (x *EnqueueCallTaskResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use EnqueueCallTaskResponse.ProtoReflect.Descriptor instead.
|
||||
func (*EnqueueCallTaskResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{41}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{43}
|
||||
}
|
||||
|
||||
func (x *EnqueueCallTaskResponse) GetTask() *Task {
|
||||
@@ -2225,7 +2329,7 @@ type WorkflowCallStatusRequest struct {
|
||||
|
||||
func (x *WorkflowCallStatusRequest) Reset() {
|
||||
*x = WorkflowCallStatusRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2237,7 +2341,7 @@ func (x *WorkflowCallStatusRequest) String() string {
|
||||
func (*WorkflowCallStatusRequest) ProtoMessage() {}
|
||||
|
||||
func (x *WorkflowCallStatusRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[42]
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2250,7 +2354,7 @@ func (x *WorkflowCallStatusRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use WorkflowCallStatusRequest.ProtoReflect.Descriptor instead.
|
||||
func (*WorkflowCallStatusRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{42}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{44}
|
||||
}
|
||||
|
||||
func (x *WorkflowCallStatusRequest) GetCallerTaskId() int64 {
|
||||
@@ -2283,7 +2387,7 @@ type WorkflowCallStatusResponse struct {
|
||||
|
||||
func (x *WorkflowCallStatusResponse) Reset() {
|
||||
*x = WorkflowCallStatusResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2295,7 +2399,7 @@ func (x *WorkflowCallStatusResponse) String() string {
|
||||
func (*WorkflowCallStatusResponse) ProtoMessage() {}
|
||||
|
||||
func (x *WorkflowCallStatusResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[43]
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2308,7 +2412,7 @@ func (x *WorkflowCallStatusResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use WorkflowCallStatusResponse.ProtoReflect.Descriptor instead.
|
||||
func (*WorkflowCallStatusResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{43}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{45}
|
||||
}
|
||||
|
||||
func (x *WorkflowCallStatusResponse) GetStatus() string {
|
||||
@@ -2341,7 +2445,7 @@ type TaskModelsRequest struct {
|
||||
|
||||
func (x *TaskModelsRequest) Reset() {
|
||||
*x = TaskModelsRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2353,7 +2457,7 @@ func (x *TaskModelsRequest) String() string {
|
||||
func (*TaskModelsRequest) ProtoMessage() {}
|
||||
|
||||
func (x *TaskModelsRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[44]
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2366,7 +2470,7 @@ func (x *TaskModelsRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskModelsRequest.ProtoReflect.Descriptor instead.
|
||||
func (*TaskModelsRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{44}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{46}
|
||||
}
|
||||
|
||||
func (x *TaskModelsRequest) GetTaskId() int64 {
|
||||
@@ -2385,7 +2489,7 @@ type TaskInstructionsRequest struct {
|
||||
|
||||
func (x *TaskInstructionsRequest) Reset() {
|
||||
*x = TaskInstructionsRequest{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2397,7 +2501,7 @@ func (x *TaskInstructionsRequest) String() string {
|
||||
func (*TaskInstructionsRequest) ProtoMessage() {}
|
||||
|
||||
func (x *TaskInstructionsRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[45]
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2410,7 +2514,7 @@ func (x *TaskInstructionsRequest) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskInstructionsRequest.ProtoReflect.Descriptor instead.
|
||||
func (*TaskInstructionsRequest) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{45}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{47}
|
||||
}
|
||||
|
||||
func (x *TaskInstructionsRequest) GetTaskId() int64 {
|
||||
@@ -2430,7 +2534,7 @@ type TaskInstructionsResponse struct {
|
||||
|
||||
func (x *TaskInstructionsResponse) Reset() {
|
||||
*x = TaskInstructionsResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2442,7 +2546,7 @@ func (x *TaskInstructionsResponse) String() string {
|
||||
func (*TaskInstructionsResponse) ProtoMessage() {}
|
||||
|
||||
func (x *TaskInstructionsResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[46]
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2455,7 +2559,7 @@ func (x *TaskInstructionsResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskInstructionsResponse.ProtoReflect.Descriptor instead.
|
||||
func (*TaskInstructionsResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{46}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{48}
|
||||
}
|
||||
|
||||
func (x *TaskInstructionsResponse) GetInstance() string {
|
||||
@@ -2483,7 +2587,7 @@ type TaskModelsResponse struct {
|
||||
|
||||
func (x *TaskModelsResponse) Reset() {
|
||||
*x = TaskModelsResponse{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
mi := &file_state_v1_task_proto_msgTypes[49]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2495,7 +2599,7 @@ func (x *TaskModelsResponse) String() string {
|
||||
func (*TaskModelsResponse) ProtoMessage() {}
|
||||
|
||||
func (x *TaskModelsResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[47]
|
||||
mi := &file_state_v1_task_proto_msgTypes[49]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2508,7 +2612,7 @@ func (x *TaskModelsResponse) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use TaskModelsResponse.ProtoReflect.Descriptor instead.
|
||||
func (*TaskModelsResponse) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{47}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{49}
|
||||
}
|
||||
|
||||
func (x *TaskModelsResponse) GetOrgId() string {
|
||||
@@ -2550,7 +2654,7 @@ type ModelProvider struct {
|
||||
|
||||
func (x *ModelProvider) Reset() {
|
||||
*x = ModelProvider{}
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
mi := &file_state_v1_task_proto_msgTypes[50]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2562,7 +2666,7 @@ func (x *ModelProvider) String() string {
|
||||
func (*ModelProvider) ProtoMessage() {}
|
||||
|
||||
func (x *ModelProvider) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_state_v1_task_proto_msgTypes[48]
|
||||
mi := &file_state_v1_task_proto_msgTypes[50]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2575,7 +2679,7 @@ func (x *ModelProvider) ProtoReflect() protoreflect.Message {
|
||||
|
||||
// Deprecated: Use ModelProvider.ProtoReflect.Descriptor instead.
|
||||
func (*ModelProvider) Descriptor() ([]byte, []int) {
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{48}
|
||||
return file_state_v1_task_proto_rawDescGZIP(), []int{50}
|
||||
}
|
||||
|
||||
func (x *ModelProvider) GetClass() string {
|
||||
@@ -2746,7 +2850,13 @@ const file_state_v1_task_proto_rawDesc = "" +
|
||||
"\bworkflow\x18\x02 \x01(\tR\bworkflow\x12\x1f\n" +
|
||||
"\vinputs_json\x18\x03 \x01(\tR\n" +
|
||||
"inputsJson\x12\x19\n" +
|
||||
"\bcall_key\x18\x04 \x01(\tR\acallKey\"Y\n" +
|
||||
"\bcall_key\x18\x04 \x01(\tR\acallKey\"a\n" +
|
||||
"\x12HandoffTaskRequest\x12\x17\n" +
|
||||
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x1a\n" +
|
||||
"\bworkflow\x18\x02 \x01(\tR\bworkflow\x12\x16\n" +
|
||||
"\x06detail\x18\x03 \x01(\tR\x06detail\"9\n" +
|
||||
"\x13HandoffTaskResponse\x12\"\n" +
|
||||
"\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\"Y\n" +
|
||||
"\x17EnqueueCallTaskResponse\x12\"\n" +
|
||||
"\x04task\x18\x01 \x01(\v2\x0e.state.v1.TaskR\x04task\x12\x1a\n" +
|
||||
"\baccepted\x18\x02 \x01(\bR\baccepted\"c\n" +
|
||||
@@ -2780,7 +2890,7 @@ const file_state_v1_task_proto_rawDesc = "" +
|
||||
"\bbase_url\x18\x02 \x01(\tR\abaseUrl\x12\x1e\n" +
|
||||
"\vapi_key_env\x18\x03 \x01(\tR\tapiKeyEnv\x12$\n" +
|
||||
"\x0eapi_key_engine\x18\x04 \x01(\tR\fapiKeyEngine\x12\x1e\n" +
|
||||
"\vapi_key_key\x18\x05 \x01(\tR\tapiKeyKey2\xe6\x0e\n" +
|
||||
"\vapi_key_key\x18\x05 \x01(\tR\tapiKeyKey2\xb2\x0f\n" +
|
||||
"\vTaskService\x12M\n" +
|
||||
"\fEnqueueIssue\x12\x1d.state.v1.EnqueueIssueRequest\x1a\x1e.state.v1.EnqueueIssueResponse\x12V\n" +
|
||||
"\x0fEnqueueChatTask\x12 .state.v1.EnqueueChatTaskRequest\x1a!.state.v1.EnqueueChatTaskResponse\x12b\n" +
|
||||
@@ -2806,7 +2916,8 @@ const file_state_v1_task_proto_rawDesc = "" +
|
||||
"\aOpenPRs\x12\x18.state.v1.OpenPRsRequest\x1a\x19.state.v1.OpenPRsResponse\x12_\n" +
|
||||
"\x12ClearTerminalTasks\x12#.state.v1.ClearTerminalTasksRequest\x1a$.state.v1.ClearTerminalTasksResponse\x128\n" +
|
||||
"\x05Tasks\x12\x16.state.v1.TasksRequest\x1a\x17.state.v1.TasksResponse\x12V\n" +
|
||||
"\x0fEnqueueCallTask\x12 .state.v1.EnqueueCallTaskRequest\x1a!.state.v1.EnqueueCallTaskResponse\x12_\n" +
|
||||
"\x0fEnqueueCallTask\x12 .state.v1.EnqueueCallTaskRequest\x1a!.state.v1.EnqueueCallTaskResponse\x12J\n" +
|
||||
"\vHandoffTask\x12\x1c.state.v1.HandoffTaskRequest\x1a\x1d.state.v1.HandoffTaskResponse\x12_\n" +
|
||||
"\x12WorkflowCallStatus\x12#.state.v1.WorkflowCallStatusRequest\x1a$.state.v1.WorkflowCallStatusResponseB\xa3\x01\n" +
|
||||
"\fcom.state.v1B\tTaskProtoP\x01ZGgithub.com/samcharles93/archie-core/internal/contracts/state/v1;statev1\xa2\x02\x03SXX\xaa\x02\bState.V1\xca\x02\bState\\V1\xe2\x02\x14State\\V1\\GPBMetadata\xea\x02\tState::V1b\x06proto3"
|
||||
|
||||
@@ -2822,7 +2933,7 @@ func file_state_v1_task_proto_rawDescGZIP() []byte {
|
||||
return file_state_v1_task_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_state_v1_task_proto_msgTypes = make([]protoimpl.MessageInfo, 51)
|
||||
var file_state_v1_task_proto_msgTypes = make([]protoimpl.MessageInfo, 53)
|
||||
var file_state_v1_task_proto_goTypes = []any{
|
||||
(*EnqueueIssueRequest)(nil), // 0: state.v1.EnqueueIssueRequest
|
||||
(*EnqueueIssueResponse)(nil), // 1: state.v1.EnqueueIssueResponse
|
||||
@@ -2865,91 +2976,96 @@ var file_state_v1_task_proto_goTypes = []any{
|
||||
(*TasksRequest)(nil), // 38: state.v1.TasksRequest
|
||||
(*TasksResponse)(nil), // 39: state.v1.TasksResponse
|
||||
(*EnqueueCallTaskRequest)(nil), // 40: state.v1.EnqueueCallTaskRequest
|
||||
(*EnqueueCallTaskResponse)(nil), // 41: state.v1.EnqueueCallTaskResponse
|
||||
(*WorkflowCallStatusRequest)(nil), // 42: state.v1.WorkflowCallStatusRequest
|
||||
(*WorkflowCallStatusResponse)(nil), // 43: state.v1.WorkflowCallStatusResponse
|
||||
(*TaskModelsRequest)(nil), // 44: state.v1.TaskModelsRequest
|
||||
(*TaskInstructionsRequest)(nil), // 45: state.v1.TaskInstructionsRequest
|
||||
(*TaskInstructionsResponse)(nil), // 46: state.v1.TaskInstructionsResponse
|
||||
(*TaskModelsResponse)(nil), // 47: state.v1.TaskModelsResponse
|
||||
(*ModelProvider)(nil), // 48: state.v1.ModelProvider
|
||||
nil, // 49: state.v1.TaskModelsResponse.AliasesEntry
|
||||
nil, // 50: state.v1.TaskModelsResponse.ProvidersEntry
|
||||
(*Task)(nil), // 51: state.v1.Task
|
||||
(*Event)(nil), // 52: state.v1.Event
|
||||
(*timestamppb.Timestamp)(nil), // 53: google.protobuf.Timestamp
|
||||
(*HandoffTaskRequest)(nil), // 41: state.v1.HandoffTaskRequest
|
||||
(*HandoffTaskResponse)(nil), // 42: state.v1.HandoffTaskResponse
|
||||
(*EnqueueCallTaskResponse)(nil), // 43: state.v1.EnqueueCallTaskResponse
|
||||
(*WorkflowCallStatusRequest)(nil), // 44: state.v1.WorkflowCallStatusRequest
|
||||
(*WorkflowCallStatusResponse)(nil), // 45: state.v1.WorkflowCallStatusResponse
|
||||
(*TaskModelsRequest)(nil), // 46: state.v1.TaskModelsRequest
|
||||
(*TaskInstructionsRequest)(nil), // 47: state.v1.TaskInstructionsRequest
|
||||
(*TaskInstructionsResponse)(nil), // 48: state.v1.TaskInstructionsResponse
|
||||
(*TaskModelsResponse)(nil), // 49: state.v1.TaskModelsResponse
|
||||
(*ModelProvider)(nil), // 50: state.v1.ModelProvider
|
||||
nil, // 51: state.v1.TaskModelsResponse.AliasesEntry
|
||||
nil, // 52: state.v1.TaskModelsResponse.ProvidersEntry
|
||||
(*Task)(nil), // 53: state.v1.Task
|
||||
(*Event)(nil), // 54: state.v1.Event
|
||||
(*timestamppb.Timestamp)(nil), // 55: google.protobuf.Timestamp
|
||||
}
|
||||
var file_state_v1_task_proto_depIdxs = []int32{
|
||||
51, // 0: state.v1.ActiveTasksByOriginResponse.tasks:type_name -> state.v1.Task
|
||||
51, // 1: state.v1.UnpostedOutcomesResponse.tasks:type_name -> state.v1.Task
|
||||
51, // 2: state.v1.EnqueueChatTaskResponse.task:type_name -> state.v1.Task
|
||||
51, // 3: state.v1.ClaimNextResponse.task:type_name -> state.v1.Task
|
||||
51, // 4: state.v1.ClaimByIssueResponse.task:type_name -> state.v1.Task
|
||||
51, // 5: state.v1.UpdateRequest.task:type_name -> state.v1.Task
|
||||
52, // 6: state.v1.ArchiveTaskRequest.audit:type_name -> state.v1.Event
|
||||
51, // 7: state.v1.TaskByIssueResponse.task:type_name -> state.v1.Task
|
||||
51, // 8: state.v1.OpenTaskByPRResponse.task:type_name -> state.v1.Task
|
||||
51, // 9: state.v1.TaskByIDResponse.task:type_name -> state.v1.Task
|
||||
51, // 10: state.v1.OpenPRsResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 11: state.v1.TasksRequest.after_updated_at:type_name -> google.protobuf.Timestamp
|
||||
51, // 12: state.v1.TasksResponse.tasks:type_name -> state.v1.Task
|
||||
51, // 13: state.v1.EnqueueCallTaskResponse.task:type_name -> state.v1.Task
|
||||
49, // 14: state.v1.TaskModelsResponse.aliases:type_name -> state.v1.TaskModelsResponse.AliasesEntry
|
||||
50, // 15: state.v1.TaskModelsResponse.providers:type_name -> state.v1.TaskModelsResponse.ProvidersEntry
|
||||
48, // 16: state.v1.TaskModelsResponse.ProvidersEntry.value:type_name -> state.v1.ModelProvider
|
||||
0, // 17: state.v1.TaskService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest
|
||||
8, // 18: state.v1.TaskService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest
|
||||
2, // 19: state.v1.TaskService.ActiveTasksByOrigin:input_type -> state.v1.ActiveTasksByOriginRequest
|
||||
4, // 20: state.v1.TaskService.UnpostedOutcomes:input_type -> state.v1.UnpostedOutcomesRequest
|
||||
6, // 21: state.v1.TaskService.MarkOutcomePosted:input_type -> state.v1.MarkOutcomePostedRequest
|
||||
10, // 22: state.v1.TaskService.ClaimNext:input_type -> state.v1.ClaimNextRequest
|
||||
12, // 23: state.v1.TaskService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest
|
||||
14, // 24: state.v1.TaskService.Transition:input_type -> state.v1.TransitionRequest
|
||||
16, // 25: state.v1.TaskService.Update:input_type -> state.v1.UpdateRequest
|
||||
44, // 26: state.v1.TaskService.TaskModels:input_type -> state.v1.TaskModelsRequest
|
||||
45, // 27: state.v1.TaskService.TaskInstructions:input_type -> state.v1.TaskInstructionsRequest
|
||||
18, // 28: state.v1.TaskService.Requeue:input_type -> state.v1.RequeueRequest
|
||||
20, // 29: state.v1.TaskService.ParkTask:input_type -> state.v1.ParkTaskRequest
|
||||
22, // 30: state.v1.TaskService.RecoverStale:input_type -> state.v1.RecoverStaleRequest
|
||||
24, // 31: state.v1.TaskService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest
|
||||
26, // 32: state.v1.TaskService.RetryTask:input_type -> state.v1.RetryTaskRequest
|
||||
28, // 33: state.v1.TaskService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest
|
||||
30, // 34: state.v1.TaskService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest
|
||||
32, // 35: state.v1.TaskService.TaskByID:input_type -> state.v1.TaskByIDRequest
|
||||
34, // 36: state.v1.TaskService.OpenPRs:input_type -> state.v1.OpenPRsRequest
|
||||
36, // 37: state.v1.TaskService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest
|
||||
38, // 38: state.v1.TaskService.Tasks:input_type -> state.v1.TasksRequest
|
||||
40, // 39: state.v1.TaskService.EnqueueCallTask:input_type -> state.v1.EnqueueCallTaskRequest
|
||||
42, // 40: state.v1.TaskService.WorkflowCallStatus:input_type -> state.v1.WorkflowCallStatusRequest
|
||||
1, // 41: state.v1.TaskService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse
|
||||
9, // 42: state.v1.TaskService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse
|
||||
3, // 43: state.v1.TaskService.ActiveTasksByOrigin:output_type -> state.v1.ActiveTasksByOriginResponse
|
||||
5, // 44: state.v1.TaskService.UnpostedOutcomes:output_type -> state.v1.UnpostedOutcomesResponse
|
||||
7, // 45: state.v1.TaskService.MarkOutcomePosted:output_type -> state.v1.MarkOutcomePostedResponse
|
||||
11, // 46: state.v1.TaskService.ClaimNext:output_type -> state.v1.ClaimNextResponse
|
||||
13, // 47: state.v1.TaskService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse
|
||||
15, // 48: state.v1.TaskService.Transition:output_type -> state.v1.TransitionResponse
|
||||
17, // 49: state.v1.TaskService.Update:output_type -> state.v1.UpdateResponse
|
||||
47, // 50: state.v1.TaskService.TaskModels:output_type -> state.v1.TaskModelsResponse
|
||||
46, // 51: state.v1.TaskService.TaskInstructions:output_type -> state.v1.TaskInstructionsResponse
|
||||
19, // 52: state.v1.TaskService.Requeue:output_type -> state.v1.RequeueResponse
|
||||
21, // 53: state.v1.TaskService.ParkTask:output_type -> state.v1.ParkTaskResponse
|
||||
23, // 54: state.v1.TaskService.RecoverStale:output_type -> state.v1.RecoverStaleResponse
|
||||
25, // 55: state.v1.TaskService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse
|
||||
27, // 56: state.v1.TaskService.RetryTask:output_type -> state.v1.RetryTaskResponse
|
||||
29, // 57: state.v1.TaskService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse
|
||||
31, // 58: state.v1.TaskService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse
|
||||
33, // 59: state.v1.TaskService.TaskByID:output_type -> state.v1.TaskByIDResponse
|
||||
35, // 60: state.v1.TaskService.OpenPRs:output_type -> state.v1.OpenPRsResponse
|
||||
37, // 61: state.v1.TaskService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse
|
||||
39, // 62: state.v1.TaskService.Tasks:output_type -> state.v1.TasksResponse
|
||||
41, // 63: state.v1.TaskService.EnqueueCallTask:output_type -> state.v1.EnqueueCallTaskResponse
|
||||
43, // 64: state.v1.TaskService.WorkflowCallStatus:output_type -> state.v1.WorkflowCallStatusResponse
|
||||
41, // [41:65] is the sub-list for method output_type
|
||||
17, // [17:41] is the sub-list for method input_type
|
||||
17, // [17:17] is the sub-list for extension type_name
|
||||
17, // [17:17] is the sub-list for extension extendee
|
||||
0, // [0:17] is the sub-list for field type_name
|
||||
53, // 0: state.v1.ActiveTasksByOriginResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 1: state.v1.UnpostedOutcomesResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 2: state.v1.EnqueueChatTaskResponse.task:type_name -> state.v1.Task
|
||||
53, // 3: state.v1.ClaimNextResponse.task:type_name -> state.v1.Task
|
||||
53, // 4: state.v1.ClaimByIssueResponse.task:type_name -> state.v1.Task
|
||||
53, // 5: state.v1.UpdateRequest.task:type_name -> state.v1.Task
|
||||
54, // 6: state.v1.ArchiveTaskRequest.audit:type_name -> state.v1.Event
|
||||
53, // 7: state.v1.TaskByIssueResponse.task:type_name -> state.v1.Task
|
||||
53, // 8: state.v1.OpenTaskByPRResponse.task:type_name -> state.v1.Task
|
||||
53, // 9: state.v1.TaskByIDResponse.task:type_name -> state.v1.Task
|
||||
53, // 10: state.v1.OpenPRsResponse.tasks:type_name -> state.v1.Task
|
||||
55, // 11: state.v1.TasksRequest.after_updated_at:type_name -> google.protobuf.Timestamp
|
||||
53, // 12: state.v1.TasksResponse.tasks:type_name -> state.v1.Task
|
||||
53, // 13: state.v1.HandoffTaskResponse.task:type_name -> state.v1.Task
|
||||
53, // 14: state.v1.EnqueueCallTaskResponse.task:type_name -> state.v1.Task
|
||||
51, // 15: state.v1.TaskModelsResponse.aliases:type_name -> state.v1.TaskModelsResponse.AliasesEntry
|
||||
52, // 16: state.v1.TaskModelsResponse.providers:type_name -> state.v1.TaskModelsResponse.ProvidersEntry
|
||||
50, // 17: state.v1.TaskModelsResponse.ProvidersEntry.value:type_name -> state.v1.ModelProvider
|
||||
0, // 18: state.v1.TaskService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest
|
||||
8, // 19: state.v1.TaskService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest
|
||||
2, // 20: state.v1.TaskService.ActiveTasksByOrigin:input_type -> state.v1.ActiveTasksByOriginRequest
|
||||
4, // 21: state.v1.TaskService.UnpostedOutcomes:input_type -> state.v1.UnpostedOutcomesRequest
|
||||
6, // 22: state.v1.TaskService.MarkOutcomePosted:input_type -> state.v1.MarkOutcomePostedRequest
|
||||
10, // 23: state.v1.TaskService.ClaimNext:input_type -> state.v1.ClaimNextRequest
|
||||
12, // 24: state.v1.TaskService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest
|
||||
14, // 25: state.v1.TaskService.Transition:input_type -> state.v1.TransitionRequest
|
||||
16, // 26: state.v1.TaskService.Update:input_type -> state.v1.UpdateRequest
|
||||
46, // 27: state.v1.TaskService.TaskModels:input_type -> state.v1.TaskModelsRequest
|
||||
47, // 28: state.v1.TaskService.TaskInstructions:input_type -> state.v1.TaskInstructionsRequest
|
||||
18, // 29: state.v1.TaskService.Requeue:input_type -> state.v1.RequeueRequest
|
||||
20, // 30: state.v1.TaskService.ParkTask:input_type -> state.v1.ParkTaskRequest
|
||||
22, // 31: state.v1.TaskService.RecoverStale:input_type -> state.v1.RecoverStaleRequest
|
||||
24, // 32: state.v1.TaskService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest
|
||||
26, // 33: state.v1.TaskService.RetryTask:input_type -> state.v1.RetryTaskRequest
|
||||
28, // 34: state.v1.TaskService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest
|
||||
30, // 35: state.v1.TaskService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest
|
||||
32, // 36: state.v1.TaskService.TaskByID:input_type -> state.v1.TaskByIDRequest
|
||||
34, // 37: state.v1.TaskService.OpenPRs:input_type -> state.v1.OpenPRsRequest
|
||||
36, // 38: state.v1.TaskService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest
|
||||
38, // 39: state.v1.TaskService.Tasks:input_type -> state.v1.TasksRequest
|
||||
40, // 40: state.v1.TaskService.EnqueueCallTask:input_type -> state.v1.EnqueueCallTaskRequest
|
||||
41, // 41: state.v1.TaskService.HandoffTask:input_type -> state.v1.HandoffTaskRequest
|
||||
44, // 42: state.v1.TaskService.WorkflowCallStatus:input_type -> state.v1.WorkflowCallStatusRequest
|
||||
1, // 43: state.v1.TaskService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse
|
||||
9, // 44: state.v1.TaskService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse
|
||||
3, // 45: state.v1.TaskService.ActiveTasksByOrigin:output_type -> state.v1.ActiveTasksByOriginResponse
|
||||
5, // 46: state.v1.TaskService.UnpostedOutcomes:output_type -> state.v1.UnpostedOutcomesResponse
|
||||
7, // 47: state.v1.TaskService.MarkOutcomePosted:output_type -> state.v1.MarkOutcomePostedResponse
|
||||
11, // 48: state.v1.TaskService.ClaimNext:output_type -> state.v1.ClaimNextResponse
|
||||
13, // 49: state.v1.TaskService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse
|
||||
15, // 50: state.v1.TaskService.Transition:output_type -> state.v1.TransitionResponse
|
||||
17, // 51: state.v1.TaskService.Update:output_type -> state.v1.UpdateResponse
|
||||
49, // 52: state.v1.TaskService.TaskModels:output_type -> state.v1.TaskModelsResponse
|
||||
48, // 53: state.v1.TaskService.TaskInstructions:output_type -> state.v1.TaskInstructionsResponse
|
||||
19, // 54: state.v1.TaskService.Requeue:output_type -> state.v1.RequeueResponse
|
||||
21, // 55: state.v1.TaskService.ParkTask:output_type -> state.v1.ParkTaskResponse
|
||||
23, // 56: state.v1.TaskService.RecoverStale:output_type -> state.v1.RecoverStaleResponse
|
||||
25, // 57: state.v1.TaskService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse
|
||||
27, // 58: state.v1.TaskService.RetryTask:output_type -> state.v1.RetryTaskResponse
|
||||
29, // 59: state.v1.TaskService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse
|
||||
31, // 60: state.v1.TaskService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse
|
||||
33, // 61: state.v1.TaskService.TaskByID:output_type -> state.v1.TaskByIDResponse
|
||||
35, // 62: state.v1.TaskService.OpenPRs:output_type -> state.v1.OpenPRsResponse
|
||||
37, // 63: state.v1.TaskService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse
|
||||
39, // 64: state.v1.TaskService.Tasks:output_type -> state.v1.TasksResponse
|
||||
43, // 65: state.v1.TaskService.EnqueueCallTask:output_type -> state.v1.EnqueueCallTaskResponse
|
||||
42, // 66: state.v1.TaskService.HandoffTask:output_type -> state.v1.HandoffTaskResponse
|
||||
45, // 67: state.v1.TaskService.WorkflowCallStatus:output_type -> state.v1.WorkflowCallStatusResponse
|
||||
43, // [43:68] is the sub-list for method output_type
|
||||
18, // [18:43] is the sub-list for method input_type
|
||||
18, // [18:18] is the sub-list for extension type_name
|
||||
18, // [18:18] is the sub-list for extension extendee
|
||||
0, // [0:18] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_state_v1_task_proto_init() }
|
||||
@@ -2964,7 +3080,7 @@ func file_state_v1_task_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_state_v1_task_proto_rawDesc), len(file_state_v1_task_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 51,
|
||||
NumMessages: 53,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -211,8 +211,12 @@ func (x *EventsSinceResponse) GetEvents() []*Event {
|
||||
}
|
||||
|
||||
type TaskEventsRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
|
||||
// transcript selects the agent_transcript entries of one attempt instead of
|
||||
// the timeline, which leaves them out.
|
||||
Transcript bool `protobuf:"varint,2,opt,name=transcript,proto3" json:"transcript,omitempty"`
|
||||
Attempt int64 `protobuf:"varint,3,opt,name=attempt,proto3" json:"attempt,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -254,6 +258,20 @@ func (x *TaskEventsRequest) GetTaskId() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *TaskEventsRequest) GetTranscript() bool {
|
||||
if x != nil {
|
||||
return x.Transcript
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *TaskEventsRequest) GetAttempt() int64 {
|
||||
if x != nil {
|
||||
return x.Attempt
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type TaskEventsResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Events []*Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"`
|
||||
@@ -311,9 +329,13 @@ const file_state_v1_task_event_proto_rawDesc = "" +
|
||||
"\bsince_id\x18\x01 \x01(\tR\asinceId\x12\x14\n" +
|
||||
"\x05limit\x18\x02 \x01(\x03R\x05limit\">\n" +
|
||||
"\x13EventsSinceResponse\x12'\n" +
|
||||
"\x06events\x18\x01 \x03(\v2\x0f.state.v1.EventR\x06events\",\n" +
|
||||
"\x06events\x18\x01 \x03(\v2\x0f.state.v1.EventR\x06events\"f\n" +
|
||||
"\x11TaskEventsRequest\x12\x17\n" +
|
||||
"\atask_id\x18\x01 \x01(\x03R\x06taskId\"=\n" +
|
||||
"\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x1e\n" +
|
||||
"\n" +
|
||||
"transcript\x18\x02 \x01(\bR\n" +
|
||||
"transcript\x12\x18\n" +
|
||||
"\aattempt\x18\x03 \x01(\x03R\aattempt\"=\n" +
|
||||
"\x12TaskEventsResponse\x12'\n" +
|
||||
"\x06events\x18\x01 \x03(\v2\x0f.state.v1.EventR\x06events2\xf3\x01\n" +
|
||||
"\x10TaskEventService\x12J\n" +
|
||||
|
||||
@@ -42,6 +42,7 @@ const (
|
||||
TaskService_ClearTerminalTasks_FullMethodName = "/state.v1.TaskService/ClearTerminalTasks"
|
||||
TaskService_Tasks_FullMethodName = "/state.v1.TaskService/Tasks"
|
||||
TaskService_EnqueueCallTask_FullMethodName = "/state.v1.TaskService/EnqueueCallTask"
|
||||
TaskService_HandoffTask_FullMethodName = "/state.v1.TaskService/HandoffTask"
|
||||
TaskService_WorkflowCallStatus_FullMethodName = "/state.v1.TaskService/WorkflowCallStatus"
|
||||
)
|
||||
|
||||
@@ -84,6 +85,9 @@ type TaskServiceClient interface {
|
||||
// (docs/prds/workflow-calls.md). CallStatus re-checks the parent-child
|
||||
// relation server-side, so the grant only names the caller.
|
||||
EnqueueCallTask(ctx context.Context, in *EnqueueCallTaskRequest, opts ...grpc.CallOption) (*EnqueueCallTaskResponse, error)
|
||||
// HandoffTask completes a running run and starts its linked successor on
|
||||
// the same work item under another workflow.
|
||||
HandoffTask(ctx context.Context, in *HandoffTaskRequest, opts ...grpc.CallOption) (*HandoffTaskResponse, error)
|
||||
WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error)
|
||||
}
|
||||
|
||||
@@ -325,6 +329,16 @@ func (c *taskServiceClient) EnqueueCallTask(ctx context.Context, in *EnqueueCall
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *taskServiceClient) HandoffTask(ctx context.Context, in *HandoffTaskRequest, opts ...grpc.CallOption) (*HandoffTaskResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(HandoffTaskResponse)
|
||||
err := c.cc.Invoke(ctx, TaskService_HandoffTask_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *taskServiceClient) WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(WorkflowCallStatusResponse)
|
||||
@@ -374,6 +388,9 @@ type TaskServiceServer interface {
|
||||
// (docs/prds/workflow-calls.md). CallStatus re-checks the parent-child
|
||||
// relation server-side, so the grant only names the caller.
|
||||
EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error)
|
||||
// HandoffTask completes a running run and starts its linked successor on
|
||||
// the same work item under another workflow.
|
||||
HandoffTask(context.Context, *HandoffTaskRequest) (*HandoffTaskResponse, error)
|
||||
WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error)
|
||||
mustEmbedUnimplementedTaskServiceServer()
|
||||
}
|
||||
@@ -454,6 +471,9 @@ func (UnimplementedTaskServiceServer) Tasks(context.Context, *TasksRequest) (*Ta
|
||||
func (UnimplementedTaskServiceServer) EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method EnqueueCallTask not implemented")
|
||||
}
|
||||
func (UnimplementedTaskServiceServer) HandoffTask(context.Context, *HandoffTaskRequest) (*HandoffTaskResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method HandoffTask not implemented")
|
||||
}
|
||||
func (UnimplementedTaskServiceServer) WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method WorkflowCallStatus not implemented")
|
||||
}
|
||||
@@ -892,6 +912,24 @@ func _TaskService_EnqueueCallTask_Handler(srv interface{}, ctx context.Context,
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _TaskService_HandoffTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(HandoffTaskRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(TaskServiceServer).HandoffTask(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: TaskService_HandoffTask_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(TaskServiceServer).HandoffTask(ctx, req.(*HandoffTaskRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _TaskService_WorkflowCallStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(WorkflowCallStatusRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -1009,6 +1047,10 @@ var TaskService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "EnqueueCallTask",
|
||||
Handler: _TaskService_EnqueueCallTask_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "HandoffTask",
|
||||
Handler: _TaskService_HandoffTask_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "WorkflowCallStatus",
|
||||
Handler: _TaskService_WorkflowCallStatus_Handler,
|
||||
|
||||
@@ -229,9 +229,13 @@ type Task struct {
|
||||
// recorded at the park site; empty when the park has no known fix.
|
||||
ParkBlocker string `protobuf:"bytes,48,opt,name=park_blocker,json=parkBlocker,proto3" json:"park_blocker,omitempty"`
|
||||
// plan_document is the structured plan (JSON) plan was rendered from.
|
||||
PlanDocument string `protobuf:"bytes,50,opt,name=plan_document,json=planDocument,proto3" json:"plan_document,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
PlanDocument string `protobuf:"bytes,50,opt,name=plan_document,json=planDocument,proto3" json:"plan_document,omitempty"`
|
||||
// handoff_from_task_id is the run that handed off to this one; 0 when none.
|
||||
HandoffFromTaskId int64 `protobuf:"varint,51,opt,name=handoff_from_task_id,json=handoffFromTaskId,proto3" json:"handoff_from_task_id,omitempty"`
|
||||
// handoff_to_task_id is the run this one handed off to; 0 when none.
|
||||
HandoffToTaskId int64 `protobuf:"varint,52,opt,name=handoff_to_task_id,json=handoffToTaskId,proto3" json:"handoff_to_task_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Task) Reset() {
|
||||
@@ -608,6 +612,20 @@ func (x *Task) GetPlanDocument() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Task) GetHandoffFromTaskId() int64 {
|
||||
if x != nil {
|
||||
return x.HandoffFromTaskId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Task) GetHandoffToTaskId() int64 {
|
||||
if x != nil {
|
||||
return x.HandoffToTaskId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Event mirrors internal/events.Event. Data is carried as a JSON object
|
||||
// string (matching the store's own on-disk representation) rather than
|
||||
// google.protobuf.Struct, to stay a direct mirror of the existing column.
|
||||
@@ -784,7 +802,7 @@ const file_state_v1_types_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"created_at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x129\n" +
|
||||
"\n" +
|
||||
"updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\x91\r\n" +
|
||||
"updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\xef\r\n" +
|
||||
"\x04Task\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x14\n" +
|
||||
"\x05owner\x18\x02 \x01(\tR\x05owner\x12\x12\n" +
|
||||
@@ -849,7 +867,9 @@ const file_state_v1_types_proto_rawDesc = "" +
|
||||
"\x11binding_signature\x18. \x01(\tR\x10bindingSignature\x12!\n" +
|
||||
"\fbinding_addr\x18/ \x01(\tR\vbindingAddr\x12!\n" +
|
||||
"\fpark_blocker\x180 \x01(\tR\vparkBlocker\x12#\n" +
|
||||
"\rplan_document\x182 \x01(\tR\fplanDocumentJ\x04\b1\x102R\tplan_view\"\xf8\x02\n" +
|
||||
"\rplan_document\x182 \x01(\tR\fplanDocument\x12/\n" +
|
||||
"\x14handoff_from_task_id\x183 \x01(\x03R\x11handoffFromTaskId\x12+\n" +
|
||||
"\x12handoff_to_task_id\x184 \x01(\x03R\x0fhandoffToTaskIdJ\x04\b1\x102R\tplan_view\"\xf8\x02\n" +
|
||||
"\x05Event\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x12*\n" +
|
||||
"\x02at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x12\n" +
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The systemd watchdog beats only while StalestLoop is fresh, so a cycle that
|
||||
// doesn't stamp it gets archied killed shortly after every start.
|
||||
func TestCycleMarksPass(t *testing.T) {
|
||||
d := &Daemon{}
|
||||
d.Cycle(context.Background())
|
||||
if loop, at := d.StalestLoop(); loop != "cycle" || at.IsZero() {
|
||||
t.Fatalf("StalestLoop() = %q, %v; want a cycle pass", loop, at)
|
||||
}
|
||||
}
|
||||
+23
-18
@@ -240,10 +240,10 @@ type Daemon struct {
|
||||
// to use.
|
||||
running runningTasks
|
||||
|
||||
// lastPollAt maps each poll loop (an identity ID, or "" for the root
|
||||
// loop) to when its latest pass began, as Unix nanoseconds. LastPollAt
|
||||
// reports the oldest, so one wedged loop is not hidden by a healthy one.
|
||||
lastPollAt sync.Map
|
||||
// loopPasses maps each run loop ("cycle", "drain") to when its latest
|
||||
// pass began, as Unix nanoseconds. StalestLoop reports the oldest, so one
|
||||
// wedged loop isn't hidden by a healthy one.
|
||||
loopPasses sync.Map
|
||||
}
|
||||
|
||||
// IssueSource is one forge connection's repositories as the identity
|
||||
@@ -389,6 +389,7 @@ func (d *Daemon) drainLoop(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
d.markPass("drain")
|
||||
d.drainNATS(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -489,6 +490,7 @@ func (d *Daemon) RunOnce(ctx context.Context) {
|
||||
// tasks; maintenance runs as built-in schedules. Draining queued tasks is the caller's job
|
||||
// (drainLoop in Run, drainNATS in RunOnce) so there is one drainer.
|
||||
func (d *Daemon) Cycle(ctx context.Context) {
|
||||
d.markPass("cycle")
|
||||
d.dispatchBindings(ctx)
|
||||
d.drainReactions(ctx)
|
||||
}
|
||||
@@ -1205,7 +1207,6 @@ func (d *taskDispatcher) Wait() {
|
||||
// afresh each cycle so a rotated credential or a new connection applies to
|
||||
// the next poll.
|
||||
func (d *Daemon) poll(ctx context.Context) error {
|
||||
d.markPoll("")
|
||||
// Webhook intake replaces polling; an empty pass is not a failure.
|
||||
if d.Cfg.Get().Forge.Intake == config.ForgeIntakeWebhook {
|
||||
return nil
|
||||
@@ -1752,7 +1753,9 @@ func (d *Daemon) cleanupTerminalTaskWorktree(ctx context.Context, task *workflow
|
||||
d.Log.WarnContext(ctx, "terminal worktree cleanup task lookup failed", "task", task.ID, "err", err)
|
||||
return
|
||||
}
|
||||
if latest == nil {
|
||||
// A run that handed off shares its work item's worktree with its
|
||||
// successor, which owns it from here.
|
||||
if latest == nil || latest.HandoffToTaskID != 0 {
|
||||
return
|
||||
}
|
||||
// Settled statuses. Keep the worktree while a PR exists.
|
||||
@@ -2603,26 +2606,28 @@ func (d *Daemon) allowConcurrentForTask(task *workflow.Task) bool {
|
||||
return ok && repo.AllowConcurrent
|
||||
}
|
||||
|
||||
// LastPollAt reports when the least recently polled loop last began a pass,
|
||||
// or the zero time when no pass has started yet.
|
||||
func (d *Daemon) LastPollAt() time.Time {
|
||||
// StalestLoop reports the run loop that least recently began a pass and when,
|
||||
// or the zero time when no loop has started yet. The systemd watchdog beats
|
||||
// only while this is fresh, so every loop Run starts must mark its passes.
|
||||
func (d *Daemon) StalestLoop() (string, time.Time) {
|
||||
var loop string
|
||||
var oldest int64
|
||||
d.lastPollAt.Range(func(_, v any) bool {
|
||||
if ns, ok := v.(int64); ok && (oldest == 0 || ns < oldest) {
|
||||
oldest = ns
|
||||
d.loopPasses.Range(func(k, v any) bool {
|
||||
name, okName := k.(string)
|
||||
if ns, ok := v.(int64); ok && okName && (oldest == 0 || ns < oldest) {
|
||||
loop, oldest = name, ns
|
||||
}
|
||||
return true
|
||||
})
|
||||
if oldest == 0 {
|
||||
return time.Time{}
|
||||
return "", time.Time{}
|
||||
}
|
||||
return time.Unix(0, oldest).UTC()
|
||||
return loop, time.Unix(0, oldest).UTC()
|
||||
}
|
||||
|
||||
// markPoll stamps the start of a poll pass for one loop, so a hung pass shows
|
||||
// as stale.
|
||||
func (d *Daemon) markPoll(loop string) {
|
||||
d.lastPollAt.Store(loop, time.Now().UnixNano())
|
||||
// markPass stamps the start of one loop's pass, so a hung pass shows as stale.
|
||||
func (d *Daemon) markPass(loop string) {
|
||||
d.loopPasses.Store(loop, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
// errContainerExited is the cancellation cause when a task's agent container
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package access
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/domain/org"
|
||||
|
||||
// CanaryGrantID is the ID the canary's scoped grant is known by in the policy
|
||||
// store and in denial records. A stored policy must not reuse it: the store's
|
||||
// seeding and the reset command overwrite shipped IDs, and this one is
|
||||
// installed by the operator from CanaryGrantPolicy's text.
|
||||
const CanaryGrantID = "org-canary-grant"
|
||||
|
||||
// CanaryGrantForbidID is the matching forbid's ID: the grant only scopes the
|
||||
// canary if everything else it could reach is forbidden, because the identity
|
||||
// may also carry a role (API-created service accounts are assigned developer)
|
||||
// whose shipped policy permits broadly within the org. A forbid wins within
|
||||
// the level, so the pair scopes the identity regardless of its role.
|
||||
const CanaryGrantForbidID = "org-canary-grant-forbid"
|
||||
|
||||
// canaryGrantActions is the exact action surface the canary needs, as one
|
||||
// Cedar condition shared by the grant's permit and its forbid.
|
||||
func canaryGrantActions() string {
|
||||
return `(
|
||||
(action == Archie::Action::"read" && ["dashboard", "task"].contains(resource.kind)) ||
|
||||
(action == Archie::Action::"read" && resource == Archie::Object::"update-settings") ||
|
||||
(action == Archie::Action::"update" && resource == Archie::Object::"update") ||
|
||||
(action == Archie::Action::"manage_identities" && resource == Archie::Object::"update-settings")
|
||||
)`
|
||||
}
|
||||
|
||||
func canaryPrincipal(identityID string) string {
|
||||
return `principal == Archie::Identity::"` + identityID + `"`
|
||||
}
|
||||
|
||||
// CanaryGrantPolicy is the grant a CI canary carries instead of instance
|
||||
// admin: exactly one named identity may read the dashboard's signal surface
|
||||
// (chat update, alerts, logs, tasks), read and write the update-settings
|
||||
// resource, and trigger an update install or deferral. Install it together
|
||||
// with CanaryGrantForbidPolicy, which forbids the same identity from
|
||||
// everything else. Every clause is guarded by the resource belonging to the
|
||||
// principal's own org, which the engine enforces structurally anyway.
|
||||
func CanaryGrantPolicy(orgID org.OrgID, identityID string) Policy {
|
||||
text := `permit(principal, action, resource) when {
|
||||
resource.org == principal.org &&
|
||||
` + canaryPrincipal(identityID) + ` &&
|
||||
` + canaryGrantActions() + `
|
||||
};`
|
||||
return Policy{ID: CanaryGrantID, Level: LevelOrg, OrgID: orgID, Text: text}
|
||||
}
|
||||
|
||||
// CanaryGrantForbidPolicy forbids the canary identity from everything outside
|
||||
// CanaryGrantPolicy's surface, so a role assigned to the identity (service
|
||||
// accounts created through the API carry developer) cannot widen it.
|
||||
func CanaryGrantForbidPolicy(orgID org.OrgID, identityID string) Policy {
|
||||
text := `forbid(principal, action, resource) when {
|
||||
resource.org == principal.org &&
|
||||
` + canaryPrincipal(identityID) + ` &&
|
||||
!` + canaryGrantActions() + `
|
||||
};`
|
||||
return Policy{ID: CanaryGrantForbidID, Level: LevelOrg, OrgID: orgID, Text: text}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// TestCanaryGrantPolicy pins the shape of the canary grant: it names exactly
|
||||
// the one identity it is built for, scoped to the org it serves, so a token
|
||||
// carrying it cannot act as anyone else or reach another org.
|
||||
func TestCanaryGrantPolicy(t *testing.T) {
|
||||
p := CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
|
||||
if err := p.Validate(); err != nil {
|
||||
t.Fatalf("Validate: %v", err)
|
||||
}
|
||||
if p.ID != CanaryGrantID || p.Level != LevelOrg || p.OrgID != org.DefaultOrgID {
|
||||
t.Fatalf("policy = %+v, want ID %q at org level in %q", p, CanaryGrantID, org.DefaultOrgID)
|
||||
}
|
||||
if !strings.Contains(p.Text, `principal == Archie::Identity::"canary-svc"`) {
|
||||
t.Fatalf("text does not name the canary identity:\n%s", p.Text)
|
||||
}
|
||||
other := CanaryGrantPolicy(org.DefaultOrgID, "another")
|
||||
if strings.Contains(other.Text, "canary-svc") || !strings.Contains(other.Text, `Archie::Identity::"another"`) {
|
||||
t.Fatalf("grant for another identity must name that identity only:\n%s", other.Text)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanaryGrantForbidPolicy pins the forbid that keeps a role assigned to
|
||||
// the canary identity from widening the grant: it names the same identity and
|
||||
// negates exactly the permit's action surface.
|
||||
func TestCanaryGrantForbidPolicy(t *testing.T) {
|
||||
permit := CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
|
||||
forbid := CanaryGrantForbidPolicy(org.DefaultOrgID, "canary-svc")
|
||||
if err := forbid.Validate(); err != nil {
|
||||
t.Fatalf("Validate: %v", err)
|
||||
}
|
||||
if forbid.ID != CanaryGrantForbidID || forbid.Level != LevelOrg || forbid.OrgID != org.DefaultOrgID {
|
||||
t.Fatalf("forbid = %+v, want ID %q at org level in %q", forbid, CanaryGrantForbidID, org.DefaultOrgID)
|
||||
}
|
||||
if !strings.HasPrefix(forbid.Text, "forbid(") {
|
||||
t.Fatalf("forbid text must be a forbid:\n%s", forbid.Text)
|
||||
}
|
||||
if !strings.Contains(forbid.Text, `principal == Archie::Identity::"canary-svc"`) {
|
||||
t.Fatalf("forbid does not name the canary identity:\n%s", forbid.Text)
|
||||
}
|
||||
// The forbid must negate the permit's surface, not the permit itself.
|
||||
permitBody := strings.TrimSuffix(strings.SplitN(permit.Text, "when {", 2)[1], "};")
|
||||
forbidBody := strings.TrimSuffix(strings.SplitN(forbid.Text, "when {", 2)[1], "};")
|
||||
if !strings.Contains(forbidBody, "!"+canaryGrantActions()) {
|
||||
t.Fatalf("forbid does not negate the grant's action surface:\npermit:%s\nforbid:%s", permitBody, forbidBody)
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,13 @@ import "context"
|
||||
|
||||
// Runner executes one autonomous stage against an already prepared workspace.
|
||||
type Runner interface {
|
||||
// report, when non-nil, is notified once per completed tool call.
|
||||
Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error)
|
||||
// report receives what the run does as it happens; its zero value
|
||||
// discards everything.
|
||||
Run(ctx context.Context, workspace string, req Request, report Reporter) (Result, error)
|
||||
}
|
||||
|
||||
// ToolCallReport is one completed tool invocation, reported through a
|
||||
// ToolCallReporter.
|
||||
// Reporter.
|
||||
type ToolCallReport struct {
|
||||
Tool string
|
||||
// Detail is a clipped one-line summary: the tool's result, or
|
||||
@@ -18,6 +19,67 @@ type ToolCallReport struct {
|
||||
Failed bool
|
||||
}
|
||||
|
||||
// ToolCallReporter receives one ToolCallReport per completed tool call. A nil
|
||||
// reporter is valid and reports nothing.
|
||||
type ToolCallReporter func(ToolCallReport)
|
||||
// Reporter receives a run's activity. Either func may be nil.
|
||||
type Reporter struct {
|
||||
// ToolCall is notified once per completed tool call.
|
||||
ToolCall func(ToolCallReport)
|
||||
// Transcript is notified of each transcript entry, in order.
|
||||
Transcript func(TranscriptEntry)
|
||||
}
|
||||
|
||||
// ReportToolCall forwards report to r.ToolCall, if set.
|
||||
func (r Reporter) ReportToolCall(report ToolCallReport) {
|
||||
if r.ToolCall != nil {
|
||||
r.ToolCall(report)
|
||||
}
|
||||
}
|
||||
|
||||
// ReportTranscript forwards entry to r.Transcript, if set.
|
||||
func (r Reporter) ReportTranscript(entry TranscriptEntry) {
|
||||
if r.Transcript != nil {
|
||||
r.Transcript(entry)
|
||||
}
|
||||
}
|
||||
|
||||
// Transcript entry kinds.
|
||||
const (
|
||||
TranscriptSystem = "system" // Text: the system prompt
|
||||
TranscriptUser = "user" // Text: the mission, or input the loop added later
|
||||
TranscriptModel = "model" // Reasoning, Text and ToolCalls: one model response
|
||||
TranscriptTool = "tool" // one tool call's arguments and result
|
||||
TranscriptCompaction = "compaction" // Text: the summary that replaced the history
|
||||
)
|
||||
|
||||
// TranscriptEntry is one ordered item of an agent run's conversation. Text
|
||||
// fields are redacted and clipped; a *Bytes field holds the full size when its
|
||||
// field was clipped.
|
||||
type TranscriptEntry struct {
|
||||
Seq int `json:"seq"`
|
||||
Kind string `json:"kind"`
|
||||
Text string `json:"text,omitempty"`
|
||||
TextBytes int `json:"text_bytes,omitempty"`
|
||||
ToolCalls []TranscriptToolCall `json:"tool_calls,omitempty"`
|
||||
|
||||
Reasoning string `json:"reasoning,omitempty"`
|
||||
ReasoningBytes int `json:"reasoning_bytes,omitempty"`
|
||||
|
||||
CallID string `json:"call_id,omitempty"`
|
||||
Tool string `json:"tool,omitempty"`
|
||||
Args string `json:"args,omitempty"`
|
||||
ArgsBytes int `json:"args_bytes,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
OutputBytes int `json:"output_bytes,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
|
||||
FinishReason string `json:"finish_reason,omitempty"`
|
||||
Usage *Usage `json:"usage,omitempty"`
|
||||
LatencyMS int64 `json:"latency_ms,omitempty"`
|
||||
}
|
||||
|
||||
// TranscriptToolCall is one tool call a model response requested.
|
||||
type TranscriptToolCall struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Args string `json:"args,omitempty"`
|
||||
ArgsBytes int `json:"args_bytes,omitempty"`
|
||||
}
|
||||
@@ -13,6 +13,10 @@ import (
|
||||
// registry's activity surface and events.
|
||||
const ActionToolCalled = "tool.called"
|
||||
|
||||
// ActionSummary is the Action.Type recorded for the pass's final text: the
|
||||
// report a definition pass produces, kept inspectable in the activity trail.
|
||||
const ActionSummary = "pass.summary"
|
||||
|
||||
// defaultDefinitionMaxSteps bounds the model/tool loop of one definition pass.
|
||||
const defaultDefinitionMaxSteps = 10
|
||||
|
||||
@@ -84,7 +88,7 @@ func (e *DefinitionEngine) Pass(ctx context.Context, in PassInput) (PassResult,
|
||||
return PassResult{}, err
|
||||
}
|
||||
|
||||
actions := make([]Action, 0, len(res.ToolCalls))
|
||||
actions := make([]Action, 0, len(res.ToolCalls)+1)
|
||||
for _, call := range res.ToolCalls {
|
||||
actions = append(actions, Action{
|
||||
At: e.host.Clock.Now(),
|
||||
@@ -93,6 +97,14 @@ func (e *DefinitionEngine) Pass(ctx context.Context, in PassInput) (PassResult,
|
||||
Reason: in.Reason,
|
||||
})
|
||||
}
|
||||
if summary := strings.TrimSpace(res.Text); summary != "" {
|
||||
actions = append(actions, Action{
|
||||
At: e.host.Clock.Now(),
|
||||
Type: ActionSummary,
|
||||
Detail: summary,
|
||||
Reason: in.Reason,
|
||||
})
|
||||
}
|
||||
return PassResult{Actions: actions}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -139,3 +139,31 @@ func TestInstructionOnlyRegistrarViewFiltered(t *testing.T) {
|
||||
t.Error("registrar view has no clock; time is always bound")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefinitionPassRecordsSummary pins that a pass's final text is recorded
|
||||
// as a pass.summary action, so a definition's report stays inspectable in the
|
||||
// activity trail instead of being dropped when the model returns.
|
||||
func TestDefinitionPassRecordsSummary(t *testing.T) {
|
||||
llm := &fakeLLM{}
|
||||
registry := NewRegistry(fullHost(llm))
|
||||
engine := NewDefinitionEngine(instructionOnlyDefinition())
|
||||
if err := registry.Register(engine); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := engine.Pass(t.Context(), PassInput{Reason: "test"})
|
||||
if err != nil {
|
||||
t.Fatalf("pass: %v", err)
|
||||
}
|
||||
var summary *Action
|
||||
for i, a := range res.Actions {
|
||||
if a.Type == ActionSummary {
|
||||
summary = &res.Actions[i]
|
||||
}
|
||||
}
|
||||
if summary == nil {
|
||||
t.Fatalf("no %s action recorded; actions: %+v", ActionSummary, res.Actions)
|
||||
}
|
||||
if summary.Detail != "done" {
|
||||
t.Errorf("summary detail = %q, want the model's final text %q", summary.Detail, "done")
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@ func mustKey(encoded string) ed25519.PublicKey {
|
||||
func DefaultCatalogue() Source {
|
||||
return Source{
|
||||
Reference: "git.catlow.cloud/sam/archipelago/catalogue",
|
||||
Key: mustKey("YL4nvn07uq/5mXZOt9cEmLYu/kB6C2+MLTnbHyoX4Pw="),
|
||||
Key: mustKey("PLouShOzvRqy1QbYaJplaM41/ulgKFN8ZQ7g1rI02Fc="),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// BindingStore persists bindings and their draft -> pending_approval ->
|
||||
// armed states.
|
||||
type BindingStore interface {
|
||||
InsertBinding(ctx context.Context, b binding.Binding) (string, error)
|
||||
GetBinding(ctx context.Context, id string) (*binding.Binding, error)
|
||||
ListBindings(ctx context.Context) ([]binding.Binding, error)
|
||||
UpdateBinding(ctx context.Context, b binding.Binding) error
|
||||
DeleteBinding(ctx context.Context, id string) error
|
||||
ApproveBinding(ctx context.Context, id string) error
|
||||
PauseBinding(ctx context.Context, id string) error
|
||||
ResumeBinding(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// DispatchLedger reads the binding dispatch ledger.
|
||||
type DispatchLedger interface {
|
||||
// ListDispatches returns the newest ledger rows matching filter.
|
||||
ListDispatches(ctx context.Context, filter DispatchFilter) ([]Dispatch, error)
|
||||
}
|
||||
|
||||
// Dispatch is one binding/capture ledger row: the task it started, or the
|
||||
// reason it started none.
|
||||
type Dispatch struct {
|
||||
BindingID string `json:"binding_id"`
|
||||
BindingVersion int64 `json:"binding_version"`
|
||||
CaptureID string `json:"capture_id"`
|
||||
TaskID int64 `json:"task_id,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
DispatchedAt time.Time `json:"dispatched_at"`
|
||||
}
|
||||
|
||||
// DispatchFilter narrows ListDispatches; empty fields match any row.
|
||||
type DispatchFilter struct {
|
||||
BindingID string
|
||||
CaptureID string
|
||||
TaskID int64
|
||||
Limit int
|
||||
}
|
||||
|
||||
// BindingDispatcher looks up armed bindings, lists undispatched captures and
|
||||
// records dispatches.
|
||||
type BindingDispatcher interface {
|
||||
ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error)
|
||||
RecordDispatch(
|
||||
ctx context.Context,
|
||||
bindingID string,
|
||||
bindingVersion int64,
|
||||
captureID string,
|
||||
// taskID addresses the SQLite-owned task tables, which are not
|
||||
// migrating: it stays an integer on purpose. A dispatch that starts
|
||||
// a task is recorded by EnqueueBindingTask instead.
|
||||
taskID int64,
|
||||
// reason is empty for a dispatch and names the terminal outcome of
|
||||
// an evaluation that started no task.
|
||||
reason string,
|
||||
) error
|
||||
ListUndispatchedCaptures(ctx context.Context, bindings []string, limit int) ([]CapturedEvent, error)
|
||||
}
|
||||
|
||||
// BindingTaskCreator is the single-method consumer-facing surface for
|
||||
// enqueueing a task triggered by a binding. Splitting it off TaskLifecycle
|
||||
// keeps the lifecycle surface narrow (8 methods, the interfacebloat limit)
|
||||
// and keeps the binding-specific shape on the binding interfaces.
|
||||
type BindingTaskCreator interface {
|
||||
// EnqueueBindingTask claims the binding's dispatch of captureID in the
|
||||
// ledger, enqueues the task and records its provenance as one unit: an
|
||||
// error leaves none of them, and a delivery already dispatched for the
|
||||
// binding returns ErrAlreadyDispatched.
|
||||
EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, captureID string, inputs map[string]any) (*task.Task, error)
|
||||
}
|
||||
|
||||
// PlaybookDispatcher records a playbook action dispatch before its side
|
||||
// effect runs, returning ErrAlreadyDispatched for a duplicate.
|
||||
// DeletePlaybookDispatches deletes one playbook's records.
|
||||
type PlaybookDispatcher interface {
|
||||
RecordPlaybookDispatch(ctx context.Context, playbookID, playbookVersion, eventID, actionID string) error
|
||||
DeletePlaybookDispatches(ctx context.Context, playbookID string) error
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
)
|
||||
|
||||
// CaptureStore persists inbound webhook captures.
|
||||
type CaptureStore interface {
|
||||
InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (string, error)
|
||||
ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error)
|
||||
}
|
||||
|
||||
// CaptureRefusalStore counts the events network rules refused, per source.
|
||||
type CaptureRefusalStore interface {
|
||||
RecordCaptureRefusal(ctx context.Context, source, addr string, at time.Time) error
|
||||
CaptureRefusals(ctx context.Context, since time.Time) ([]CaptureRefusals, error)
|
||||
}
|
||||
|
||||
// CaptureRefusals is one source's refusals and accepted captures since a
|
||||
// time, and the addresses it refused.
|
||||
type CaptureRefusals struct {
|
||||
Source string `json:"source"`
|
||||
Refused int64 `json:"refused"`
|
||||
Accepted int64 `json:"accepted"`
|
||||
Addrs []string `json:"addrs"`
|
||||
}
|
||||
|
||||
// EventTypeStore persists event types. Insert and Update refuse a type whose
|
||||
// rule overlaps another on the same source with eventtype.ErrOverlap, and a
|
||||
// malformed one with eventtype.ErrInvalid. Update rewrites the name and rule;
|
||||
// the schema is the one the type was created with.
|
||||
type EventTypeStore interface {
|
||||
InsertEventType(ctx context.Context, t eventtype.EventType) (string, error)
|
||||
UpdateEventType(ctx context.Context, t eventtype.EventType) error
|
||||
DeleteEventType(ctx context.Context, id string) error
|
||||
ListEventTypes(ctx context.Context) ([]eventtype.EventType, error)
|
||||
}
|
||||
|
||||
// CapturedEvent is one unbound inbound webhook capture: no workflow binding,
|
||||
// no forge/task association -- just what arrived, from where, and when.
|
||||
type CapturedEvent struct {
|
||||
ID string `json:"id"`
|
||||
ReceivedAt time.Time `json:"received_at"`
|
||||
Source string `json:"source"`
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
ContentType string `json:"content_type"`
|
||||
// Headers and Body are redacted (webhookguard.RedactPayload) before
|
||||
// they ever reach InsertCapture; the store persists what it is given.
|
||||
Headers string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
// EventType is the ID of the event type the capture was identified as
|
||||
// when it arrived, or empty when it matched none. An unidentified capture
|
||||
// is never dispatched.
|
||||
EventType string `json:"event_type"`
|
||||
// Unsigned marks an event that arrived on an approved unsigned source.
|
||||
// It dispatches without Authenticated and is flagged wherever it shows.
|
||||
Unsigned bool `json:"unsigned"`
|
||||
// Delivery names the sender's delivery; a retry of one delivery shares
|
||||
// it, so a binding dispatches each delivery once. Intake sets it from the
|
||||
// source's delivery header; the store fills the capture ID when empty.
|
||||
Delivery string `json:"delivery"`
|
||||
// OrgID is honoured only for a schedule-fired capture, whose source is
|
||||
// reserved and so names no org; every other capture takes its source's.
|
||||
OrgID string `json:"org_id,omitempty"`
|
||||
}
|
||||
|
||||
// Dispatchable reports whether a binding may start a task from this event:
|
||||
// a valid signature, or a source approved to take unsigned events.
|
||||
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
|
||||
@@ -0,0 +1,25 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
)
|
||||
|
||||
// HarnessSecretStore stores one org's OAuth token set per credential binding
|
||||
// service, encrypted at rest.
|
||||
type HarnessSecretStore interface {
|
||||
GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error)
|
||||
PutHarnessSecret(ctx context.Context, s harnesssecret.Secret) error
|
||||
}
|
||||
|
||||
// RunCredentialStore keeps run credentials by digest: the SHA-256 of the
|
||||
// token a task's container presents. A lookup of an unknown or expired
|
||||
// digest reports ErrRunCredentialUnknown.
|
||||
type RunCredentialStore interface {
|
||||
PutRunCredential(ctx context.Context, digest [32]byte, taskID int64, expires time.Time) error
|
||||
DeleteRunCredential(ctx context.Context, digest [32]byte) error
|
||||
RunCredentialTask(ctx context.Context, digest [32]byte, now time.Time) (int64, error)
|
||||
DeleteExpiredRunCredentials(ctx context.Context, now time.Time) error
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Sentinel errors, part of the wire contract: staterpc's
|
||||
// mapError/unmapError match these by (code, canonical message) across the
|
||||
// gRPC boundary, so their message strings are load-bearing and must never
|
||||
// change.
|
||||
var (
|
||||
// ErrStaleTransition is returned when a task transition's expected
|
||||
// from status does not match the task's current status.
|
||||
ErrStaleTransition = errors.New("store: stale transition: task status does not match expected from status")
|
||||
// ErrIllegalTransition is returned when the transition table does not allow
|
||||
// the status pair.
|
||||
ErrIllegalTransition = errors.New("store: illegal transition: status pair is not in the transition table")
|
||||
// ErrInvalidStep is returned when a step-execution request names a kind the
|
||||
// store does not record or a step whose identifying fields do not resolve.
|
||||
// Distinct from the transition sentinels, which cover a row's state.
|
||||
ErrInvalidStep = errors.New("store: invalid step execution request")
|
||||
// ErrResumeIncomplete is returned when a retry resumes after a stage whose
|
||||
// last run did not complete, so there are no results to start from.
|
||||
ErrResumeIncomplete = errors.New("store: the step before the resume point did not complete in its last run")
|
||||
// ErrBindingNotFound is returned when a binding ID does not exist.
|
||||
ErrBindingNotFound = errors.New("store: binding not found")
|
||||
// ErrBindingOverlap is returned when a binding's matcher overlaps an
|
||||
// existing binding for the same source.
|
||||
ErrBindingOverlap = errors.New("store: binding overlaps existing binding for source")
|
||||
// ErrBindingTransition is returned when a binding state transition is
|
||||
// rejected by the draft -> pending_approval -> armed machine.
|
||||
ErrBindingTransition = errors.New("store: binding state transition rejected")
|
||||
// ErrAlreadyDispatched is returned when a dispatch ledger already holds the
|
||||
// key.
|
||||
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
|
||||
// ErrCallNotYours is returned when a workflow.call status read names a
|
||||
// task that is not a callee of the calling task, or the caller itself
|
||||
// does not exist: a caller reads only the tasks it started
|
||||
ErrCallNotYours = errors.New("store: task is not a callee of the calling task")
|
||||
// ErrCallCallerNotRunning is returned when a workflow.call enqueue names
|
||||
// a caller that is not running: a stale retry, or a bug in the caller.
|
||||
ErrCallCallerNotRunning = errors.New("store: workflow.call caller is not running")
|
||||
// ErrCallDepthExceeded is returned when a workflow.call enqueue would
|
||||
// pass workflow.MaxCallDepth. The engine refuses the same call first;
|
||||
// the store re-checks because it owns the table.
|
||||
ErrCallDepthExceeded = errors.New("store: workflow.call would pass the depth limit")
|
||||
// ErrMappingNotFound is returned when a mapping ID does not exist.
|
||||
ErrMappingNotFound = errors.New("store: mapping not found")
|
||||
// ErrEventTypeNotFound is returned when an event type ID does not exist.
|
||||
ErrEventTypeNotFound = errors.New("store: event type not found")
|
||||
// ErrSourceNotFound is returned when a source path does not exist.
|
||||
ErrSourceNotFound = errors.New("store: source not found")
|
||||
// ErrSourceInUse is returned when deleting a source an armed binding
|
||||
// fires on.
|
||||
ErrSourceInUse = errors.New("store: source has an armed binding")
|
||||
// ErrSourcePathTaken is returned when a new source's path is in use.
|
||||
ErrSourcePathTaken = errors.New("store: source path already taken")
|
||||
// ErrSourceSigningStale is returned when a signing write's expected
|
||||
// from state does not match the stored one.
|
||||
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
|
||||
// ErrHarnessSecretNotFound is returned when no OAuth token set is
|
||||
// stored for an org/service pair -- the setup terminal has not
|
||||
// captured one yet.
|
||||
ErrHarnessSecretNotFound = errors.New("store: harness secret not found")
|
||||
// ErrRereviewCapReached is returned when a review gate re-review would
|
||||
// round past prreview.MaxRereviewRounds. The task stays waiting and its
|
||||
// gate row is unchanged. The dashboard answers it 409, like every other
|
||||
// conflict.
|
||||
ErrRereviewCapReached = errors.New("store: re-review cap reached")
|
||||
|
||||
// ErrResourceNotFound is returned when a control-plane resource kind has
|
||||
// no stored document. It is in-process only (not on the gRPC wire): the
|
||||
// control plane runs in the daemon against the local store.
|
||||
ErrResourceNotFound = errors.New("resource not found")
|
||||
// ErrResourceVersionConflict is returned when a resource write carries an
|
||||
// expected version that does not match the stored revision.
|
||||
ErrResourceVersionConflict = errors.New("resource version conflict")
|
||||
)
|
||||
|
||||
// ErrUnavailable means the store could not serve a request now: it is
|
||||
// restarting or unreachable. It is not paired with a canonical message the way
|
||||
// the sentinels above are -- staterpc derives it from the Unavailable code
|
||||
// alone, whose text varies by transport -- and it is the one store error a
|
||||
// caller with budget may answer by retrying rather than by failing its own
|
||||
// work. The wrapping keeps the gRPC status code readable through the chain.
|
||||
var ErrUnavailable = errors.New("store: state store unavailable")
|
||||
|
||||
// ErrRunCredentialUnknown is a run credential that was never issued, was
|
||||
// revoked, or has expired.
|
||||
var ErrRunCredentialUnknown = errors.New("run credential unknown or expired")
|
||||
@@ -0,0 +1,26 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
// MappingStore persists payload field mappings. Deliberately separate from
|
||||
// TaskStore and CaptureStore for the same reason those are split: the
|
||||
// dashboard's mapping editor should only acquire the mapping surface, not the
|
||||
// full task or capture APIs. See
|
||||
type MappingStore interface {
|
||||
InsertMapping(ctx context.Context, m mapping.Mapping) (string, error)
|
||||
GetMapping(ctx context.Context, id string) (*mapping.Mapping, error)
|
||||
ListMappings(ctx context.Context) ([]mapping.Mapping, error)
|
||||
UpdateMapping(ctx context.Context, m mapping.Mapping) error
|
||||
DeleteMapping(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// MappingMatchRecorder counts the events each mapping resolved, which the
|
||||
// store reports as Mapping.MatchCount and LastMatchedAt. Recording the same
|
||||
// (mapping, capture) twice counts once.
|
||||
type MappingMatchRecorder interface {
|
||||
RecordMappingMatch(ctx context.Context, mappingID, captureID string) error
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Resource is one control-plane resource document: the stored value for an
|
||||
// org's kind, its revision, and the audit record written with the last write.
|
||||
// Resource and ResourceWrite live here so the UI-side consumers can reference
|
||||
// them without linking the PostgreSQL implementation.
|
||||
type Resource struct {
|
||||
OrgID string
|
||||
Kind string
|
||||
Value []byte
|
||||
Version int64
|
||||
Actor string
|
||||
Source string
|
||||
RequestID string
|
||||
ExpectedVersion int64
|
||||
CurrentVersion int64
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// DefaultOrgID is the org every resource written before orgs existed belongs
|
||||
// to, and the org a request that names none acts in.
|
||||
const DefaultOrgID = "org-sys"
|
||||
|
||||
// ResourceAuditKey is the sys_audit record key of one org's resource kind. The
|
||||
// default org keeps the bare kind, so audit rows written before resources were
|
||||
// per-org still resolve.
|
||||
func ResourceAuditKey(orgID, kind string) string {
|
||||
if orgID == DefaultOrgID {
|
||||
return kind
|
||||
}
|
||||
return orgID + "/" + kind
|
||||
}
|
||||
|
||||
// ResourceWrite is a control-plane resource write request. ExpectedVersion is
|
||||
// the optimistic-concurrency guard: a write whose expectation does not match
|
||||
// the stored revision is refused with ErrResourceVersionConflict.
|
||||
type ResourceWrite struct {
|
||||
OrgID string
|
||||
Kind string
|
||||
Value []byte
|
||||
Actor string
|
||||
Source string
|
||||
RequestID string
|
||||
ExpectedVersion int64
|
||||
At time.Time
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
)
|
||||
|
||||
// SourceStore persists capture sources keyed by path. Secrets are encrypted
|
||||
// at rest; signing transitions use an expected-from guard.
|
||||
type SourceStore interface {
|
||||
InsertSource(ctx context.Context, s source.Source) error
|
||||
// GetSource returns (nil, nil) for an unknown path.
|
||||
GetSource(ctx context.Context, path string) (*source.Source, error)
|
||||
ListSources(ctx context.Context) ([]source.Source, error)
|
||||
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
|
||||
SetSourceSecret(ctx context.Context, path, secret string) error
|
||||
SetSourceName(ctx context.Context, path, name string) error
|
||||
SetSourceDeliveryHeader(ctx context.Context, path, header string) error
|
||||
// DeleteSource refuses with ErrSourceInUse while an armed binding fires
|
||||
// on the source.
|
||||
DeleteSource(ctx context.Context, path string) error
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
)
|
||||
|
||||
// ConfigSnapshotStore holds the published configuration view.
|
||||
type ConfigSnapshotStore interface {
|
||||
PutConfigSnapshot(ctx context.Context, snapshot ConfigSnapshot) error
|
||||
ConfigSnapshot(ctx context.Context) (ConfigSnapshot, bool, error)
|
||||
}
|
||||
|
||||
// ChannelStatusStore holds channel runtime state published by the process
|
||||
// hosting the channels.
|
||||
type ChannelStatusStore interface {
|
||||
// PutChannelStatus records the reporting process's whole set: a channel it no
|
||||
// longer reports is removed rather than left behind, because a stale "running"
|
||||
// row is a lie the dashboard would show indefinitely.
|
||||
PutChannelStatus(ctx context.Context, channels []ChannelStatus) error
|
||||
ChannelStatus(ctx context.Context) ([]ChannelStatus, error)
|
||||
}
|
||||
|
||||
// ApplyStatusStore holds which version of each control-plane resource each
|
||||
// process is running. Same split as ConfigSnapshotStore and for the same
|
||||
// reason: the writers are the processes that apply a resource, the reader is
|
||||
// the UI, and a task-scoped credential must reach neither.
|
||||
type ApplyStatusStore interface {
|
||||
PutApplyStatus(ctx context.Context, status ApplyStatus) error
|
||||
ListApplyStatus(ctx context.Context) ([]ApplyStatus, error)
|
||||
}
|
||||
|
||||
// PresenceStore holds one record per running service instance. Writers are
|
||||
// the services themselves; readers are the UI and archied status.
|
||||
type PresenceStore interface {
|
||||
PutPresence(ctx context.Context, presence Presence) error
|
||||
ListPresence(ctx context.Context) ([]Presence, error)
|
||||
}
|
||||
|
||||
// ConfigSnapshot is the published, secret-free configuration view. Schema
|
||||
// names Document's shape.
|
||||
type ConfigSnapshot struct {
|
||||
Schema string
|
||||
Document []byte
|
||||
PublishedAt time.Time
|
||||
}
|
||||
|
||||
// ChannelStatus is one channel's runtime state as the process hosting it
|
||||
// reports it. ReloadSupported is a capability declaration rather than a request:
|
||||
// asking for a reload travels on its own surface, because a transient request and
|
||||
// a durable state do not share a lifetime.
|
||||
type ChannelStatus struct {
|
||||
ID string
|
||||
Name string
|
||||
State string
|
||||
Detail string
|
||||
Configured bool
|
||||
ReloadSupported bool
|
||||
ObservedAt time.Time
|
||||
}
|
||||
|
||||
// ApplyStatus is one process's report on one resource kind. On error,
|
||||
// AppliedVersion stays at the last applied version. ReportedAt is
|
||||
// re-stamped periodically.
|
||||
type ApplyStatus struct {
|
||||
Process string `json:"process"`
|
||||
Kind string `json:"kind"`
|
||||
AppliedVersion int64 `json:"applied_version"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ReportedAt time.Time `json:"reported_at"`
|
||||
}
|
||||
|
||||
// Presence is one running service instance. Ready and Detail summarise its
|
||||
// readiness probes; Detail names the degraded ones.
|
||||
type Presence struct {
|
||||
Checks []health.Component `json:"checks"`
|
||||
Service string `json:"service"`
|
||||
InstanceID string `json:"instance_id"`
|
||||
Version string `json:"version"`
|
||||
InstallType string `json:"install_type"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ReportedAt time.Time `json:"reported_at"`
|
||||
Ready bool `json:"ready"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
@@ -2,23 +2,6 @@
|
||||
// without an implementation.
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// TaskStore is the full store surface the daemon needs.
|
||||
// Consumers depend on TaskStore, never on a concrete type.
|
||||
type TaskStore interface {
|
||||
@@ -31,591 +14,3 @@ type TaskStore interface {
|
||||
ReviewGateResponder
|
||||
RemediationStarter
|
||||
}
|
||||
|
||||
// TaskLifecycle manages the core task state machine and enqueuing.
|
||||
// Binding-triggered task creation lives on BindingTaskCreator, not here,
|
||||
// so the lifecycle surface stays narrow and non-binding consumers (forge
|
||||
// poll, chat spawn, drain loop) do not acquire a binding-specific shape.
|
||||
type TaskLifecycle interface {
|
||||
EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error)
|
||||
EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*task.Task, error)
|
||||
ClaimNext(ctx context.Context) (*task.Task, error)
|
||||
ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
Transition(ctx context.Context, taskID int64, from, to, detail string) error
|
||||
Update(ctx context.Context, t *task.Task) error
|
||||
Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error
|
||||
RecoverStale(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
// TaskParker parks a task with a park class and the blocker the park site
|
||||
// knows, if any. Unknown classes become needs_decision.
|
||||
type TaskParker interface {
|
||||
ParkTask(ctx context.Context, taskID int64, from, detail, class, blocker string) error
|
||||
}
|
||||
|
||||
// StepRecorder records a running execution's steps.
|
||||
type StepRecorder interface {
|
||||
StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error)
|
||||
FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error)
|
||||
}
|
||||
|
||||
// ExecutionCanceller cancels an execution and its current attempt's open
|
||||
// steps in one transaction. It also cancels the callees the execution was
|
||||
// waiting on, and returns their ids (nested callees included) so the caller
|
||||
// can stop their runs too.
|
||||
type ExecutionCanceller interface {
|
||||
CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error)
|
||||
}
|
||||
|
||||
// StepReader lists one execution's recorded steps.
|
||||
type StepReader interface {
|
||||
ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error)
|
||||
}
|
||||
|
||||
// HarnessSecretStore stores one org's OAuth token set per credential binding
|
||||
// service, encrypted at rest.
|
||||
type HarnessSecretStore interface {
|
||||
GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error)
|
||||
PutHarnessSecret(ctx context.Context, s harnesssecret.Secret) error
|
||||
}
|
||||
|
||||
// TaskArchiver removes one terminal task's local record with an optimistic
|
||||
// status guard. It is separate from the already broad lifecycle contract so
|
||||
// consumers that only run tasks do not acquire an operator-only capability.
|
||||
type TaskArchiver interface {
|
||||
OutcomePoster
|
||||
ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error)
|
||||
ClearTerminalTasks(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
// TaskRetryer atomically requeues recoverable work and accounts for the new
|
||||
// attempt so a partial write cannot evade the retry cap. retryMode is the
|
||||
// operator's worktree choice for the next dispatch (taskstate.RetryMode),
|
||||
// persisted on the row so the daemon reads it instead of inferring it. resume
|
||||
// is where the attempt starts; a resume whose After stage did not complete in
|
||||
// its last run is refused with ErrResumeIncomplete.
|
||||
type TaskRetryer interface {
|
||||
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string, resume task.Resume, currentDefinition bool) error
|
||||
}
|
||||
|
||||
// ReviewGateResponder records the operator's review-gate answer. A re-review
|
||||
// increments rereview_rounds and requeues; one past the cap returns
|
||||
// ErrRereviewCapReached and writes nothing.
|
||||
type ReviewGateResponder interface {
|
||||
RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error
|
||||
}
|
||||
|
||||
// RemediationStarter queues a review-triggered remediation for an Archie-owned
|
||||
// open-PR task: one guarded transition that carries the JSON-encoded review
|
||||
// unit in the same write, so a claimed remediation always has its input. Runs
|
||||
// for one task are serialised, so a distinct review that arrives while a
|
||||
// remediation owns the task is queued behind it and remediated once that run
|
||||
// finishes; a re-delivered unit is absorbed, not queued twice.
|
||||
// UpdateReviewPayload merges late-arriving comments into the unclaimed unit
|
||||
// for the same review, active or queued behind a running remediation.
|
||||
type RemediationStarter interface {
|
||||
BeginRemediation(ctx context.Context, taskID int64, payload string) error
|
||||
UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error
|
||||
// SetReviewCursors persists the poll backstop's per-task review and
|
||||
// comment high-water marks (pr-review-remediation.md decision 2). The
|
||||
// pr_open guard is part of the contract: cursors only move while no
|
||||
// remediation run owns the task.
|
||||
SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error
|
||||
}
|
||||
|
||||
// OutcomePoster tracks which finished chat tasks have reported back to their
|
||||
// conversation.
|
||||
type OutcomePoster interface {
|
||||
// UnpostedOutcomes returns finished chat tasks whose outcome has not been
|
||||
// posted to the conversation that created them.
|
||||
UnpostedOutcomes(ctx context.Context) ([]*task.Task, error)
|
||||
// MarkOutcomePosted records that the task's state at status was posted.
|
||||
MarkOutcomePosted(ctx context.Context, taskID int64, status string) error
|
||||
}
|
||||
|
||||
// TaskQueries groups read-only task accessors.
|
||||
type TaskQueries interface {
|
||||
TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
|
||||
OpenPRs(ctx context.Context) ([]task.Task, error)
|
||||
// ActiveTasksByOrigin returns the queued and running tasks the
|
||||
// conversation origin created, for its /stop.
|
||||
ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error)
|
||||
// Tasks returns the most recently updated tasks.
|
||||
Tasks(ctx context.Context, limit int) ([]task.Task, error)
|
||||
// TasksPage returns one page of tasks, most recently updated first.
|
||||
TasksPage(ctx context.Context, page TaskPage) ([]task.Task, error)
|
||||
StatusCounts(ctx context.Context) (map[string]int, error)
|
||||
}
|
||||
|
||||
// TaskEvents groups observability and lifecycle methods.
|
||||
type TaskEvents interface {
|
||||
InsertEvent(ctx context.Context, e events.Event) (int64, error)
|
||||
EventsSince(ctx context.Context, cursor string, limit int) ([]events.Event, error)
|
||||
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
|
||||
WorkflowStats(ctx context.Context) ([]WorkflowStat, error)
|
||||
StageStats(ctx context.Context) ([]StageStat, error)
|
||||
TokensByDay(ctx context.Context, days int) ([]DayTokens, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// CaptureStore persists inbound webhook captures.
|
||||
type CaptureStore interface {
|
||||
InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (string, error)
|
||||
ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error)
|
||||
}
|
||||
|
||||
// CaptureRefusalStore counts the events network rules refused, per source.
|
||||
type CaptureRefusalStore interface {
|
||||
RecordCaptureRefusal(ctx context.Context, source, addr string, at time.Time) error
|
||||
CaptureRefusals(ctx context.Context, since time.Time) ([]CaptureRefusals, error)
|
||||
}
|
||||
|
||||
// CaptureRefusals is one source's refusals and accepted captures since a
|
||||
// time, and the addresses it refused.
|
||||
type CaptureRefusals struct {
|
||||
Source string `json:"source"`
|
||||
Refused int64 `json:"refused"`
|
||||
Accepted int64 `json:"accepted"`
|
||||
Addrs []string `json:"addrs"`
|
||||
}
|
||||
|
||||
// ConfigSnapshotStore holds the published configuration view.
|
||||
type ConfigSnapshotStore interface {
|
||||
PutConfigSnapshot(ctx context.Context, snapshot ConfigSnapshot) error
|
||||
ConfigSnapshot(ctx context.Context) (ConfigSnapshot, bool, error)
|
||||
}
|
||||
|
||||
// ChannelStatusStore holds channel runtime state published by the process
|
||||
// hosting the channels.
|
||||
type ChannelStatusStore interface {
|
||||
// PutChannelStatus records the reporting process's whole set: a channel it no
|
||||
// longer reports is removed rather than left behind, because a stale "running"
|
||||
// row is a lie the dashboard would show indefinitely.
|
||||
PutChannelStatus(ctx context.Context, channels []ChannelStatus) error
|
||||
ChannelStatus(ctx context.Context) ([]ChannelStatus, error)
|
||||
}
|
||||
|
||||
// ApplyStatusStore holds which version of each control-plane resource each
|
||||
// process is running. Same split as ConfigSnapshotStore and for the same
|
||||
// reason: the writers are the processes that apply a resource, the reader is
|
||||
// the UI, and a task-scoped credential must reach neither.
|
||||
type ApplyStatusStore interface {
|
||||
PutApplyStatus(ctx context.Context, status ApplyStatus) error
|
||||
ListApplyStatus(ctx context.Context) ([]ApplyStatus, error)
|
||||
}
|
||||
|
||||
// PresenceStore holds one record per running service instance. Writers are
|
||||
// the services themselves; readers are the UI and archied status.
|
||||
type PresenceStore interface {
|
||||
PutPresence(ctx context.Context, presence Presence) error
|
||||
ListPresence(ctx context.Context) ([]Presence, error)
|
||||
}
|
||||
|
||||
// MappingStore persists payload field mappings. Deliberately separate from
|
||||
// TaskStore and CaptureStore for the same reason those are split: the
|
||||
// dashboard's mapping editor should only acquire the mapping surface, not the
|
||||
// full task or capture APIs. See
|
||||
type MappingStore interface {
|
||||
InsertMapping(ctx context.Context, m mapping.Mapping) (string, error)
|
||||
GetMapping(ctx context.Context, id string) (*mapping.Mapping, error)
|
||||
ListMappings(ctx context.Context) ([]mapping.Mapping, error)
|
||||
UpdateMapping(ctx context.Context, m mapping.Mapping) error
|
||||
DeleteMapping(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// MappingMatchRecorder counts the events each mapping resolved, which the
|
||||
// store reports as Mapping.MatchCount and LastMatchedAt. Recording the same
|
||||
// (mapping, capture) twice counts once.
|
||||
type MappingMatchRecorder interface {
|
||||
RecordMappingMatch(ctx context.Context, mappingID, captureID string) error
|
||||
}
|
||||
|
||||
// EventTypeStore persists event types. Insert and Update refuse a type whose
|
||||
// rule overlaps another on the same source with eventtype.ErrOverlap, and a
|
||||
// malformed one with eventtype.ErrInvalid. Update rewrites the name and rule;
|
||||
// the schema is the one the type was created with.
|
||||
type EventTypeStore interface {
|
||||
InsertEventType(ctx context.Context, t eventtype.EventType) (string, error)
|
||||
UpdateEventType(ctx context.Context, t eventtype.EventType) error
|
||||
DeleteEventType(ctx context.Context, id string) error
|
||||
ListEventTypes(ctx context.Context) ([]eventtype.EventType, error)
|
||||
}
|
||||
|
||||
// BindingStore persists bindings and their draft -> pending_approval ->
|
||||
// armed states.
|
||||
type BindingStore interface {
|
||||
InsertBinding(ctx context.Context, b binding.Binding) (string, error)
|
||||
GetBinding(ctx context.Context, id string) (*binding.Binding, error)
|
||||
ListBindings(ctx context.Context) ([]binding.Binding, error)
|
||||
UpdateBinding(ctx context.Context, b binding.Binding) error
|
||||
DeleteBinding(ctx context.Context, id string) error
|
||||
ApproveBinding(ctx context.Context, id string) error
|
||||
PauseBinding(ctx context.Context, id string) error
|
||||
ResumeBinding(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// SourceStore persists capture sources keyed by path. Secrets are encrypted
|
||||
// at rest; signing transitions use an expected-from guard.
|
||||
type SourceStore interface {
|
||||
InsertSource(ctx context.Context, s source.Source) error
|
||||
// GetSource returns (nil, nil) for an unknown path.
|
||||
GetSource(ctx context.Context, path string) (*source.Source, error)
|
||||
ListSources(ctx context.Context) ([]source.Source, error)
|
||||
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
|
||||
SetSourceSecret(ctx context.Context, path, secret string) error
|
||||
SetSourceName(ctx context.Context, path, name string) error
|
||||
SetSourceDeliveryHeader(ctx context.Context, path, header string) error
|
||||
// DeleteSource refuses with ErrSourceInUse while an armed binding fires
|
||||
// on the source.
|
||||
DeleteSource(ctx context.Context, path string) error
|
||||
}
|
||||
|
||||
// DispatchLedger reads the binding dispatch ledger.
|
||||
type DispatchLedger interface {
|
||||
// ListDispatches returns the newest ledger rows matching filter.
|
||||
ListDispatches(ctx context.Context, filter DispatchFilter) ([]Dispatch, error)
|
||||
}
|
||||
|
||||
// TaskPage selects one page of the task list. Empty Statuses matches every
|
||||
// status. A zero After starts at the newest task; otherwise the page begins
|
||||
// after the task it names, in (updated_at, id) descending order.
|
||||
type TaskPage struct {
|
||||
Statuses []string
|
||||
// Workflow, when set, keeps only that workflow's tasks.
|
||||
Workflow string
|
||||
After TaskCursor
|
||||
Limit int
|
||||
}
|
||||
|
||||
// TaskCursor is the position of the last task a page returned.
|
||||
type TaskCursor struct {
|
||||
UpdatedAt time.Time
|
||||
ID int64
|
||||
}
|
||||
|
||||
// Dispatch is one binding/capture ledger row: the task it started, or the
|
||||
// reason it started none.
|
||||
type Dispatch struct {
|
||||
BindingID string `json:"binding_id"`
|
||||
BindingVersion int64 `json:"binding_version"`
|
||||
CaptureID string `json:"capture_id"`
|
||||
TaskID int64 `json:"task_id,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
DispatchedAt time.Time `json:"dispatched_at"`
|
||||
}
|
||||
|
||||
// DispatchFilter narrows ListDispatches; empty fields match any row.
|
||||
type DispatchFilter struct {
|
||||
BindingID string
|
||||
CaptureID string
|
||||
TaskID int64
|
||||
Limit int
|
||||
}
|
||||
|
||||
// BindingDispatcher looks up armed bindings, lists undispatched captures and
|
||||
// records dispatches.
|
||||
type BindingDispatcher interface {
|
||||
ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error)
|
||||
RecordDispatch(
|
||||
ctx context.Context,
|
||||
bindingID string,
|
||||
bindingVersion int64,
|
||||
captureID string,
|
||||
// taskID addresses the SQLite-owned task tables, which are not
|
||||
// migrating: it stays an integer on purpose. A dispatch that starts
|
||||
// a task is recorded by EnqueueBindingTask instead.
|
||||
taskID int64,
|
||||
// reason is empty for a dispatch and names the terminal outcome of
|
||||
// an evaluation that started no task.
|
||||
reason string,
|
||||
) error
|
||||
ListUndispatchedCaptures(ctx context.Context, bindings []string, limit int) ([]CapturedEvent, error)
|
||||
}
|
||||
|
||||
// BindingTaskCreator is the single-method consumer-facing surface for
|
||||
// enqueueing a task triggered by a binding. Splitting it off TaskLifecycle
|
||||
// keeps the lifecycle surface narrow (8 methods, the interfacebloat limit)
|
||||
// and keeps the binding-specific shape on the binding interfaces.
|
||||
type BindingTaskCreator interface {
|
||||
// EnqueueBindingTask claims the binding's dispatch of captureID in the
|
||||
// ledger, enqueues the task and records its provenance as one unit: an
|
||||
// error leaves none of them, and a delivery already dispatched for the
|
||||
// binding returns ErrAlreadyDispatched.
|
||||
EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, captureID string, inputs map[string]any) (*task.Task, error)
|
||||
}
|
||||
|
||||
// WorkflowCaller starts a workflow.call callee and reads it back.
|
||||
type WorkflowCaller = task.Caller
|
||||
|
||||
// PlaybookDispatcher records a playbook action dispatch before its side
|
||||
// effect runs, returning ErrAlreadyDispatched for a duplicate.
|
||||
// DeletePlaybookDispatches deletes one playbook's records.
|
||||
type PlaybookDispatcher interface {
|
||||
RecordPlaybookDispatch(ctx context.Context, playbookID, playbookVersion, eventID, actionID string) error
|
||||
DeletePlaybookDispatches(ctx context.Context, playbookID string) error
|
||||
}
|
||||
|
||||
// TaskLogStore reads one task attempt's log. Found=false means no log;
|
||||
// ErrTaskLogsUnavailable means this process cannot read logs.
|
||||
type TaskLogStore interface {
|
||||
// TaskLog returns a page of one attempt's decoded log. attempt 0 selects
|
||||
// the task's current attempt.
|
||||
TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error)
|
||||
// TaskLogContent writes one attempt's log verbatim to w, for a download.
|
||||
// found is false, with a nil error, when the attempt has no log file.
|
||||
TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (found bool, err error)
|
||||
}
|
||||
|
||||
// CapturedEvent is one unbound inbound webhook capture: no workflow binding,
|
||||
// no forge/task association -- just what arrived, from where, and when.
|
||||
type CapturedEvent struct {
|
||||
ID string `json:"id"`
|
||||
ReceivedAt time.Time `json:"received_at"`
|
||||
Source string `json:"source"`
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
ContentType string `json:"content_type"`
|
||||
// Headers and Body are redacted (webhookguard.RedactPayload) before
|
||||
// they ever reach InsertCapture; the store persists what it is given.
|
||||
Headers string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
// EventType is the ID of the event type the capture was identified as
|
||||
// when it arrived, or empty when it matched none. An unidentified capture
|
||||
// is never dispatched.
|
||||
EventType string `json:"event_type"`
|
||||
// Unsigned marks an event that arrived on an approved unsigned source.
|
||||
// It dispatches without Authenticated and is flagged wherever it shows.
|
||||
Unsigned bool `json:"unsigned"`
|
||||
// Delivery names the sender's delivery; a retry of one delivery shares
|
||||
// it, so a binding dispatches each delivery once. Intake sets it from the
|
||||
// source's delivery header; the store fills the capture ID when empty.
|
||||
Delivery string `json:"delivery"`
|
||||
// OrgID is honoured only for a schedule-fired capture, whose source is
|
||||
// reserved and so names no org; every other capture takes its source's.
|
||||
OrgID string `json:"org_id,omitempty"`
|
||||
}
|
||||
|
||||
// Dispatchable reports whether a binding may start a task from this event:
|
||||
// a valid signature, or a source approved to take unsigned events.
|
||||
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
|
||||
|
||||
// ConfigSnapshot is the published, secret-free configuration view. Schema
|
||||
// names Document's shape.
|
||||
type ConfigSnapshot struct {
|
||||
Schema string
|
||||
Document []byte
|
||||
PublishedAt time.Time
|
||||
}
|
||||
|
||||
// ChannelStatus is one channel's runtime state as the process hosting it
|
||||
// reports it. ReloadSupported is a capability declaration rather than a request:
|
||||
// asking for a reload travels on its own surface, because a transient request and
|
||||
// a durable state do not share a lifetime.
|
||||
type ChannelStatus struct {
|
||||
ID string
|
||||
Name string
|
||||
State string
|
||||
Detail string
|
||||
Configured bool
|
||||
ReloadSupported bool
|
||||
ObservedAt time.Time
|
||||
}
|
||||
|
||||
// ApplyStatus is one process's report on one resource kind. On error,
|
||||
// AppliedVersion stays at the last applied version. ReportedAt is
|
||||
// re-stamped periodically.
|
||||
type ApplyStatus struct {
|
||||
Process string `json:"process"`
|
||||
Kind string `json:"kind"`
|
||||
AppliedVersion int64 `json:"applied_version"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ReportedAt time.Time `json:"reported_at"`
|
||||
}
|
||||
|
||||
// Presence is one running service instance. Ready and Detail summarise its
|
||||
// readiness probes; Detail names the degraded ones.
|
||||
type Presence struct {
|
||||
Checks []health.Component `json:"checks"`
|
||||
Service string `json:"service"`
|
||||
InstanceID string `json:"instance_id"`
|
||||
Version string `json:"version"`
|
||||
InstallType string `json:"install_type"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ReportedAt time.Time `json:"reported_at"`
|
||||
Ready bool `json:"ready"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// WorkflowStat is one row of the per-workflow metrics table.
|
||||
type WorkflowStat struct {
|
||||
Workflow string `json:"workflow"`
|
||||
Runs int `json:"runs"`
|
||||
Merged int `json:"merged"`
|
||||
Completed int `json:"completed"`
|
||||
PROpen int `json:"pr_open"`
|
||||
Parked int `json:"parked"`
|
||||
AvgTokens int `json:"avg_tokens"`
|
||||
AvgSteps float64 `json:"avg_steps"`
|
||||
TotalToken int `json:"total_tokens"`
|
||||
// Running and LastStatus describe the workflow now: how many of its runs
|
||||
// are working, and how its newest one ended.
|
||||
Running int `json:"running"`
|
||||
LastStatus string `json:"last_status"`
|
||||
}
|
||||
|
||||
// StageStat is average stage duration and failure counts per stage.
|
||||
type StageStat struct {
|
||||
Workflow string `json:"workflow"`
|
||||
Stage string `json:"stage"`
|
||||
Runs int `json:"runs"`
|
||||
AvgMs int `json:"avg_ms"`
|
||||
Errors int `json:"errors"`
|
||||
}
|
||||
|
||||
// DayTokens is token spend per UTC day.
|
||||
type DayTokens struct {
|
||||
Day string `json:"day"`
|
||||
Tokens int `json:"tokens"`
|
||||
}
|
||||
|
||||
// Sentinel errors, part of the wire contract: staterpc's
|
||||
// mapError/unmapError match these by (code, canonical message) across the
|
||||
// gRPC boundary, so their message strings are load-bearing and must never
|
||||
// change.
|
||||
var (
|
||||
// ErrStaleTransition is returned when a task transition's expected
|
||||
// from status does not match the task's current status.
|
||||
ErrStaleTransition = errors.New("store: stale transition: task status does not match expected from status")
|
||||
// ErrIllegalTransition is returned when the transition table does not allow
|
||||
// the status pair.
|
||||
ErrIllegalTransition = errors.New("store: illegal transition: status pair is not in the transition table")
|
||||
// ErrInvalidStep is returned when a step-execution request names a kind the
|
||||
// store does not record or a step whose identifying fields do not resolve.
|
||||
// Distinct from the transition sentinels, which cover a row's state.
|
||||
ErrInvalidStep = errors.New("store: invalid step execution request")
|
||||
// ErrResumeIncomplete is returned when a retry resumes after a stage whose
|
||||
// last run did not complete, so there are no results to start from.
|
||||
ErrResumeIncomplete = errors.New("store: the step before the resume point did not complete in its last run")
|
||||
// ErrBindingNotFound is returned when a binding ID does not exist.
|
||||
ErrBindingNotFound = errors.New("store: binding not found")
|
||||
// ErrBindingOverlap is returned when a binding's matcher overlaps an
|
||||
// existing binding for the same source.
|
||||
ErrBindingOverlap = errors.New("store: binding overlaps existing binding for source")
|
||||
// ErrBindingTransition is returned when a binding state transition is
|
||||
// rejected by the draft -> pending_approval -> armed machine.
|
||||
ErrBindingTransition = errors.New("store: binding state transition rejected")
|
||||
// ErrAlreadyDispatched is returned when a dispatch ledger already holds the
|
||||
// key.
|
||||
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
|
||||
// ErrCallNotYours is returned when a workflow.call status read names a
|
||||
// task that is not a callee of the calling task, or the caller itself
|
||||
// does not exist: a caller reads only the tasks it started
|
||||
ErrCallNotYours = errors.New("store: task is not a callee of the calling task")
|
||||
// ErrCallCallerNotRunning is returned when a workflow.call enqueue names
|
||||
// a caller that is not running: a stale retry, or a bug in the caller.
|
||||
ErrCallCallerNotRunning = errors.New("store: workflow.call caller is not running")
|
||||
// ErrCallDepthExceeded is returned when a workflow.call enqueue would
|
||||
// pass workflow.MaxCallDepth. The engine refuses the same call first;
|
||||
// the store re-checks because it owns the table.
|
||||
ErrCallDepthExceeded = errors.New("store: workflow.call would pass the depth limit")
|
||||
// ErrMappingNotFound is returned when a mapping ID does not exist.
|
||||
ErrMappingNotFound = errors.New("store: mapping not found")
|
||||
// ErrEventTypeNotFound is returned when an event type ID does not exist.
|
||||
ErrEventTypeNotFound = errors.New("store: event type not found")
|
||||
// ErrSourceNotFound is returned when a source path does not exist.
|
||||
ErrSourceNotFound = errors.New("store: source not found")
|
||||
// ErrSourceInUse is returned when deleting a source an armed binding
|
||||
// fires on.
|
||||
ErrSourceInUse = errors.New("store: source has an armed binding")
|
||||
// ErrSourcePathTaken is returned when a new source's path is in use.
|
||||
ErrSourcePathTaken = errors.New("store: source path already taken")
|
||||
// ErrSourceSigningStale is returned when a signing write's expected
|
||||
// from state does not match the stored one.
|
||||
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
|
||||
// ErrHarnessSecretNotFound is returned when no OAuth token set is
|
||||
// stored for an org/service pair -- the setup terminal has not
|
||||
// captured one yet.
|
||||
ErrHarnessSecretNotFound = errors.New("store: harness secret not found")
|
||||
// ErrRereviewCapReached is returned when a review gate re-review would
|
||||
// round past prreview.MaxRereviewRounds. The task stays waiting and its
|
||||
// gate row is unchanged. The dashboard answers it 409, like every other
|
||||
// conflict.
|
||||
ErrRereviewCapReached = errors.New("store: re-review cap reached")
|
||||
|
||||
// ErrResourceNotFound is returned when a control-plane resource kind has
|
||||
// no stored document. It is in-process only (not on the gRPC wire): the
|
||||
// control plane runs in the daemon against the local store.
|
||||
ErrResourceNotFound = errors.New("resource not found")
|
||||
// ErrResourceVersionConflict is returned when a resource write carries an
|
||||
// expected version that does not match the stored revision.
|
||||
ErrResourceVersionConflict = errors.New("resource version conflict")
|
||||
)
|
||||
|
||||
// ErrUnavailable means the store could not serve a request now: it is
|
||||
// restarting or unreachable. It is not paired with a canonical message the way
|
||||
// the sentinels above are -- staterpc derives it from the Unavailable code
|
||||
// alone, whose text varies by transport -- and it is the one store error a
|
||||
// caller with budget may answer by retrying rather than by failing its own
|
||||
// work. The wrapping keeps the gRPC status code readable through the chain.
|
||||
var ErrUnavailable = errors.New("store: state store unavailable")
|
||||
|
||||
// Resource is one control-plane resource document: the stored value for an
|
||||
// org's kind, its revision, and the audit record written with the last write.
|
||||
// Resource and ResourceWrite live here so the UI-side consumers can reference
|
||||
// them without linking the PostgreSQL implementation.
|
||||
type Resource struct {
|
||||
OrgID string
|
||||
Kind string
|
||||
Value []byte
|
||||
Version int64
|
||||
Actor string
|
||||
Source string
|
||||
RequestID string
|
||||
ExpectedVersion int64
|
||||
CurrentVersion int64
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// DefaultOrgID is the org every resource written before orgs existed belongs
|
||||
// to, and the org a request that names none acts in.
|
||||
const DefaultOrgID = "org-sys"
|
||||
|
||||
// ResourceAuditKey is the sys_audit record key of one org's resource kind. The
|
||||
// default org keeps the bare kind, so audit rows written before resources were
|
||||
// per-org still resolve.
|
||||
func ResourceAuditKey(orgID, kind string) string {
|
||||
if orgID == DefaultOrgID {
|
||||
return kind
|
||||
}
|
||||
return orgID + "/" + kind
|
||||
}
|
||||
|
||||
// ResourceWrite is a control-plane resource write request. ExpectedVersion is
|
||||
// the optimistic-concurrency guard: a write whose expectation does not match
|
||||
// the stored revision is refused with ErrResourceVersionConflict.
|
||||
type ResourceWrite struct {
|
||||
OrgID string
|
||||
Kind string
|
||||
Value []byte
|
||||
Actor string
|
||||
Source string
|
||||
RequestID string
|
||||
ExpectedVersion int64
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// ErrRunCredentialUnknown is a run credential that was never issued, was
|
||||
// revoked, or has expired.
|
||||
var ErrRunCredentialUnknown = errors.New("run credential unknown or expired")
|
||||
|
||||
// RunCredentialStore keeps run credentials by digest: the SHA-256 of the
|
||||
// token a task's container presents. A lookup of an unknown or expired
|
||||
// digest reports ErrRunCredentialUnknown.
|
||||
type RunCredentialStore interface {
|
||||
PutRunCredential(ctx context.Context, digest [32]byte, taskID int64, expires time.Time) error
|
||||
DeleteRunCredential(ctx context.Context, digest [32]byte) error
|
||||
RunCredentialTask(ctx context.Context, digest [32]byte, now time.Time) (int64, error)
|
||||
DeleteExpiredRunCredentials(ctx context.Context, now time.Time) error
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package storecontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// TaskLifecycle manages the core task state machine and enqueuing.
|
||||
// Binding-triggered task creation lives on BindingTaskCreator, not here,
|
||||
// so the lifecycle surface stays narrow and non-binding consumers (forge
|
||||
// poll, chat spawn, drain loop) do not acquire a binding-specific shape.
|
||||
type TaskLifecycle interface {
|
||||
EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error)
|
||||
EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*task.Task, error)
|
||||
ClaimNext(ctx context.Context) (*task.Task, error)
|
||||
ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
Transition(ctx context.Context, taskID int64, from, to, detail string) error
|
||||
Update(ctx context.Context, t *task.Task) error
|
||||
Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error
|
||||
RecoverStale(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
// TaskParker parks a task with a park class and the blocker the park site
|
||||
// knows, if any. Unknown classes become needs_decision.
|
||||
type TaskParker interface {
|
||||
ParkTask(ctx context.Context, taskID int64, from, detail, class, blocker string) error
|
||||
}
|
||||
|
||||
// StepRecorder records a running execution's steps.
|
||||
type StepRecorder interface {
|
||||
StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error)
|
||||
FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error)
|
||||
}
|
||||
|
||||
// ExecutionCanceller cancels an execution and its current attempt's open
|
||||
// steps in one transaction. It also cancels the callees the execution was
|
||||
// waiting on, and returns their ids (nested callees included) so the caller
|
||||
// can stop their runs too.
|
||||
type ExecutionCanceller interface {
|
||||
CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error)
|
||||
}
|
||||
|
||||
// StepReader lists one execution's recorded steps.
|
||||
type StepReader interface {
|
||||
ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error)
|
||||
}
|
||||
|
||||
// TaskArchiver removes one terminal task's local record with an optimistic
|
||||
// status guard. It is separate from the already broad lifecycle contract so
|
||||
// consumers that only run tasks do not acquire an operator-only capability.
|
||||
type TaskArchiver interface {
|
||||
OutcomePoster
|
||||
ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error)
|
||||
ClearTerminalTasks(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
// TaskRetryer atomically requeues recoverable work and accounts for the new
|
||||
// attempt so a partial write cannot evade the retry cap. retryMode is the
|
||||
// operator's worktree choice for the next dispatch (taskstate.RetryMode),
|
||||
// persisted on the row so the daemon reads it instead of inferring it. resume
|
||||
// is where the attempt starts; a resume whose After stage did not complete in
|
||||
// its last run is refused with ErrResumeIncomplete.
|
||||
type TaskRetryer interface {
|
||||
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string, resume task.Resume, currentDefinition bool) error
|
||||
}
|
||||
|
||||
// ReviewGateResponder records the operator's review-gate answer. A re-review
|
||||
// increments rereview_rounds and requeues; one past the cap returns
|
||||
// ErrRereviewCapReached and writes nothing.
|
||||
type ReviewGateResponder interface {
|
||||
RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error
|
||||
}
|
||||
|
||||
// RemediationStarter queues a review-triggered remediation for an Archie-owned
|
||||
// open-PR task: one guarded transition that carries the JSON-encoded review
|
||||
// unit in the same write, so a claimed remediation always has its input. Runs
|
||||
// for one task are serialised, so a distinct review that arrives while a
|
||||
// remediation owns the task is queued behind it and remediated once that run
|
||||
// finishes; a re-delivered unit is absorbed, not queued twice.
|
||||
// UpdateReviewPayload merges late-arriving comments into the unclaimed unit
|
||||
// for the same review, active or queued behind a running remediation.
|
||||
type RemediationStarter interface {
|
||||
BeginRemediation(ctx context.Context, taskID int64, payload string) error
|
||||
UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error
|
||||
// SetReviewCursors persists the poll backstop's per-task review and
|
||||
// comment high-water marks (pr-review-remediation.md decision 2). The
|
||||
// pr_open guard is part of the contract: cursors only move while no
|
||||
// remediation run owns the task.
|
||||
SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error
|
||||
}
|
||||
|
||||
// OutcomePoster tracks which finished chat tasks have reported back to their
|
||||
// conversation.
|
||||
type OutcomePoster interface {
|
||||
// UnpostedOutcomes returns finished chat tasks whose outcome has not been
|
||||
// posted to the conversation that created them.
|
||||
UnpostedOutcomes(ctx context.Context) ([]*task.Task, error)
|
||||
// MarkOutcomePosted records that the task's state at status was posted.
|
||||
MarkOutcomePosted(ctx context.Context, taskID int64, status string) error
|
||||
}
|
||||
|
||||
// TaskQueries groups read-only task accessors.
|
||||
type TaskQueries interface {
|
||||
TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
|
||||
OpenPRs(ctx context.Context) ([]task.Task, error)
|
||||
// ActiveTasksByOrigin returns the queued and running tasks the
|
||||
// conversation origin created, for its /stop.
|
||||
ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error)
|
||||
// Tasks returns the most recently updated tasks.
|
||||
Tasks(ctx context.Context, limit int) ([]task.Task, error)
|
||||
// TasksPage returns one page of tasks, most recently updated first.
|
||||
TasksPage(ctx context.Context, page TaskPage) ([]task.Task, error)
|
||||
StatusCounts(ctx context.Context) (map[string]int, error)
|
||||
}
|
||||
|
||||
// TaskEvents groups observability and lifecycle methods.
|
||||
type TaskEvents interface {
|
||||
InsertEvent(ctx context.Context, e events.Event) (int64, error)
|
||||
EventsSince(ctx context.Context, cursor string, limit int) ([]events.Event, error)
|
||||
// TaskEvents returns a task's timeline, without agent transcripts.
|
||||
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
|
||||
// TaskTranscript returns one attempt's agent transcript entries in order.
|
||||
TaskTranscript(ctx context.Context, taskID int64, attempt int) ([]events.Event, error)
|
||||
WorkflowStats(ctx context.Context) ([]WorkflowStat, error)
|
||||
StageStats(ctx context.Context) ([]StageStat, error)
|
||||
TokensByDay(ctx context.Context, days int) ([]DayTokens, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// TaskPage selects one page of the task list. Empty Statuses matches every
|
||||
// status. A zero After starts at the newest task; otherwise the page begins
|
||||
// after the task it names, in (updated_at, id) descending order.
|
||||
type TaskPage struct {
|
||||
Statuses []string
|
||||
// Workflow, when set, keeps only that workflow's tasks.
|
||||
Workflow string
|
||||
After TaskCursor
|
||||
Limit int
|
||||
}
|
||||
|
||||
// TaskCursor is the position of the last task a page returned.
|
||||
type TaskCursor struct {
|
||||
UpdatedAt time.Time
|
||||
ID int64
|
||||
}
|
||||
|
||||
// WorkflowCaller starts a workflow.call callee and reads it back.
|
||||
type WorkflowCaller = task.Caller
|
||||
|
||||
// TaskLogStore reads one task attempt's log. Found=false means no log;
|
||||
// ErrTaskLogsUnavailable means this process cannot read logs.
|
||||
type TaskLogStore interface {
|
||||
// TaskLog returns a page of one attempt's decoded log. attempt 0 selects
|
||||
// the task's current attempt.
|
||||
TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error)
|
||||
// TaskLogContent writes one attempt's log verbatim to w, for a download.
|
||||
// found is false, with a nil error, when the attempt has no log file.
|
||||
TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (found bool, err error)
|
||||
}
|
||||
|
||||
// WorkflowStat is one row of the per-workflow metrics table.
|
||||
type WorkflowStat struct {
|
||||
Workflow string `json:"workflow"`
|
||||
Runs int `json:"runs"`
|
||||
Merged int `json:"merged"`
|
||||
Completed int `json:"completed"`
|
||||
PROpen int `json:"pr_open"`
|
||||
Parked int `json:"parked"`
|
||||
AvgTokens int `json:"avg_tokens"`
|
||||
AvgSteps float64 `json:"avg_steps"`
|
||||
TotalToken int `json:"total_tokens"`
|
||||
// Running and LastStatus describe the workflow now: how many of its runs
|
||||
// are working, and how its newest one ended.
|
||||
Running int `json:"running"`
|
||||
LastStatus string `json:"last_status"`
|
||||
}
|
||||
|
||||
// StageStat is average stage duration and failure counts per stage.
|
||||
type StageStat struct {
|
||||
Workflow string `json:"workflow"`
|
||||
Stage string `json:"stage"`
|
||||
Runs int `json:"runs"`
|
||||
AvgMs int `json:"avg_ms"`
|
||||
Errors int `json:"errors"`
|
||||
}
|
||||
|
||||
// DayTokens is token spend per UTC day.
|
||||
type DayTokens struct {
|
||||
Day string `json:"day"`
|
||||
Tokens int `json:"tokens"`
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func (a AgentStage) Stage() Stage {
|
||||
// The agent call is a child of the stage's recorded step: the store
|
||||
// says what the stage's runtime did, not just what the stage did.
|
||||
res, runErr := tc.RunAgentChild(ctx, a.Name, a.Model, modelRef, func() (agentrun.Result, error) {
|
||||
return tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter(ctx, a.Name))
|
||||
return tc.Agent.Run(ctx, tc.Dir, req, tc.reporter(ctx, a.Name))
|
||||
})
|
||||
return a.handleResult(ctx, tc, req, res, runErr, modelRef)
|
||||
}}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
// fakeBudgetRunner is an agent runner whose stage exhausted its budget.
|
||||
type fakeBudgetRunner struct{ res agentrun.Result }
|
||||
|
||||
func (f fakeBudgetRunner) Run(context.Context, string, agentrun.Request, agentrun.ToolCallReporter) (agentrun.Result, error) {
|
||||
func (f fakeBudgetRunner) Run(context.Context, string, agentrun.Request, agentrun.Reporter) (agentrun.Result, error) {
|
||||
return f.res, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -36,8 +36,8 @@ type handoffSettings struct {
|
||||
Detail string `yaml:"detail" doc:"Why the task was handed off."`
|
||||
}
|
||||
|
||||
// newHandoffStage requeues the task under another workflow: the same task,
|
||||
// not a child run, so its history stays in one place.
|
||||
// newHandoffStage completes the run and starts a linked run of another
|
||||
// workflow on the same work item.
|
||||
func newHandoffStage(settings yaml.Node) (Stage, error) {
|
||||
s, err := decodeSettings[handoffSettings](HandoffStepName, settings)
|
||||
if err != nil {
|
||||
@@ -47,8 +47,7 @@ func newHandoffStage(settings yaml.Node) (Stage, error) {
|
||||
return Stage{}, fmt.Errorf("%s: settings.workflow is required", HandoffStepName)
|
||||
}
|
||||
return Stage{Name: HandoffStepName, Run: func(_ context.Context, tc *TaskContext) error {
|
||||
tc.Task.Workflow = strings.TrimSpace(s.Workflow)
|
||||
tc.Outcome = Outcome{Status: StatusQueued, Detail: s.Detail}
|
||||
tc.Outcome = Outcome{Status: StatusCompleted, Detail: s.Detail, Handoff: strings.TrimSpace(s.Workflow)}
|
||||
return nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
@@ -387,3 +387,37 @@ func hasStepType(node any, types []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RepairDefinitionCollection rebuilds a stored collection that no longer
|
||||
// validates, keeping every entry it can: a valid entry is kept, an invalid
|
||||
// shipped entry is replaced by this build's copy, and any other invalid or
|
||||
// duplicate entry is removed and its id returned. An unreadable document or a
|
||||
// repair that still fails validation is an error.
|
||||
func RepairDefinitionCollection(value []byte, registry StepRegistry) (WorkflowDefinitionCollection, []string, error) {
|
||||
var stored WorkflowDefinitionCollection
|
||||
if err := json.Unmarshal(value, &stored); err != nil {
|
||||
return WorkflowDefinitionCollection{}, nil, err
|
||||
}
|
||||
shipped := ShippedDefinitions()
|
||||
seen := make(map[string]struct{}, len(stored.Definitions))
|
||||
var repaired WorkflowDefinitionCollection
|
||||
var removed []string
|
||||
for _, entry := range stored.Definitions {
|
||||
if _, dup := seen[entry.ID]; dup {
|
||||
removed = append(removed, entry.ID)
|
||||
continue
|
||||
}
|
||||
seen[entry.ID] = struct{}{}
|
||||
if definition, err := ParseDefinition(entry.YAML, registry); err == nil && definition.ID == entry.ID {
|
||||
repaired.Definitions = append(repaired.Definitions, entry)
|
||||
} else if factory, ok := shipped.DefinitionByID(entry.ID); ok {
|
||||
repaired.Definitions = append(repaired.Definitions, factory)
|
||||
} else {
|
||||
removed = append(removed, entry.ID)
|
||||
}
|
||||
}
|
||||
if err := ValidateDefinitionCollection(repaired, registry); err != nil {
|
||||
return WorkflowDefinitionCollection{}, nil, err
|
||||
}
|
||||
return repaired, removed, nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A stored collection that stopped validating keeps every entry it can: valid
|
||||
// entries stay, a broken shipped entry is restored, a broken custom one goes.
|
||||
func TestRepairDefinitionCollection(t *testing.T) {
|
||||
shipped, _ := ShippedDefinitions().DefinitionByID("triage")
|
||||
custom := strings.Replace(shipped.YAML, "id: triage", "id: mine", 1)
|
||||
edited := shipped.YAML + "\n# edited by the operator\n"
|
||||
broken := "id: broken\nsteps:\n - id: a\n type: removed.step\n"
|
||||
// with is the shipped set with triage's YAML swapped and extra appended.
|
||||
with := func(triage string, extra ...WorkflowDefinitionEntry) ([]WorkflowDefinitionEntry, map[string]string) {
|
||||
entries, byID := []WorkflowDefinitionEntry{}, map[string]string{}
|
||||
for _, entry := range ShippedDefinitions().Definitions {
|
||||
if entry.ID == "triage" {
|
||||
entry.YAML = triage
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
byID[entry.ID] = entry.YAML
|
||||
}
|
||||
for _, entry := range extra {
|
||||
entries = append(entries, entry)
|
||||
byID[entry.ID] = entry.YAML
|
||||
}
|
||||
return entries, byID
|
||||
}
|
||||
restoredStored, _ := with(broken, WorkflowDefinitionEntry{ID: "mine", YAML: custom})
|
||||
_, restoredWant := with(shipped.YAML, WorkflowDefinitionEntry{ID: "mine", YAML: custom})
|
||||
editedStored, _ := with(edited, WorkflowDefinitionEntry{ID: "broken", YAML: broken})
|
||||
_, editedWant := with(edited)
|
||||
tests := []struct {
|
||||
name string
|
||||
stored []WorkflowDefinitionEntry
|
||||
want map[string]string
|
||||
wantRemoved []string
|
||||
}{
|
||||
{
|
||||
name: "broken shipped entry is restored, custom kept",
|
||||
stored: restoredStored,
|
||||
want: restoredWant,
|
||||
},
|
||||
{
|
||||
name: "broken custom entry is removed, edited shipped kept",
|
||||
stored: editedStored,
|
||||
want: editedWant,
|
||||
wantRemoved: []string{"broken"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
value, err := json.Marshal(WorkflowDefinitionCollection{Definitions: tt.stored})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, removed, err := RepairDefinitionCollection(value, triageRegistry())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := map[string]string{}
|
||||
for _, entry := range got.Definitions {
|
||||
byID[entry.ID] = entry.YAML
|
||||
}
|
||||
if len(byID) != len(tt.want) {
|
||||
t.Fatalf("kept %d entries, want %d", len(byID), len(tt.want))
|
||||
}
|
||||
for id, yaml := range tt.want {
|
||||
if byID[id] != yaml {
|
||||
t.Errorf("entry %q not kept as expected", id)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(removed, tt.wantRemoved) {
|
||||
t.Errorf("removed %v, want %v", removed, tt.wantRemoved)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func runBaselineFix(ctx context.Context, tc *TaskContext, argv []string, out []b
|
||||
}
|
||||
|
||||
res, agentErr := tc.RunAgentChild(ctx, "baseline-fix", "", modelRef, func() (agentrun.Result, error) {
|
||||
return tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter(ctx, "baseline-fix"))
|
||||
return tc.Agent.Run(ctx, tc.Dir, req, tc.reporter(ctx, "baseline-fix"))
|
||||
})
|
||||
if agentErr != nil && res.Version == 0 {
|
||||
return baselineFixFailedError(argv, string(out), fmt.Sprintf("the builder could not run: %v", agentErr))
|
||||
|
||||
@@ -579,7 +579,7 @@ func runReviewerAgent(
|
||||
if err != nil {
|
||||
return agentrun.Result{}, err
|
||||
}
|
||||
res, runErr := tc.Agent.Run(ctx, tc.prReview.snapshotDir, req, tc.toolCallReporter(ctx, name))
|
||||
res, runErr := tc.Agent.Run(ctx, tc.prReview.snapshotDir, req, tc.reporter(ctx, name))
|
||||
tc.prReview.tokensSpent.Add(int64(res.TokensUsed))
|
||||
to, detail := taskstate.StepSucceeded, res.Summary
|
||||
switch {
|
||||
@@ -805,7 +805,7 @@ func runPRReviewAgentRecorded(
|
||||
CaptureTools: captureTools,
|
||||
}
|
||||
res, err := tc.RunAgentChild(ctx, name, "", modelRef, func() (agentrun.Result, error) {
|
||||
return tc.Agent.Run(ctx, workspace, req, tc.toolCallReporter(ctx, name))
|
||||
return tc.Agent.Run(ctx, workspace, req, tc.reporter(ctx, name))
|
||||
})
|
||||
tc.prReview.tokensSpent.Add(int64(res.TokensUsed))
|
||||
return res, err
|
||||
|
||||
@@ -113,7 +113,7 @@ func runRepoTooling(ctx context.Context, tc *TaskContext) error {
|
||||
}
|
||||
|
||||
type repoCommitSettings struct {
|
||||
Message string `yaml:"message" doc:"The commit message."`
|
||||
Message string `yaml:"message" doc:"The commit message. Hooks in the checkout never run, so commit-message policy (commitlint, DCO) is not applied."`
|
||||
// Reference is the verb that links the commit to the task's issue
|
||||
// ("Fixes", "Implements", "Refs"); empty links nothing.
|
||||
Reference string `yaml:"reference" enum:"Fixes,Implements,Refs" doc:"How the commit links to the task issue."`
|
||||
|
||||
@@ -16,4 +16,8 @@ type Caller interface {
|
||||
// call_parent_task_id is callerTaskID, so a caller reads only its own
|
||||
// callees.
|
||||
CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (status, detail string, outputs map[string]any, err error)
|
||||
// Handoff completes the running task fromTaskID with detail and starts
|
||||
// its linked successor on the same work item under workflow, returning
|
||||
// the successor.
|
||||
Handoff(ctx context.Context, fromTaskID int64, workflow, detail string) (*Task, error)
|
||||
}
|
||||
@@ -141,6 +141,10 @@ type Task struct {
|
||||
// one; 0 on a root run. A caller reads only the tasks it started,
|
||||
// through WorkflowCallStatus.
|
||||
CallParentTaskID int64 `json:"call_parent_task_id,omitempty"`
|
||||
// HandoffFromTaskID is the run whose workflow.handoff started this one,
|
||||
// and HandoffToTaskID the run this one handed off to; 0 when none.
|
||||
HandoffFromTaskID int64 `json:"handoff_from_task_id,omitempty"`
|
||||
HandoffToTaskID int64 `json:"handoff_to_task_id,omitempty"`
|
||||
// CallDepth counts workflow.call hops from the root run. The engine
|
||||
// refuses a call past workflow.MaxCallDepth, and the store re-checks on
|
||||
// insert, so no enqueue path can pass the limit.
|
||||
|
||||
@@ -45,6 +45,11 @@ type recordedForge struct {
|
||||
deliveries Deliveries
|
||||
}
|
||||
|
||||
func (f recordedForge) CreateIssue(ctx context.Context, owner, repo, title, _ string, _ []string) (int, error) {
|
||||
f.deliveries.Record(ctx, fmt.Sprintf("open issue %q in %s/%s", title, owner, repo))
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (f recordedForge) CloseIssue(ctx context.Context, owner, repo string, number int, _ string) error {
|
||||
f.deliveries.Record(ctx, fmt.Sprintf("close issue %s/%s#%d", owner, repo, number))
|
||||
return nil
|
||||
|
||||
@@ -64,7 +64,7 @@ type fakePromptRunner struct {
|
||||
mission string
|
||||
}
|
||||
|
||||
func (f *fakePromptRunner) Run(_ context.Context, workspace string, req agentrun.Request, _ agentrun.ToolCallReporter) (agentrun.Result, error) {
|
||||
func (f *fakePromptRunner) Run(_ context.Context, workspace string, req agentrun.Request, _ agentrun.Reporter) (agentrun.Result, error) {
|
||||
f.workspace = workspace
|
||||
f.mission = req.Mission
|
||||
return f.res, nil
|
||||
|
||||
@@ -206,7 +206,7 @@ func (tc *TaskContext) Emit(ctx context.Context, kind, stage, detail string, dat
|
||||
|
||||
// Activity belongs to the recorded stage, even when an agent uses its own name.
|
||||
func (tc *TaskContext) activityData(kind string, data map[string]any) map[string]any {
|
||||
if tc.StepID == 0 || (kind != events.KindToolCall && kind != events.KindAgentFinish) {
|
||||
if tc.StepID == 0 || (kind != events.KindToolCall && kind != events.KindAgentFinish && kind != events.KindAgentTranscript) {
|
||||
return data
|
||||
}
|
||||
out := make(map[string]any, len(data)+2)
|
||||
@@ -239,23 +239,49 @@ func (tc *TaskContext) EmitDurable(ctx context.Context, kind, stage, detail stri
|
||||
return nil
|
||||
}
|
||||
|
||||
// toolCallReporter builds the agentrun.ToolCallReporter an agent stage passes
|
||||
// to tc.Agent.Run, so every completed tool call during that run surfaces as a
|
||||
// tool_call event on the task timeline. Safe to call on a nil Bus: Emit no-ops.
|
||||
func (tc *TaskContext) toolCallReporter(ctx context.Context, stage string) agentrun.ToolCallReporter {
|
||||
return func(report agentrun.ToolCallReport) {
|
||||
tc.Emit(ctx, events.KindToolCall, stage, report.Detail, map[string]any{
|
||||
"tool": report.Tool,
|
||||
"failed": report.Failed,
|
||||
})
|
||||
// reporter builds the agentrun.Reporter an agent stage passes to
|
||||
// tc.Agent.Run: every completed tool call surfaces as a tool_call event on the
|
||||
// task timeline, and every transcript entry is persisted as an
|
||||
// agent_transcript event so it outlives the container. A transcript entry
|
||||
// that cannot be persisted is logged and dropped; it never fails the run.
|
||||
func (tc *TaskContext) reporter(ctx context.Context, stage string) agentrun.Reporter {
|
||||
return agentrun.Reporter{
|
||||
ToolCall: func(report agentrun.ToolCallReport) {
|
||||
tc.Emit(ctx, events.KindToolCall, stage, report.Detail, map[string]any{
|
||||
"tool": report.Tool,
|
||||
"failed": report.Failed,
|
||||
})
|
||||
},
|
||||
Transcript: func(entry agentrun.TranscriptEntry) {
|
||||
data, err := transcriptData(entry)
|
||||
if err == nil {
|
||||
err = tc.EmitDurable(ctx, events.KindAgentTranscript, stage, entry.Kind, data)
|
||||
}
|
||||
if err != nil && tc.Log != nil {
|
||||
tc.Log.WarnContext(ctx, "agent transcript entry not recorded",
|
||||
"task", tc.Task.ID, "stage", stage, "seq", entry.Seq, "err", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func transcriptData(entry agentrun.TranscriptEntry) (map[string]any, error) {
|
||||
encoded, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var data map[string]any
|
||||
return data, json.Unmarshal(encoded, &data)
|
||||
}
|
||||
|
||||
// Outcome is a stage's terminal decision for the whole workflow. Stages
|
||||
// that don't end the workflow leave it zero.
|
||||
type Outcome struct {
|
||||
Status string // Status* value; empty = continue to next stage
|
||||
Detail string // park reason / close rationale / PR body context
|
||||
// Handoff names the workflow a linked successor run starts under once
|
||||
// this run completes; empty starts none.
|
||||
Handoff string
|
||||
}
|
||||
|
||||
// Stage is one named step. Returning an error parks the task with the
|
||||
@@ -484,6 +510,26 @@ func publishEvent(ctx context.Context, tc *TaskContext, e events.Event) {
|
||||
tc.Bus.Publish(ctx, e)
|
||||
}
|
||||
|
||||
// handoff completes the run and starts its linked successor in one store
|
||||
// write, so the work item keeps exactly one current run.
|
||||
func handoff(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
if tc.Calls == nil {
|
||||
park(ctx, tc, "workflow.handoff: this runner cannot start a linked run")
|
||||
return
|
||||
}
|
||||
next, err := tc.Calls.Handoff(ctx, tc.Task.ID, tc.Outcome.Handoff, tc.Outcome.Detail)
|
||||
if err != nil {
|
||||
log.ErrorContext(ctx, "workflow handoff failed", "err", err)
|
||||
park(ctx, tc, fmt.Sprintf("workflow.handoff to %s: %v", tc.Outcome.Handoff, err))
|
||||
return
|
||||
}
|
||||
tc.Task.HandoffToTaskID = next.ID
|
||||
tc.Emit(ctx, events.KindOutcome, tc.Stage, tc.Outcome.Detail, map[string]any{
|
||||
"status": tc.Outcome.Status, "handoff_task_id": next.ID, "workflow": tc.Outcome.Handoff,
|
||||
})
|
||||
log.InfoContext(ctx, "workflow handed off", "workflow", tc.Outcome.Handoff, "task", next.ID)
|
||||
}
|
||||
|
||||
func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
t := tc.Task
|
||||
if tc.Outcome.Status == StatusParked {
|
||||
@@ -502,6 +548,10 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
park(ctx, tc, fmt.Sprintf("persist workflow outcome: %v", err))
|
||||
return
|
||||
}
|
||||
if tc.Outcome.Handoff != "" {
|
||||
handoff(ctx, tc, log)
|
||||
return
|
||||
}
|
||||
if err := tc.Store.Transition(ctx, t.ID, StatusRunning, tc.Outcome.Status, tc.Outcome.Detail); err != nil {
|
||||
log.ErrorContext(ctx, "workflow outcome transition failed", "err", err)
|
||||
return
|
||||
|
||||
@@ -37,6 +37,10 @@ func (c *callSpy) StartCall(_ context.Context, callerTaskID int64, callKey, _ st
|
||||
return child, nil
|
||||
}
|
||||
|
||||
func (c *callSpy) Handoff(context.Context, int64, string, string) (*task.Task, error) {
|
||||
return nil, errors.New("no handoff")
|
||||
}
|
||||
|
||||
func (c *callSpy) CallStatus(context.Context, int64, int64) (string, string, map[string]any, error) {
|
||||
return StatusCompleted, "", nil, nil
|
||||
}
|
||||
@@ -384,6 +388,10 @@ func (c *wobblyCaller) StartCall(_ context.Context, callerTaskID int64, _, _ str
|
||||
return &task.Task{ID: 42, CallParentTaskID: callerTaskID}, nil
|
||||
}
|
||||
|
||||
func (c *wobblyCaller) Handoff(context.Context, int64, string, string) (*task.Task, error) {
|
||||
return nil, errors.New("no handoff")
|
||||
}
|
||||
|
||||
func (c *wobblyCaller) CallStatus(context.Context, int64, int64) (string, string, map[string]any, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
@@ -22,8 +22,12 @@ const (
|
||||
KindAgentFinish = "agent_finish" // data: status, stop_reason, tokens, iterations, model, prompt_tokens, completion_tokens, cached_tokens, cache_creation_tokens
|
||||
// KindToolCall marks one completed tool invocation during an agent stage
|
||||
// run. Only emitted for runners that execute in the same process as their
|
||||
// tools; see agentexec.ToolCallReporter.
|
||||
// tools; see agentrun.Reporter.
|
||||
KindToolCall = "tool_call" // data: tool, failed
|
||||
// KindAgentTranscript is one entry of an agent run's conversation: a
|
||||
// prompt, a model response, a tool call or a compaction. detail: the
|
||||
// entry kind; data: agentrun.TranscriptEntry's fields.
|
||||
KindAgentTranscript = "agent_transcript"
|
||||
// KindDeliveryRecorded records one outward delivery a test run did not
|
||||
// perform: a forge write, a push, an HTTP request, a central tool call.
|
||||
// detail: what it would have done, phrased "would ...".
|
||||
|
||||
@@ -38,6 +38,10 @@ type IssueForge interface {
|
||||
// Comment posts an issue (or PR) comment and returns its id.
|
||||
Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error)
|
||||
|
||||
// CreateIssue opens an issue with title, body and optional labels,
|
||||
// returning its number.
|
||||
CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error)
|
||||
|
||||
// CloseIssue closes an issue with an optional final comment.
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
|
||||
|
||||
@@ -30,6 +30,10 @@ func (n *NoopForge) Comment(ctx context.Context, owner, repo string, number int,
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (n *NoopForge) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (n *NoopForge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
const (
|
||||
SubjectComment = "archie.forge.comment"
|
||||
SubjectCreateIssue = "archie.forge.create_issue"
|
||||
SubjectCloseIssue = "archie.forge.close_issue"
|
||||
SubjectCreatePR = "archie.forge.create_pr"
|
||||
SubjectLinkBranch = "archie.forge.link_branch"
|
||||
@@ -35,8 +36,9 @@ const (
|
||||
// set a task of that identity may publish to.
|
||||
func Subjects(identity string) []string {
|
||||
bases := []string{
|
||||
SubjectComment, SubjectCloseIssue, SubjectCreatePR, SubjectLinkBranch,
|
||||
SubjectSetStateLabel, SubjectCreateReviewComment, SubjectReplyToReview,
|
||||
SubjectComment, SubjectCreateIssue, SubjectCloseIssue, SubjectCreatePR,
|
||||
SubjectLinkBranch, SubjectSetStateLabel, SubjectCreateReviewComment,
|
||||
SubjectReplyToReview,
|
||||
}
|
||||
out := make([]string, len(bases))
|
||||
for i, base := range bases {
|
||||
@@ -80,6 +82,17 @@ type CommentResponse struct {
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
type CreateIssueRequest struct {
|
||||
Target
|
||||
Title, Body string
|
||||
Labels []string
|
||||
}
|
||||
|
||||
type CreateIssueResponse struct {
|
||||
Number int `json:"number"`
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
type CloseIssueRequest struct {
|
||||
Target
|
||||
Number int
|
||||
@@ -168,6 +181,7 @@ func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func()
|
||||
}
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: serverSubject(identity, SubjectComment), Handler: as(s.handleComment)},
|
||||
{Subject: serverSubject(identity, SubjectCreateIssue), Handler: as(s.handleCreateIssue)},
|
||||
{Subject: serverSubject(identity, SubjectCloseIssue), Handler: as(s.handleCloseIssue)},
|
||||
{Subject: serverSubject(identity, SubjectCreatePR), Handler: as(s.handleCreatePR)},
|
||||
{Subject: serverSubject(identity, SubjectLinkBranch), Handler: as(s.handleLinkBranch)},
|
||||
@@ -249,6 +263,21 @@ func (s *Server) handleComment(ctx context.Context, identity string, msg *nats.M
|
||||
s.respond(msg, CommentResponse{ID: id, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateIssue(ctx context.Context, identity string, msg *nats.Msg) {
|
||||
var req CreateIssueRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, CreateIssueResponse{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode create_issue request: %w", err))})
|
||||
return
|
||||
}
|
||||
client, err := s.authorizedForge(ctx, identity, req.Target, "comment")
|
||||
if err != nil {
|
||||
s.respond(msg, CreateIssueResponse{Envelope: natsrpc.NewEnvelope(err)})
|
||||
return
|
||||
}
|
||||
number, err := client.CreateIssue(ctx, req.Owner, req.Repo, req.Title, req.Body, req.Labels)
|
||||
s.respond(msg, CreateIssueResponse{Number: number, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleCloseIssue(ctx context.Context, identity string, msg *nats.Msg) {
|
||||
var req CloseIssueRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
@@ -392,6 +421,18 @@ func (c *Client) Comment(ctx context.Context, owner, repo string, number int, bo
|
||||
return resp.ID, nil
|
||||
}
|
||||
|
||||
func (c *Client) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
|
||||
req := CreateIssueRequest{Target: c.target(owner, repo), Title: title, Body: body, Labels: labels}
|
||||
resp, err := natsrpc.Call[CreateIssueResponse](ctx, c.rpc(), c.subject(SubjectCreateIssue), req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := resp.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return resp.Number, nil
|
||||
}
|
||||
|
||||
func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
req := CloseIssueRequest{Target: c.target(owner, repo), Number: number, Comment: comment}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectCloseIssue), req)
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// maxIssueListed bounds what issue_list returns, so a large backlog does not
|
||||
// land in the context window whole.
|
||||
const maxIssueListed = 200
|
||||
|
||||
// IssueSource is the forge surface the issue tools use, reached through the
|
||||
// daemon.
|
||||
type IssueSource interface {
|
||||
OpenIssues(ctx context.Context, owner, repo string) ([]forge.Issue, error)
|
||||
CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error)
|
||||
}
|
||||
|
||||
// IssueSummary is one open issue as issue_list shows it.
|
||||
type IssueSummary struct {
|
||||
Number int `json:"number"`
|
||||
Title string `json:"title"`
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
}
|
||||
|
||||
// IssueTools returns issue_list and issue_create for curators. Filing work
|
||||
// feeds the daemon's issue intake, so both are checked as acting on tasks.
|
||||
// Nil source or authorizer registers none.
|
||||
func IssueTools(source IssueSource, authz access.Authorizer) []tools.ToolEntry {
|
||||
if source == nil || authz == nil {
|
||||
return nil
|
||||
}
|
||||
return []tools.ToolEntry{
|
||||
guarded(authz, access.ActionRead, access.KindTask, nil, issueListTool(source)),
|
||||
guarded(authz, access.ActionCreate, access.KindTask, nil, issueCreateTool(source)),
|
||||
}
|
||||
}
|
||||
|
||||
var repoProperty = map[string]any{
|
||||
"type": "string",
|
||||
"description": "The repository as owner/name, as run_list reports it.",
|
||||
}
|
||||
|
||||
func splitRepo(input map[string]any) (owner, repo string, err error) {
|
||||
raw, _ := input["repo"].(string)
|
||||
owner, repo, ok := strings.Cut(strings.TrimSpace(raw), "/")
|
||||
if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") {
|
||||
return "", "", fmt.Errorf("repo must be owner/name")
|
||||
}
|
||||
return owner, repo, nil
|
||||
}
|
||||
|
||||
func issueListTool(source IssueSource) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "issue_list",
|
||||
Toolset: "issues",
|
||||
Description: "List a repository's open issues (number, title, labels). Check it before filing so you never duplicate one.",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{"repo": repoProperty},
|
||||
"required": []string{"repo"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
owner, repo, err := splitRepo(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_list: %w", err)
|
||||
}
|
||||
issues, err := source.OpenIssues(ctx, owner, repo)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_list: %w", err)
|
||||
}
|
||||
out := make([]IssueSummary, 0, min(len(issues), maxIssueListed))
|
||||
for _, is := range issues[:min(len(issues), maxIssueListed)] {
|
||||
out = append(out, IssueSummary{Number: is.Number, Title: is.Title, Labels: is.Labels})
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func issueCreateTool(source IssueSource) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "issue_create",
|
||||
Toolset: "issues",
|
||||
Description: "File a new issue in a repository. List open issues first and file only work no open issue covers. " +
|
||||
"The body must cite the run that produced it.",
|
||||
Classification: tools.ClassMutating,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"repo": repoProperty,
|
||||
"title": map[string]any{"type": "string"},
|
||||
"body": map[string]any{"type": "string"},
|
||||
"labels": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
|
||||
},
|
||||
"required": []string{"repo", "title", "body"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
owner, repo, err := splitRepo(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_create: %w", err)
|
||||
}
|
||||
title, _ := input["title"].(string)
|
||||
body, _ := input["body"].(string)
|
||||
if strings.TrimSpace(title) == "" || strings.TrimSpace(body) == "" {
|
||||
return nil, fmt.Errorf("issue_create: title and body are required")
|
||||
}
|
||||
var labels []string
|
||||
if raw, ok := input["labels"].([]any); ok {
|
||||
for _, l := range raw {
|
||||
if s, ok := l.(string); ok && s != "" {
|
||||
labels = append(labels, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
number, err := source.CreateIssue(ctx, owner, repo, title, body, labels)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("issue_create: %w", err)
|
||||
}
|
||||
return map[string]any{"number": number}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// RunSource is the state-store surface the run-inspection tools use. The
|
||||
// State Store client satisfies it directly.
|
||||
type RunSource interface {
|
||||
// Tasks returns the most recently updated tasks.
|
||||
Tasks(ctx context.Context, limit int) ([]task.Task, error)
|
||||
// TaskEvents returns one task's events, oldest first.
|
||||
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
|
||||
}
|
||||
|
||||
// RunSummary is one task as run_list shows it.
|
||||
type RunSummary struct {
|
||||
ID int64 `json:"id"`
|
||||
Repo string `json:"repo"`
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
Issue int `json:"issue,omitempty"`
|
||||
PRNumber int `json:"pr_number,omitempty"`
|
||||
ParkReason string `json:"park_reason,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// RunEvent is one task event as run_events shows it.
|
||||
type RunEvent struct {
|
||||
At time.Time `json:"at"`
|
||||
Kind string `json:"kind"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// RunTools returns the read-only run-inspection tools for long-running
|
||||
// curators: what ran recently, and each run's event trail. Reads are checked
|
||||
// as reading tasks, the same check the dashboard's task list gets. Nil
|
||||
// source or authorizer registers none.
|
||||
func RunTools(source RunSource, authz access.Authorizer) []tools.ToolEntry {
|
||||
if source == nil || authz == nil {
|
||||
return nil
|
||||
}
|
||||
read := func(entry tools.ToolEntry) tools.ToolEntry {
|
||||
return guarded(authz, access.ActionRead, access.KindTask, nil, entry)
|
||||
}
|
||||
return []tools.ToolEntry{
|
||||
read(runListTool(source)),
|
||||
read(runEventsTool(source)),
|
||||
}
|
||||
}
|
||||
|
||||
func runListTool(source RunSource) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "run_list",
|
||||
Toolset: "runs",
|
||||
Description: "List the most recently updated task runs across the instance, most recent first. " +
|
||||
"Use it to survey what ran, what parked and why.",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"limit": map[string]any{
|
||||
"type": "integer",
|
||||
"description": fmt.Sprintf(
|
||||
"Maximum runs to return. Defaults to %d, capped at %d.",
|
||||
defaultTaskListLimit, maxTaskListLimit,
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
rows, err := source.Tasks(ctx, taskListLimit(input))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("run_list: %w", err)
|
||||
}
|
||||
out := make([]RunSummary, 0, len(rows))
|
||||
for _, t := range rows {
|
||||
out = append(out, RunSummary{
|
||||
ID: t.ID,
|
||||
Repo: t.Owner + "/" + t.Repo,
|
||||
Title: t.Title,
|
||||
Status: t.Status,
|
||||
Workflow: t.Workflow,
|
||||
Issue: t.IssueNumber,
|
||||
PRNumber: t.PRNumber,
|
||||
ParkReason: t.ParkReason,
|
||||
UpdatedAt: t.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func runEventsTool(source RunSource) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "run_events",
|
||||
Toolset: "runs",
|
||||
Description: "List one task run's event trail, oldest first: stage transitions, deliveries, " +
|
||||
"failures and park reasons. Use it to see why a run ended the way it did.",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"task_id": map[string]any{
|
||||
"type": "integer",
|
||||
"description": "The task run's ID, as run_list reports it.",
|
||||
},
|
||||
},
|
||||
"required": []string{"task_id"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
id, ok := asInt64(input["task_id"])
|
||||
if !ok || id <= 0 {
|
||||
return nil, fmt.Errorf("run_events: task_id must be a positive integer")
|
||||
}
|
||||
evs, err := source.TaskEvents(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("run_events: %w", err)
|
||||
}
|
||||
out := make([]RunEvent, 0, len(evs))
|
||||
for _, e := range evs {
|
||||
out = append(out, RunEvent{At: e.At, Kind: e.Kind, Stage: e.Stage, Detail: e.Detail})
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -112,3 +112,84 @@ func TestWorkspaceEnvironment(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanaryGrant pins the scoped canary grant: the one identity it names may
|
||||
// read the signal surface, read and write update-settings, and trigger an
|
||||
// install -- and nothing else, neither for it nor for anyone else. The canary
|
||||
// principal carries the developer role (API-created service accounts are
|
||||
// assigned it); the grant's forbid must keep the role from widening access.
|
||||
func TestCanaryGrant(t *testing.T) {
|
||||
const canaryID = identity.IdentityID("canary-svc")
|
||||
grant := access.CanaryGrantPolicy(org.DefaultOrgID, string(canaryID))
|
||||
forbid := access.CanaryGrantForbidPolicy(org.DefaultOrgID, string(canaryID))
|
||||
engine := New(append(access.ShippedOrgPolicies(org.DefaultOrgID), grant, forbid))
|
||||
if len(engine.Problems()) != 0 {
|
||||
t.Fatalf("problems = %v, want the canary grant to compile", engine.Problems())
|
||||
}
|
||||
canary := access.Principal{
|
||||
IdentityID: canaryID, Org: org.DefaultOrgID,
|
||||
Memberships: []org.Membership{{IdentityID: canaryID, OrgID: org.DefaultOrgID, Role: org.RoleDeveloper}},
|
||||
}
|
||||
other := access.Principal{IdentityID: "someone-else", Org: org.DefaultOrgID}
|
||||
at := func(kind access.ResourceKind, id string) access.Resource {
|
||||
return access.Resource{Kind: kind, ID: id, Org: org.DefaultOrgID}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
principal access.Principal
|
||||
action access.Action
|
||||
resource access.Resource
|
||||
allowed bool
|
||||
}{
|
||||
{"read the dashboard", canary, access.ActionRead, at(access.KindDashboard, ""), true},
|
||||
{"read tasks", canary, access.ActionRead, at(access.KindTask, ""), true},
|
||||
{"read one task", canary, access.ActionRead, at(access.KindTask, "7"), true},
|
||||
{"read update-settings", canary, access.ActionRead, at(access.KindPolicy, "update-settings"), true},
|
||||
{"install an update", canary, access.ActionUpdate, at(access.KindDashboard, "update"), true},
|
||||
{"replace update-settings", canary, access.ActionManageIdentities, at(access.KindPolicy, "update-settings"), true},
|
||||
{"read a secret", canary, access.ActionReadSecret, at(access.KindSecret, "github-token"), false},
|
||||
{"delete a task", canary, access.ActionDelete, at(access.KindTask, "7"), false},
|
||||
{"manage policies", canary, access.ActionManagePolicies, at(access.KindPolicy, "org-role-read"), false},
|
||||
{"run a workflow", canary, access.ActionRun, at(access.KindWorkflow, "triage"), false},
|
||||
{"create anything", canary, access.ActionCreate, at(access.KindTask, ""), false},
|
||||
{"update another object", canary, access.ActionUpdate, at(access.KindDashboard, "other"), false},
|
||||
{"read another object", canary, access.ActionRead, at(access.KindPolicy, "other-policy"), false},
|
||||
{"manage identities on another object", canary, access.ActionManageIdentities, at(access.KindIdentity, "someone-else"), false},
|
||||
{"read logs", canary, access.ActionReadLogs, at(access.KindTask, "7"), false},
|
||||
{"read the audit feed", canary, access.ActionReadAudit, at(access.KindAudit, ""), false},
|
||||
{"a resource of another org", canary, access.ActionRead, access.Resource{Kind: access.KindDashboard, Org: "acme"}, false},
|
||||
{"another identity reads the dashboard", other, access.ActionRead, at(access.KindDashboard, ""), false},
|
||||
{"another identity installs an update", other, access.ActionUpdate, at(access.KindDashboard, "update"), false},
|
||||
{"another identity replaces update-settings", other, access.ActionManageIdentities, at(access.KindPolicy, "update-settings"), false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := engine.Authorize(tt.principal, tt.action, tt.resource, access.Context{})
|
||||
if got.Allowed != tt.allowed {
|
||||
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanaryGrantValidates pins that the canary grant passes the domain's
|
||||
// structural check and the engine's schema validation, so it can be installed
|
||||
// through the policy store.
|
||||
func TestCanaryGrantValidates(t *testing.T) {
|
||||
grant := access.CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
|
||||
forbid := access.CanaryGrantForbidPolicy(org.DefaultOrgID, "canary-svc")
|
||||
for _, p := range []access.Policy{grant, forbid} {
|
||||
if err := p.Validate(); err != nil {
|
||||
t.Fatalf("Validate %s: %v", p.ID, err)
|
||||
}
|
||||
}
|
||||
engine := New([]access.Policy{grant, forbid})
|
||||
for _, p := range []access.Policy{grant, forbid} {
|
||||
if err := engine.Validate(p); err != nil {
|
||||
t.Fatalf("engine Validate %s: %v", p.ID, err)
|
||||
}
|
||||
}
|
||||
if len(engine.Problems()) != 0 {
|
||||
t.Fatalf("problems = %v, want none", engine.Problems())
|
||||
}
|
||||
}
|
||||
@@ -193,6 +193,12 @@ func (d deadlineCaller) StartCall(ctx context.Context, callerTaskID int64, callK
|
||||
return d.Caller.StartCall(ctx, callerTaskID, callKey, wf, inputs)
|
||||
}
|
||||
|
||||
func (d deadlineCaller) Handoff(ctx context.Context, fromTaskID int64, wf, detail string) (*task.Task, error) {
|
||||
ctx, cancel := d.withDeadline(ctx)
|
||||
defer cancel()
|
||||
return d.Caller.Handoff(ctx, fromTaskID, wf, detail)
|
||||
}
|
||||
|
||||
func (d deadlineCaller) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, map[string]any, error) {
|
||||
ctx, cancel := d.withDeadline(ctx)
|
||||
defer cancel()
|
||||
|
||||
@@ -52,3 +52,13 @@ func DefaultUpdateStateDir() string {
|
||||
}
|
||||
return filepath.Join(dir, InstanceName(), "update")
|
||||
}
|
||||
|
||||
// UpdateStateDir is the one resolution of the host's update state directory:
|
||||
// ARCHIE_UPDATE_STATE_DIR when set, else the default. The daemon's
|
||||
// transactions and the dashboard's update snapshot must read the same one.
|
||||
func UpdateStateDir() string {
|
||||
if dir := os.Getenv("ARCHIE_UPDATE_STATE_DIR"); dir != "" {
|
||||
return dir
|
||||
}
|
||||
return DefaultUpdateStateDir()
|
||||
}
|
||||
@@ -221,7 +221,7 @@ func (s *Server) resource(ctx context.Context, orgID, kind string) (storecontrac
|
||||
}
|
||||
return resource, err
|
||||
}
|
||||
if _, err := s.seedKind(ctx, orgID, s.definitions[kind], config.Config{}); err != nil && !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
if _, _, err := s.seedKind(ctx, orgID, s.definitions[kind], config.Config{}); err != nil && !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
return storecontract.Resource{}, err
|
||||
}
|
||||
return s.store.Resource(ctx, orgID, kind)
|
||||
|
||||
@@ -28,6 +28,10 @@ type Definition struct {
|
||||
// Defaults is the factory value clients offer as "restore shipped". Only
|
||||
// resources that ship with content set it.
|
||||
Defaults func() any
|
||||
// Repair rebuilds a stored value this build no longer accepts, keeping what
|
||||
// it can, and names what it removed. Nil means an invalid stored value of a
|
||||
// shipped kind is replaced by the seed.
|
||||
Repair func(stored []byte) (value []byte, removed []string, err error)
|
||||
// SchemaExtensions are merged into the derived schema's top level, for
|
||||
// vocabulary the document type alone cannot express.
|
||||
SchemaExtensions map[string]any
|
||||
@@ -73,6 +77,9 @@ func (d Definition) Decode(input []byte) ([]byte, error) {
|
||||
type SeedSkip struct {
|
||||
Kind string
|
||||
Err error
|
||||
// Removed names entries a repair dropped from a stored value; Err is nil
|
||||
// then, because the kind was written.
|
||||
Removed []string
|
||||
}
|
||||
|
||||
// seedActor is the audit identity seeds write under.
|
||||
@@ -89,7 +96,10 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
|
||||
versions := make(map[string]int64, len(s.ordered))
|
||||
var skipped []SeedSkip
|
||||
for _, definition := range s.ordered {
|
||||
version, err := s.seedKind(ctx, storecontract.DefaultOrgID, definition, cfg)
|
||||
version, removed, err := s.seedKind(ctx, storecontract.DefaultOrgID, definition, cfg)
|
||||
if len(removed) > 0 {
|
||||
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Removed: removed})
|
||||
}
|
||||
var refusal *seedRefusal
|
||||
switch {
|
||||
case errors.As(err, &refusal):
|
||||
@@ -108,9 +118,13 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
|
||||
if resource.OrgID == storecontract.DefaultOrgID || resource.Kind != WorkflowDefinitionsKind {
|
||||
continue
|
||||
}
|
||||
if _, err := s.seedKind(ctx, resource.OrgID, s.definitions[resource.Kind], config.Config{}); err != nil {
|
||||
_, removed, err := s.seedKind(ctx, resource.OrgID, s.definitions[resource.Kind], config.Config{})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(removed) > 0 {
|
||||
skipped = append(skipped, SeedSkip{Kind: resource.Kind, Removed: removed})
|
||||
}
|
||||
}
|
||||
return versions, skipped, nil
|
||||
}
|
||||
@@ -127,30 +141,32 @@ func (r *seedRefusal) Unwrap() error { return r.err }
|
||||
|
||||
// seedKind seeds, refreshes or leaves one kind and returns its version. A
|
||||
// *seedRefusal means the seed failed validation and nothing was written.
|
||||
func (s *Server) seedKind(ctx context.Context, orgID string, definition Definition, cfg config.Config) (int64, error) {
|
||||
func (s *Server) seedKind(ctx context.Context, orgID string, definition Definition, cfg config.Config) (int64, []string, error) {
|
||||
stored, storedErr := s.store.Resource(ctx, orgID, definition.Kind)
|
||||
absent := errors.Is(storedErr, storecontract.ErrResourceNotFound)
|
||||
if storedErr != nil && !absent {
|
||||
return 0, storedErr
|
||||
return 0, nil, storedErr
|
||||
}
|
||||
value, err := definition.seededValue(cfg)
|
||||
if err != nil {
|
||||
// Skipped, not fatal.
|
||||
return 0, &seedRefusal{err: err}
|
||||
return 0, nil, &seedRefusal{err: err}
|
||||
}
|
||||
if !absent && bytes.Equal(stored.Value, value) {
|
||||
// The store already holds what this build seeds. Comparing the values
|
||||
// rather than re-writing them is what keeps a boot from adding a
|
||||
// revision for a document that did not change.
|
||||
return stored.Version, nil
|
||||
return stored.Version, nil, nil
|
||||
}
|
||||
var removed []string
|
||||
if !absent {
|
||||
refresh, err := s.shippedValueIsStale(ctx, orgID, definition)
|
||||
var keep bool
|
||||
value, removed, keep, err = s.replacement(ctx, orgID, definition, stored.Value, value)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, nil, err
|
||||
}
|
||||
if !refresh {
|
||||
return stored.Version, nil
|
||||
if keep {
|
||||
return stored.Version, nil, nil
|
||||
}
|
||||
}
|
||||
write := storecontract.ResourceWrite{
|
||||
@@ -161,9 +177,29 @@ func (s *Server) seedKind(ctx context.Context, orgID string, definition Definiti
|
||||
}
|
||||
resource, err := s.store.PutResource(ctx, write)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("seed %s: %w", definition.Kind, err)
|
||||
return 0, nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
|
||||
}
|
||||
return resource.Version, nil
|
||||
return resource.Version, removed, nil
|
||||
}
|
||||
|
||||
// replacement decides what a seed writes over a stored value: nothing (keep),
|
||||
// a repair of it, or the seeded value. A failed repair falls back to the seed:
|
||||
// an invalid stored value breaks every reader, so keeping it protects nothing.
|
||||
func (s *Server) replacement(ctx context.Context, orgID string, definition Definition, stored, seeded []byte) ([]byte, []string, bool, error) {
|
||||
replace, err := s.storedValueIsReplaced(ctx, orgID, definition, stored)
|
||||
if err != nil {
|
||||
return nil, nil, false, err
|
||||
}
|
||||
if !replace {
|
||||
return nil, nil, true, nil
|
||||
}
|
||||
if definition.Repair == nil || definition.accepts(stored) {
|
||||
return seeded, nil, false, nil
|
||||
}
|
||||
if repaired, removed, err := definition.Repair(stored); err == nil {
|
||||
return repaired, removed, false, nil
|
||||
}
|
||||
return seeded, nil, false, nil
|
||||
}
|
||||
|
||||
// expectedVersion is the optimistic-concurrency guard a seed writes under: the
|
||||
@@ -175,15 +211,24 @@ func expectedVersion(stored storecontract.Resource, absent bool) int64 {
|
||||
return stored.Version
|
||||
}
|
||||
|
||||
// shippedValueIsStale reports whether the newest stored revision of a
|
||||
// shipped document was written by the seed.
|
||||
func (s *Server) shippedValueIsStale(ctx context.Context, orgID string, definition Definition) (bool, error) {
|
||||
// storedValueIsReplaced reports whether a stored shipped document is rewritten
|
||||
// at seed: the seed wrote it, or this build no longer accepts it.
|
||||
func (s *Server) storedValueIsReplaced(ctx context.Context, orgID string, definition Definition, stored []byte) (bool, error) {
|
||||
if definition.Defaults == nil {
|
||||
return false, nil
|
||||
}
|
||||
if !definition.accepts(stored) {
|
||||
return true, nil
|
||||
}
|
||||
return s.seedWroteNewest(ctx, orgID, definition.Kind)
|
||||
}
|
||||
|
||||
// accepts reports whether input decodes under this build's validator.
|
||||
func (d Definition) accepts(input []byte) bool {
|
||||
_, err := d.Decode(input)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// seedWroteNewest reports whether the newest revision of kind was written by a
|
||||
// seed. It reads the ledger rather than the current row because the ledger is
|
||||
// what records who wrote a value, and the row does not.
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package controlplanestore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type memStore struct {
|
||||
resource storecontract.Resource
|
||||
history []storecontract.Resource
|
||||
}
|
||||
|
||||
func (m *memStore) ListResources(context.Context) ([]storecontract.Resource, error) {
|
||||
return []storecontract.Resource{m.resource}, nil
|
||||
}
|
||||
|
||||
func (m *memStore) Resource(context.Context, string, string) (storecontract.Resource, error) {
|
||||
return m.resource, nil
|
||||
}
|
||||
|
||||
func (m *memStore) ResourceHistory(context.Context, string, string, int) ([]storecontract.Resource, error) {
|
||||
return m.history, nil
|
||||
}
|
||||
|
||||
func (m *memStore) PutResource(_ context.Context, w storecontract.ResourceWrite) (storecontract.Resource, error) {
|
||||
m.resource = storecontract.Resource{OrgID: w.OrgID, Kind: w.Kind, Value: w.Value, Version: m.resource.Version + 1}
|
||||
return m.resource, nil
|
||||
}
|
||||
|
||||
// A shipped document an operator edited is kept, unless it no longer validates:
|
||||
// then it is repaired, or replaced by the build's copy when it has no repair.
|
||||
func TestSeedRefreshesStoredShippedDocumentOnlyWhenInvalid(t *testing.T) {
|
||||
definition := Definition{
|
||||
Kind: "shipped",
|
||||
Seed: func(config.Config) any { return "current" },
|
||||
Defaults: func() any { return "current" },
|
||||
Validate: func(in []byte) error {
|
||||
if string(in) != `"current"` && string(in) != `"edited"` {
|
||||
return errors.New("names a deleted step type")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
repair := func([]byte) ([]byte, []string, error) { return []byte(`"edited"`), []string{"gone"}, nil }
|
||||
tests := []struct {
|
||||
name string
|
||||
stored string
|
||||
repair func([]byte) ([]byte, []string, error)
|
||||
want string
|
||||
wantRemoved []string
|
||||
}{
|
||||
{"edited and valid is kept", `"edited"`, repair, `"edited"`, nil},
|
||||
{"invalid is repaired", `"deleted-step"`, repair, `"edited"`, []string{"gone"}},
|
||||
{"invalid without a repair is replaced", `"deleted-step"`, nil, `"current"`, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
store := &memStore{
|
||||
resource: storecontract.Resource{Kind: "shipped", Value: []byte(tt.stored), Version: 3},
|
||||
history: []storecontract.Resource{{Actor: "operator", Source: "dashboard"}},
|
||||
}
|
||||
s := &Server{store: store}
|
||||
definition.Repair = tt.repair
|
||||
_, removed, err := s.seedKind(context.Background(), storecontract.DefaultOrgID, definition, config.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(removed, tt.wantRemoved) {
|
||||
t.Fatalf("removed %v, want %v", removed, tt.wantRemoved)
|
||||
}
|
||||
if got := string(store.resource.Value); got != tt.want {
|
||||
t.Fatalf("stored %s, want %s", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,14 @@ func workflowDefinitionsDefinition(steps workflow.StepRegistry, settings map[str
|
||||
_, err := workflow.DecodeDefinitionCollection(input, steps)
|
||||
return err
|
||||
},
|
||||
Repair: func(stored []byte) ([]byte, []string, error) {
|
||||
collection, removed, err := workflow.RepairDefinitionCollection(stored, steps)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
value, err := json.Marshal(collection)
|
||||
return value, removed, err
|
||||
},
|
||||
SchemaExtensions: map[string]any{"x-step-types": stepTypeVocabulary(steps, settings), "x-intake-routes": workflow.IntakeRoutes()},
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 574 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user