Compare commits

...
20 Commits
Author SHA1 Message Date
sam 19cf9ae2ab chore(release): v1.40.0
deploy / gate (push) Failing after 5m33s
deploy / build-and-push (push) Skipped
deploy / dist-zip (push) Skipped
2026-09-23 13:30:57 +10:00
sam 67c2dff3e1 merge(release): bring the v1.39.0 release commit into sams-cleanup
The branch and main diverged at 8faa0f6a: the release commit was cut on
main while the branch kept advancing with the park-classification wave.
Merging main here first, so main can fast-forward to the branch tip
without a merge on the release side. No content conflicts: the release
commit touches the changelog and news artifacts only.
2026-09-23 13:23:16 +10:00
sam 10dd85443d feat(staterpc,daemon): park classification on the wire and at the park sites
Domain fields ParkClass/RemediationRounds landed in d6f61c2c; this is
the wire and daemon half. Task gains park_class (32) and
remediation_rounds (33) and maps both directions; the classified park
write crosses the wire as ParkTask on a narrow TaskParker contract
(TaskLifecycle stays under the 8-method cap), with conformance
coverage local + grpc including the stale-guard sentinel and
needs_human normalization. Every daemon park site now states its
class: terminal for a repo that left config and a retired identity,
transient for the environmental parks (worktree, storage, grants,
taskrun), and identityMayAct returns the class beside its reason.
2026-09-23 13:18:08 +10:00
sam 53bdbd3309 fix(staterpc): carry park class and remediation rounds across the wire
d6f61c2c added Task.ParkClass and Task.RemediationRounds to the domain
without the wire half; the parity guard went red. Add the two proto
fields (32/33) and map both directions in values.go.
2026-09-23 13:10:31 +10:00
sam 5d6fbd5c30 fix(release): CI owns the release stamp; :latest moves only from a release
Two beads, one root: four sites stamped a version and only two of them were CI.

`Taskfile.yml`'s build and `install.sh` derived GATEWAY_VERSION/RUNTIME_VERSION
from `git describe`, so a from-source build claimed a release it was not
running, and the stamp became a function of the commit graph -- the one input a
content-checksum build cache cannot see. An empty commit moved `git describe`
while `task build` reported "up to date" and shipped the previous stamp
(archie-core-pdq2). Both sites now stamp `dev`: a source build says so, and the
version a release carries is written into the artifact CI publishes. That
removes the non-file input rather than caching it, and traceability for a local
build is the checkout it came from.

`deploy.yml` published `:latest` from any push to main, so a release's own
stamping survived only until the next ordinary commit -- minutes, in an active
repo -- and a host deploying :latest reported dev, leaving the update path
unable to tell current from stale (archie-core-i5nb). `:latest` now moves only
from a commit that IS a release; every other build publishes `:edge` (mutable,
newest main) and `sha-<commit>` (immutable). A host that runs releases follows
`:latest`; a host that tracks main follows `:edge`, which RELEASING.md now says.

Verified: `task build` reports `archied dev`; the new workflow test fails
against the old workflow on all five guards and passes after; deploy.yml
parses; install.sh passes `bash -n`.

Gated with `task check` (exit 0) at 8faa0f6a -- the v1.39.0 base, CI-green --
with these five files applied. It is NOT gated at HEAD: HEAD carries an
unrelated red, `TestTaskProtoCarriesEveryDomainField`, because d6f61c2c added
ParkClass and RemediationRounds without the proto mapping. This change neither
causes nor fixes that.
2026-09-23 13:09:01 +10:00
sam 3940487335 feat(webui): show the park class beside the Parked badge
The classification rides the API for free (taskView embeds task.Task),
so this is the read side only: a parked row shows what kind of
intervention it needs -- needs you, transient, terminal -- as a chip
with the answer in its tooltip, instead of a bare Parked every time.
Non-parked rows render nothing.
2026-09-23 12:57:27 +10:00
sam d6f61c2c6f feat(workflow): typed park classification and split remediation budgets
The F2+F3 schema wave from the auto-fix/resume investigation, sequenced
together as one migration. Every failure funneled to one parked status
with free-text ParkReason, and Task.RetryCount doubled as the
operator-retry budget and the review-remediation round budget -- so N
operator retries ate the remediation budget, a repo-level round cap
could re-park a task an operator had just legally retried, and no
surface could answer what a park needed from an operator.

Park class (F2): a producer-recorded vocabulary in taskstate --
needs_human (the default, so an unclassified park always reads as
operator-actionable), transient (environmental; a requeue can succeed),
terminal (retrying is pointless). Recorded at the park site, never
inferred from reason text; NormalizeParkClass makes unknown values
persist as needs_human. Transition-to-parked defaults the class, so
every existing unclassified park site reads correctly with no call-site
churn; the classified ParkTask write follows for parks that know
better. Requeue, RetryTask and BeginRemediation clear the class back to
the default with the reason.

Split budgets (F3): Task.RemediationRounds is the remediation's own
budget; RetryCount stays the operator's. The round-cap stage counts and
caps rounds; operator retry keeps counting RetryCount and can drive a
task to dead without touching rounds. remediation_rounds is a
presence-gated migrator column written through Update.

Known state: proto fields, the ParkTask RPC, the staterpc mapping and
the daemon-side park-site classification follow in the wire half of
this wave (the proto parity test is intentionally red until then).
2026-09-23 12:55:03 +10:00
sam ee78bfa7bc chore(release): v1.39.0
deploy / gate (push) Failing after 5m48s
deploy / build-and-push (push) Skipped
deploy / dist-zip (push) Skipped
2026-09-23 12:53:48 +10:00
sam 8faa0f6a30 feat(daemon,forge): the review-reaction producers
Sequencing steps 6 and 7 of pr-review-remediation.md: the consumer
landed in 052e350b, and these are the two sources that feed it.

Webhook (decision 2, low latency): the GitHub receiver decodes
pull_request_review and pull_request_review_comment events behind the
existing HMAC verification and publishes the same typed reaction the
poller produces, keyed source-independently so PublishUnique collapses
the two sources. Only submitted/created carry a verdict to remediate;
edited and dismissed are acknowledged. Reaction deliveries are
rate-limited per source (decision 6's 'add when the receiver gains a
second event family'), and the reaction path carries no dispatch
predicate -- eligibility is the consumer's owned-PR lookup.

Poll (both forges, the no-webhook backstop): one shared scan over all
pr_open tasks, each with the forge client its own identity owns
(reconcilePRs's shape), listing reviews and comments since per-task
persisted high-water marks and skipping the owning identity's bot user
(decision 5's own-comment exclusion, which the poll is positioned to
make identity-correct).

The cursors are two, not one: review IDs and comment IDs are independent
forge sequences, and a combined high-water mark would silently skip
reviews once a larger comment ID landed. watch_comment_id -- dead since
the comment-watch design it was created for never shipped -- carries the
comment cursor; review_cursor is a new presence-gated migrator column,
and SetReviewCursors is its guarded RPC (pr_open only, so cursors never
move under a run that owns the task). forge.ReviewComment gains ReviewID
so a comment is collectable into its review's unit (decision 5) on both
forges, and forge.Review gains Body so poll-delivered reviews carry
their summary.

Note: the store/proto/facade half of this work landed early in a65eae24
under a release session's message -- a shared-checkout collision, kept
rather than rewritten; that commit carries the review_cursor migration
and the SetReviewCursors contract, this one carries the producers.
2026-09-23 12:41:53 +10:00
sam 59614cc63f style(update): adopt the formatter's alignment in the watchdog test
task check's fmt pass rewrites this literal; the version committed with
the readiness-wait change predated that pass.
2026-09-23 12:30:10 +10:00
sam 40f2e13f0b fix(docs): derive the docsite artifact from the commit, not the working tree
docs:artifact:check regenerated the artifact from a directory walk of
docs/, which also sees an UNTRACKED page. The committed artifact then
looked stale and the gate demanded a regeneration that was already
correct -- one that would have committed a page belonging to no commit.
It cost two sessions in one day: a migration branch, and an unrelated
writer adding a PRD.

Enumerate through `git ls-files --cached` instead, so a page the commit
carries is required in the artifact and a working-tree scratch file is
not. The index counts as well as HEAD, deliberately: a page staged for
this commit is about to be carried by it. Outside a git work tree there
is no commit to disagree with, so the walk is kept and says so on stderr
rather than passing as the stronger guarantee.

Test fails against the walk with the gate's own message ("is stale;
regenerate it by running ...") and passes against the enumeration.
2026-09-23 12:29:29 +10:00
sam a65eae2458 docs(agents): a bead never carries production instance detail
Beads sync to a Dolt remote, so anything written into one is published.
Two beads filed earlier today named an operator host, its internal
address and its filesystem paths -- the tracker was treated as a private
store, which it is not.

The rule is stated where the tracker is described, next to the existing
one about .beads/ never reaching a commit, because it is the same class:
the tracker is not a private store. Host-specific facts belong in the
operator's memos instance, which a bead may point at.
2026-09-23 12:29:29 +10:00
sam 052e350bf1 feat(daemon): wire the review-reaction consumer to remediate runs
The remediate workflow was registered but had no trigger: the reaction
stream was provisioned, the envelope, resolver and owned-PR lookup all
landed, yet nothing consumed the stream (pr-review-remediation.md's
sequencing left the consumer for this step). The daemon now drains the
reaction stream each cycle, before the task drain, so a reaction can be
claimed in the same pass that carried it.

Per decision 3, the store's owned-PR lookup is the authorization
boundary: an unmatched, merged or closed PR drops with a counter, and a
public reaction can never start an agent against a foreign repository.
Per decision 5, a review is the unit of remediation -- its comment
events are appended to the unit while it is queued and dropped once the
run is claimed (the round cap bounds the exchange); a standalone comment
is its own unit of one; approved reviews never remediate; and archie's
own comments, matched on the owning identity's bot user, are excluded so
its replies cannot retrigger it.

The guarded BeginRemediation/UpdateReviewPayload store methods are the
dedup: the pr_open -> queued transition carries the review unit in the
same write, so re-delivered reactions fail the status guard instead of
starting a second round. Both are new StateStoreService RPCs following
the Requeue shape, covered by the local/grpc conformance battery.
2026-09-23 12:08:44 +10:00
sam 2393ec6dae docs(prds): approve the master-detail run page PRD
The maintainer approved task-run-master-detail.md after the
adversarial-review round; its status moves Draft -> Approved while the
work it describes is completed and verified.
2026-09-23 11:36:16 +10:00
sam 00cfd6bda0 fix(webui): reset the stage filter on an attempt switch
A stage filter is a command scoped to the attempt it was made on: the
rail set it against that attempt's stage list. selectAttempt and
performRetry left filters untouched, so a stage selected on attempt 2
carried into attempt 1 -- a same-named stage there rendered as selected
without ever being commanded, or the log stayed narrowed to a stage the
new attempt does not have. The stage filter now resets when the selected
attempt changes; the level filter is attempt-agnostic and survives.

The master-detail PRD absorbs the adversarial review's verified findings:
the reload claim is narrowed to the URL contract (filters are not in the
URL), the unimplemented scroll and pinned claims are dropped, the
unnamed-stage and level-filter contracts are stated, the rail inventory
is corrected, and the acceptance list gains criteria for the
command-not-binding rule, attempt-switch reset, and keyboard selection.
2026-09-23 11:31:58 +10:00
sam 89fc8fc7f1 fix(webui): group live activity by payload, not by event kind
The first cut grouped consecutive same-kind events, but the real noise
shape is an interleave: one background cycle emits curator_run,
session-memory and curator_action events carrying the same payload, and
kind-keyed grouping left them all visible. The grouping key is now the
rendered detail plus the task, so one cycle of noise collapses to one
row regardless of which internal kind emitted each event, while events
carrying different information never merge. Verified against a live
daemon: 50 background events collapse to one expandable row.
2026-09-23 11:20:45 +10:00
sam fd3f661a73 feat(webui): split the task run page into a master-detail pane
The five tabs gave the stage rail less than a third of the screen and
disconnected the log stream from the stage that produced it. The stage
rail is now the page's master pane, always visible; the four context
panels are the inspector and own the tab bar. Selecting a stage commands
the inspector to the log tab with that stage's filter set; clicking the
selected stage clears it. Selection is a command, not a binding -- the
operator can change the filter afterwards.

No endpoint, RPC or contract changed. tab=stages still resolves, to the
log tab; every inspector tab and attempt deep-link survives a reload.
Below the shell's 900px frame breakpoint the rail stacks above the
inspector. Design of record: docs/prds/task-run-master-detail.md (Draft,
per-run panel contracts unchanged from task-run-detail.md).
2026-09-23 11:20:45 +10:00
sam cdedbaa1f5 feat(webui): collapse runs of background telemetry in live activity
The feed's 50 raw events were dominated by consecutive same-shape
background rows (session-memory cycles, runner calls), which buried the
milestones the dashboard exists to surface. Consecutive events sharing
one label and one task now collapse into a group row with an xN badge;
expanding it reveals its events in place. The grouping is consecutive,
not global, so interleaved kinds keep their order and a milestone is
never merged with an event that merely shares its kind.

The projection is a pure view over the store's raw stream (activity-group.ts,
table-tested); the store keeps every event. Group rows keep ActivityRow's
link contract, and the disclosure button is stop-propagated inside the
first cell so it never fights the row-level link.
2026-09-23 11:07:14 +10:00
sam f0c1b34882 docs(skills): add archie-web-ui guidance for dashboard work
Carries the stack facts agents must not fight (token file, ui/dist as a
generated LAW asset, feature layout, UI gates), the operational-tool
design rules, the WCAG AA bar, and the rule that external design
prototypes are specs to translate, never code to port.
2026-09-23 11:05:58 +10:00
sam fde21c43d4 fix(webui): clear WCAG AA on info and subtle text tokens
The info token doubled as badge text on info-soft and as the log-level
label, and failed 4.5:1 there (4.29:1 dark over card, 4.45:1 over glass;
light theme 4.11:1 on canvas, 3.58:1 on its soft). Dark --info moves to
#B08BF8, light --info to #6F47A6, both clearing 4.5:1 on every surface
they land on. Light --fg-subtle moves to #675E6F for the wash-composited
canvas where the old value measured 4.44:1. Measured pairs recorded at
the token definitions.
2026-09-23 11:05:56 +10:00
66 changed files with 4398 additions and 779 deletions

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
---
name: archie-web-ui
description: "Develop, review, or redesign archie-core's dashboard web UI (ui/). Load when adding or changing Vue components, pages, views, styling, theming, layout, or interaction patterns under ui/src; when auditing UI accessibility or contrast; or when porting design prototypes (e.g. React mockups) into the Vue dashboard. Carries stack facts, design-system rules, and the operational-tool tone required here."
---
# Web UI development (ui/)
Archie's dashboard is an **operational supervision tool** for senior developers
watching an autonomous orchestrator: quiet, dense, scannable, work-focused.
Not editorial, not marketing, not playful. Every rule below serves that.
## Stack facts (do not fight these)
- Vue 3 SFCs + TypeScript, Vite, Pinia, vue-router.
- Tailwind CSS v4 via `@tailwindcss/vite`; `@custom-variant dark` keyed on the
`[data-theme]` attribute; shadcn-vue + reka-ui for primitives;
`@lucide/vue` for icons; `@fontsource-variable/geist` is the typeface.
- Features live in `ui/src/<feature>/` with colocated `.js`/`.css`. Extract a
helper to `ui/src/base/` only on the **second distinct consumer**.
- `ui/dist/` is committed and generated — never hand-edit it, never ignore it
(see the header comment in `ui/src/style.css` for why builds are
content-coupled to the bundle).
- Gates: `task ui` (build), `task test:ui` (node --test over DOM-building
primitives in `ui/test/`), `vue-tsc` via `npm run typecheck`. `task check`
includes all of them.
- The dashboard is a LAW asset built from `ui/dist` — a Go-side embed. A UI
change is not done until `task ui` regenerates it and the commit carries it.
## Design-system rules
- **Tokens only.** Semantic CSS variables from `ui/src/style.css`
(`--primary`, `--ok`, `--muted`, ...). Never a raw hex in a component, never
a hue-named token. Dark is default; light defines the same variable set and
is a first-class theme, not an afterthought. Density is a single knob
(`[data-density="compact"]` tightens the spacing scale) — do not add
per-component density conditionals.
- **Icons, not text-as-decoration.** Buttons for clear commands use lucide
icons (icon-only where the symbol is familiar, with a tooltip naming it);
segmented controls for modes, toggles/checkboxes for binary settings,
selects/menus for option sets, tabs for views.
- **Cards 8px radius or less; no cards inside cards;** page sections are
full-width bands or unframed layouts, not floating cards. No gradient orbs,
bokeh blobs, or decorative backgrounds.
- **Stable dimensions.** Tables, tiles, toolbars, sparklines, and icon buttons
get fixed/constrained sizing so dynamic content (long titles, loading
states, big numbers) cannot shift layout. Text never overflows its
container on any viewport; wrap or downsize before it can.
- **No viewport-scaled font sizes, no negative letter-spacing.**
- **No one-note palettes.** If a screen reads as a single hue family
(e.g. all-violet), rebalance with neutrals and status colours rather than
more of the accent.
- **No in-app prose explaining the app** — no help text describing features,
keyboard shortcuts, or how to use a control. If a control needs explaining,
redesign the control.
- **No landing pages.** Every route opens the working experience directly.
## Tone & content
- Match copy to the domain: state names, gate results, timings, token counts —
concrete operational nouns, not conversational flourishes. A header states
system status ("Cluster operational · 4 awaiting intervention"), not a
greeting.
- Every human-actionable state (parked, gate failed, needs review) shows the
reason inline and links to the exact place to act on it (the failing log,
the gate output) — never just a status label.
- High-frequency background telemetry is grouped/summarised in activity feeds
("session-memory · 24 background cycles"), with high-signal events
(stage finished, gate failure, task parked) visually elevated.
## Accessibility bar
- WCAG AA minimum on all text: secondary/metadata labels must clear 4.5:1
against their actual background — audit the token, not the element. If a
muted token fails, fix the token value (one file), not individual spots.
- Log output, hashes, and code are monospace in a strict grid; do not put
rounded pill badges inside raw log lines (breaks monospace alignment).
Truncated stack traces fold into expandable blocks.
- Controls that filter or toggle (log level, wrap, follow, search) live in a
sticky toolbar inside the pane they affect.
## Porting design prototypes
External mockups (Gemini, Figma, React `.tsx` prototypes) are **specs, not
code**. This app is Vue; translate layout, hierarchy, and interaction
decisions into SFCs using shadcn-vue primitives and existing tokens. Mock data
in a prototype proves nothing — verify the pattern against real task/log/diff
shapes before building around it. A prototype proposing new information
architecture (e.g. splitting the task view into a master-detail pane) is an
open design question: it needs a decisive 1-page doc in `docs/prds/` before
structural work lands, per AGENTS.md.
+28 -11
View File
@@ -12,7 +12,7 @@ on:
# preceding fix, say) previously queued a full gate+build for each one,
# several minutes apiece, with no caching -- so a burst of pushes left
# three deploys racing in parallel for the same runner capacity. Only the
# last one's images matter (both jobs push :latest), so cancel a
# last one's images matter (each job pushes its image tags), so cancel a
# superseded run rather than let it fight for resources it can't use.
#
# Keyed on the commit, not github.ref: `git push --follow-tags` pushes
@@ -140,7 +140,7 @@ jobs:
exit 1
fi
if ! git tag --points-at HEAD | grep -qE '^(v[0-9]|archied/v|archie/v)' ; then
echo "::warning ::No release tags at HEAD, so this build publishes :latest for a commit that is not a release. It is stamped dev+<sha> and tagged sha-<sha> so it stays traceable and restorable, but it supersedes the previous release's :latest stamping until the next release is cut."
echo "This commit is not a release, so the images are published as :edge and sha-<sha>; :latest keeps naming the newest release."
fi
build-and-push:
@@ -184,12 +184,13 @@ jobs:
RUNTIME_VERSION="${RUNTIME_TAG#archie/}"
[ -n "$GATEWAY_VERSION" ] || GATEWAY_VERSION="${RELEASE_TAG#v}"
[ -n "$RUNTIME_VERSION" ] || RUNTIME_VERSION="${RELEASE_TAG#v}"
# Not a bare `dev`. A literal dev tells an operator nothing about which
# build they are running, and it is what made a release's stamping look
# transient: the next commit to main republished :latest as `dev`. The
# commit is appended so a main build is identifiable and is visibly not
# a release. (On an untagged push GITHUB_SHA IS the commit — the tag
# case is handled by the dereference above.)
# `dev+<sha>` is what a build that is NOT a release reports, and it is
# honest now that such a build no longer publishes :latest: the version
# names the commit it came from, and the sha-<sha> tag makes it
# restorable. Before, this same string reached :latest minutes after a
# release and made the release's own stamping read as dev
# (archie-core-i5nb). (On an untagged push GITHUB_SHA IS the commit —
# the tag case is handled by the dereference above.)
[ -n "$GATEWAY_VERSION" ] || GATEWAY_VERSION="dev+${GITHUB_SHA:0:12}"
[ -n "$RUNTIME_VERSION" ] || RUNTIME_VERSION="dev+${GITHUB_SHA:0:12}"
# Keep the raw tag presence separate from the version fallback: a
@@ -202,6 +203,24 @@ jobs:
echo "release_tag=$RELEASE_TAG" >> "$GITHUB_OUTPUT"
echo "gateway=$GATEWAY_VERSION" >> "$GITHUB_OUTPUT"
echo "runtime=$RUNTIME_VERSION" >> "$GITHUB_OUTPUT"
# :latest names the newest RELEASE, so only a commit that IS one
# publishes it. A push to main publishes :edge (mutable, newest main)
# and sha-<sha> (immutable) instead. That is what stops a release's
# :latest stamping from being overwritten minutes later by the next
# ordinary commit, which left a host reporting dev and made the update
# path unable to tell current from stale (archie-core-i5nb).
#
# `if` blocks rather than `[ -n "$X" ] && echo`: the latter returns
# non-zero when the test fails, and these steps run under `set -e`.
{
echo "archied_tags<<EOF"
if [ -n "$RELEASE_TAG" ]; then
echo "ghcr.io/samcharles93/archied:latest"
fi
echo "ghcr.io/samcharles93/archied:edge"
echo "ghcr.io/samcharles93/archied:sha-${{ steps.commit.outputs.sha }}"
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Build and push archied
uses: docker/build-push-action@v6
@@ -209,9 +228,7 @@ jobs:
context: .
file: Dockerfile.archied
push: true
tags: |
ghcr.io/samcharles93/archied:latest
ghcr.io/samcharles93/archied:sha-${{ steps.commit.outputs.sha }}
tags: ${{ steps.versions.outputs.archied_tags }}
build-args: |
GATEWAY_VERSION=${{ steps.versions.outputs.gateway }}
RUNTIME_VERSION=${{ steps.versions.outputs.runtime }}
+50
View File
@@ -5,6 +5,56 @@ release's per-component sections are labelled beneath its heading.
## [Unreleased]
## [1.40.0] - 2026-09-23
### archied
- **Every park now says what kind of intervention it needs.** A parked task
is classified as `needs you` (a decision or fix only an operator can
supply), `transient` (an environment problem -- container pool, storage,
transport -- retry once it is fixed), or `terminal` (the repository or
identity cannot act; retrying cannot succeed). The class shows beside the
Parked badge on the dashboard, so "needs you" reads as a request rather
than a failure.
- **Operator retries and review-remediation rounds now have separate
budgets.** An operator's manual retries no longer draw down the rounds
Archie may spend addressing review feedback on its pull requests, and a
round-cap park no longer makes a later retry re-park immediately.
- **`latest` now names the newest release. A push to `main` that is not a
release publishes `edge` and `sha-<commit>` instead. A host that was
following `main` by pulling `latest` stops advancing at this release --
switch it to `edge` to keep tracking `main`, or leave it on `latest` to
follow releases.**
### archie-agent
- The park-classification wire format is part of this image; a host that
runs the agent should `docker compose pull agent` to pick it up.
## [1.39.0] - 2026-09-23
### archied
- **Archie now acts on review comments left on its own pull requests.** A
requested-changes review (or a standalone comment) on a PR Archie opened
dispatches a remediation run: the smallest change that satisfies the
feedback, committed to the same PR branch and answered in the review
thread. Approved reviews never remediate, each reaction is its own round,
and the exchange is bounded by the repo's `max_retries` before Archie stops
and says so on the PR.
- **The task run page is a master-detail view.** The run's stage rail and
detail panels sit beside the run list, so one run's timeline is visible
without leaving the page.
- **Live activity groups related updates instead of stacking them by event
kind**, so a burst of progress on one task reads as one story, and the
stage filter resets when you switch attempts.
- Contrast fixes on the info and subtle text tokens clear WCAG AA.
### archie-agent
- The review-reaction remediation path is part of this image; a host that
runs the agent should `docker compose pull agent` to pick it up.
## [1.38.0] - 2026-09-23
### archied — Event capture, mappings and bindings are PocketBase records
+8
View File
@@ -336,6 +336,14 @@ bd remember # Persist cross-session architectural facts
(`.gitignore`d, `export.auto: false`) -- never `git add` them and never
create a commit whose only content is beads bookkeeping. Bead state moves
through Dolt, not through git commits on this repo.
- **A bead never carries production instance detail.** No operator host name,
hostname, IP or port, filesystem path, PID, or credential -- in the body
*or* the title, since both sync to the Dolt remote and are therefore
published. Write the mechanism and the evidence shape instead ("a production
host", "the State Store target", "the host's `config.toml`"), and put the
host-specific facts in the operator's memos instance, which the bead may
point at. This is the same class of rule as never committing a credential:
the tracker is not a private store.
## Session Completion Protocol
+5
View File
@@ -76,6 +76,11 @@ Tagging one version produces, from a single `deploy` run:
`ghcr.io/samcharles93/archie-agent:latest`. The runtime image is rebuilt by the
release, so runtime commits merged to `main` do not reach a running sandbox until the
host pulls the new image.
- **`:latest` names the newest release, not the newest commit.** A push to `main`
that is not a release publishes `archied:edge` (mutable, tracking `main`) and
`archied:sha-<commit>` (immutable) instead, so a release's `:latest` stamping is
not overwritten minutes later by the next ordinary commit. A host that runs
releases follows `:latest`; a host that tracks `main` follows `:edge`.
- **A GitHub Release with a distribution zip** — `dist-zip` builds every process the
reference deployment runs (`archied`, `archie-gateway`, `archie-state-store`,
`archie-ui`, `archie-messaging`, `archie-playbooks`) for linux/amd64, packs them with
+13 -10
View File
@@ -439,17 +439,20 @@ tasks:
build:
desc: Build archie services and agent binaries
# Version stamping used to live only in Dockerfile.archied, so any build
# from source -- including a host deployment -- reported "dev" for
# both components and /version was useless there. Derive the same
# -X values from the release tags so a source build is stamped too.
# git describe (without --abbrev=0) yields 1.7.0-2-gbb54786 when HEAD is
# past the tag, which is the honest answer for a mid-cycle build.
# A from-source build is not a release, and CI is the only thing that stamps
# one: the version a release carries is written into the artifact CI
# publishes, the zip's binaries and the container image, and is never
# derived from whatever tags a local checkout happens to have.
#
# Deriving it here also made the stamp a function of the commit graph, which
# is the one input a content-checksum build cache cannot see: an empty
# commit moved `git describe` while `task build` still reported "up to date"
# and shipped the previous stamp (archie-core-pdq2). Stamping `dev` removes
# the non-file input rather than caching it, and a local build's
# traceability is the checkout it came from.
vars:
GATEWAY_VERSION:
sh: git describe --tags --match 'archied/v*' 2>/dev/null | sed 's|^archied/v||' || echo dev
RUNTIME_VERSION:
sh: git describe --tags --match 'archie/v*' 2>/dev/null | sed 's|^archie/v||' || echo dev
GATEWAY_VERSION: dev
RUNTIME_VERSION: dev
sources:
- "**/*.go"
- go.mod
+31
View File
@@ -50,6 +50,37 @@ func TestDeployWorkflowOnlyPublishesRuntimeImageForTaggedRelease(t *testing.T) {
}
}
// TestDeployWorkflowPublishesLatestOnlyFromARelease pins the rule that keeps a
// release's :latest stamping from being overwritten by the next ordinary commit.
//
// build-and-push runs on any push to main and used to always push :latest, so a
// release's own stamping survived only until the next commit — minutes, in an
// active repo — and a host deploying :latest reported dev, leaving the update
// path unable to tell current from stale (archie-core-i5nb). :latest now moves
// only from a commit that IS a release; everything else publishes :edge and an
// immutable sha-<commit>.
func TestDeployWorkflowPublishesLatestOnlyFromARelease(t *testing.T) {
source := readDeploymentFile(t, ".github/workflows/deploy.yml")
for _, required := range []string{
`if [ -n "$RELEASE_TAG" ]; then`,
`echo "ghcr.io/samcharles93/archied:latest"`,
`echo "ghcr.io/samcharles93/archied:edge"`,
`archied_tags<<EOF`,
`tags: ${{ steps.versions.outputs.archied_tags }}`,
} {
if !strings.Contains(source, required) {
t.Errorf("deploy workflow is missing the release-only :latest guard %q", required)
}
}
// One occurrence: the guard above, not a second unconditional copy that would
// undo it.
if got := strings.Count(source, "ghcr.io/samcharles93/archied:latest"); got != 1 {
t.Errorf("archied :latest appears %d times, want exactly 1 inside the release-tag guard", got)
}
}
func TestDeployWorkflowUsesConfiguredFormatters(t *testing.T) {
source := readDeploymentFile(t, ".github/workflows/deploy.yml")
for _, required := range []string{
+11 -1
View File
@@ -304,7 +304,7 @@
"url": "/dev/prds/news-and-releases/",
"title": "Public news and per-version release notes -- decision",
"section": "PRDs",
"body": "# Public news and per-version release notes -- decision\n\n**Status:** Approved\n**Date:** 2026-09-21\n**Beads issue:** `archie-core-2ncm.2`\n\nA public news page and a release-notes page for every version. Both are derived\nfrom the changelogs the release process already produces, so publishing a\nrelease adds no writing. Part A is the derivation and the artifact any renderer\nconsumes; it is not tied to MkDocs. Part B is the MkDocs rendering that\npublishes them at `offloaded.dev/news/`.\n\n## Part A -- release facts and their derivation\n\n### Source of truth\n\nRelease notes come from `CHANGELOG.archied.md` and `CHANGELOG.archie.md`. Those\nare the release process's frozen notes: `tools/release.sh --prepare` writes a\nsection, the maintainer edits it, and `--tag` refuses to tag a version without\nits section. A page exists exactly for a release the process cut, and no second\ncopy of release prose can drift from the changelog.\n\nTags are not the source. CI and deployment check out shallow, so tags are absent\nfrom a site build; the changelogs are always present and their\n`## [\u003cversion\u003e] - \u003cdate\u003e` headings carry the same version and date the tags\ncarry. Raw commits are not the source either: the changelog is the edited text,\nnot the commit list.\n\n### What a version's notes contain\n\nThe version and date parsed from the section heading, and the section body\nunchanged. The body keeps the maintainer's headings and bullets; the generator\ndoes not regroup them into feature and fix categories, because those categories\nexist only on commits the edited changelog does not preserve.\n\n`## [Unreleased]` is skipped. Any other `## [` heading that is not\n`[version] - date` stops generation, so a malformed heading cannot silently drop\na release. A relative Markdown link in a body stops generation too: a rendered\npage sits at a different depth from the changelog, and a host's link checking\nwould fail on the dead link. Absolute links pass through.\n\n### Two components\n\n`archied` and `archie-agent` version independently and either can be held back,\nso the data carries the tag prefix (`archied`, `archie`), the product name\n(`archied`, `archie-agent`), and the version as separate fields. A release that\nmoved one component is one entry. The generator never pairs two component\nversions or invents a combined product version.\n\n### The canonical artifact\n\n`docs/news/releases.json` is the host hand-off: a committed, generated,\nnewest-first array of `{component, name, version, date, body}`. Every adapter\nrenders from this file rather than re-parsing a changelog. The JSON is the\ncontract; a host adapter may add markup, but not facts.\n\n### Zero per-release maintenance\n\n`task news` regenerates the JSON and the MkDocs pages from the changelogs.\n`task news:check` regenerates them in a temporary directory and fails when the\ncommitted files differ; it runs in `task check`, so a changelog edit cannot land\nwithout its regeneration. `tools/release.sh --tag` regenerates and stages them\nin the release commit, so a tag's tree carries its own facts.\n\nThe generator owns `docs/news/releases.json`, `docs/news/index.md` and the two\ncomponent directories end-to-end: it rewrites expected files and reports an\nunexpected file in a component directory as drift. It leaves every other file\nunder `docs/news/` alone, so a future hand-written announcement is not its\nbusiness.\n\n## Part B -- publishing\n\nMkDocs is the host. `docs/news/index.md` is the news page: date-grouped, newest\nfirst, one entry per release carrying the component, the version, and a link to\nits notes. `docs/news/archied/\u003cversion\u003e.md` and `docs/news/archie/\u003cversion\u003e.md`\nhold the notes. `site_url` is `https://offloaded.dev/`, so the pages are served\nat `offloaded.dev/news/`.\n\nThe version pages stay out of the derived navigation (`not_in_nav` in\n`mkdocs.yml`) while remaining published; the news page is their entry point, so\na version list that grows with every release cannot push the architecture tree\noff the screen.\n\nA different renderer would read `docs/news/releases.json` instead of these\nMarkdown files. That is a separate change in that renderer's repository and\ndoes not alter Part A; the JSON, not the Markdown, is the reusable half.\n\n## Not in scope\n\n- Generated summaries, categories, or section headings; the changelog has no\n structured summary field to derive one from.\n- Per-release download or install links; where to get the artifacts is\n documented once, not restated for every version.\n- Hand-written news items. The generated page lists releases.\n- Changes to `infra/ansible`. Serving the site at a hostname other than\n `offloaded.dev` is an infrastructure decision.\n\n## Verification\n\n- `go test ./tools/newsgen/...` covers parsing, ordering, rendering, the link\n and heading refusals, and check-mode drift.\n- `task news:check` passes inside `task check`.\nLine truncated
"body": "# Public news and per-version release notes -- decision\n\n**Status:** Approved\n**Date:** 2026-09-21\n**Beads issue:** `archie-core-2ncm.2`\n**Superseded in part:** `docs/prds/release-stream-and-commit-rules.md` supersedes the\nsections \"Source of truth\" and \"Two components\" below. There is now one release\nstream: a single `CHANGELOG.md` carries every release section, the per-component\n`CHANGELOG.archied.md` and `CHANGELOG.archie.md` are deleted, and one `vX.Y.Z` tag\nnames a release. The rest of this document still holds.\n\nA public news page and a release-notes page for every version. Both are derived\nfrom the changelogs the release process already produces, so publishing a\nrelease adds no writing. Part A is the derivation and the artifact any renderer\nconsumes; it is not tied to MkDocs. Part B is the MkDocs rendering that\npublishes them at `offloaded.dev/news/`.\n\n## Part A -- release facts and their derivation\n\n### Source of truth\n\nRelease notes come from `CHANGELOG.archied.md` and `CHANGELOG.archie.md`. Those\nare the release process's frozen notes: `tools/release.sh --prepare` writes a\nsection, the maintainer edits it, and `--tag` refuses to tag a version without\nits section. A page exists exactly for a release the process cut, and no second\ncopy of release prose can drift from the changelog.\n\nTags are not the source. CI and deployment check out shallow, so tags are absent\nfrom a site build; the changelogs are always present and their\n`## [\u003cversion\u003e] - \u003cdate\u003e` headings carry the same version and date the tags\ncarry. Raw commits are not the source either: the changelog is the edited text,\nnot the commit list.\n\n### What a version's notes contain\n\nThe version and date parsed from the section heading, and the section body\nunchanged. The body keeps the maintainer's headings and bullets; the generator\ndoes not regroup them into feature and fix categories, because those categories\nexist only on commits the edited changelog does not preserve.\n\n`## [Unreleased]` is skipped. Any other `## [` heading that is not\n`[version] - date` stops generation, so a malformed heading cannot silently drop\na release. A relative Markdown link in a body stops generation too: a rendered\npage sits at a different depth from the changelog, and a host's link checking\nwould fail on the dead link. Absolute links pass through.\n\n### Two components\n\n`archied` and `archie-agent` version independently and either can be held back,\nso the data carries the tag prefix (`archied`, `archie`), the product name\n(`archied`, `archie-agent`), and the version as separate fields. A release that\nmoved one component is one entry. The generator never pairs two component\nversions or invents a combined product version.\n\n### The canonical artifact\n\n`docs/news/releases.json` is the host hand-off: a committed, generated,\nnewest-first array of `{component, name, version, date, body}`. Every adapter\nrenders from this file rather than re-parsing a changelog. The JSON is the\ncontract; a host adapter may add markup, but not facts.\n\n### Zero per-release maintenance\n\n`task news` regenerates the JSON and the MkDocs pages from the changelogs.\n`task news:check` regenerates them in a temporary directory and fails when the\ncommitted files differ; it runs in `task check`, so a changelog edit cannot land\nwithout its regeneration. `tools/release.sh --tag` regenerates and stages them\nin the release commit, so a tag's tree carries its own facts.\n\nThe generator owns `docs/news/releases.json`, `docs/news/index.md` and the two\ncomponent directories end-to-end: it rewrites expected files and reports an\nunexpected file in a component directory as drift. It leaves every other file\nunder `docs/news/` alone, so a future hand-written announcement is not its\nbusiness.\n\n## Part B -- publishing\n\nMkDocs is the host. `docs/news/index.md` is the news page: date-grouped, newest\nfirst, one entry per release carrying the component, the version, and a link to\nits notes. `docs/news/archied/\u003cversion\u003e.md` and `docs/news/archie/\u003cversion\u003e.md`\nhold the notes. `site_url` is `https://offloaded.dev/`, so the pages are served\nat `offloaded.dev/news/`.\n\nThe version pages stay out of the derived navigation (`not_in_nav` in\n`mkdocs.yml`) while remaining published; the news page is their entry point, so\na version list that grows with every release cannot push the architecture tree\noff the screen.\n\nA different renderer would read `docs/news/releases.json` instead of these\nMarkdown files. That is a separate change in that renderer's repository and\ndoes not alter Part A; the JSON, not the Markdown, is the reusable half.\n\n## Not in scope\n\n- Generated summaries, categories, or section headings; the changelog has no\n structured summary field to derive one from.\n- Per-release download or install links; where to get the artifacts is\n documented once, not restated for eveLine truncated
},
{
"url": "/dev/prds/operator-pr-review/",
@@ -414,6 +414,12 @@
"section": "PRDs",
"body": "# Per-run task detail: attempts, stages, changes, config, debug\n\n**Status:** Approved\n**Authority:** the surface contract itself is\n`docs/architecture/observability.md`.\n**Date:** 2026-09-18\n**Compounds with:** `docs/prds/task-logs-pagination.md` (a bounded read says\nwhat it does not show), `docs/prds/status-health-surface.md` (no surface that\nanswers something already answered elsewhere).\n\n## Decision\n\nA task gets one detail page that answers \"what did this run actually do?\" per\n**attempt**: an ordered stage rail, the change each commit/push produced, the\neffective configuration the attempt ran under, the attempt's log, and the raw\nrecord behind all of it.\n\nThe single organising idea is **attempt attribution**. The dashboard\nrenders a task's whole event stream as one flat timeline, so a retried task\nreads as one long run with two of everything. Every new panel is scoped to one\nattempt and says which one.\n\nThe second organising idea is **provenance, not re-derivation**. What a run\nproduced is captured at the producer, while the evidence exists, and persisted\ndurably. Nothing in this surface tries to reconstruct a past run from state\nthat has since moved on.\n\n## The requirement set\n\n| # | Requirement | Mechanism |\n| --- | --- | --- |\n| R1 | Per-attempt stage rail: stages with name, start, duration, terminal status and error, ordered within one attempt | `GET /api/tasks/{id}/attempts` reads the task's events and groups them by `attempt` |\n| R2 | Events carry an attempt, migrated safely and carried on the wire | `events.attempt` column + presence-gated migrator arm; `Event.attempt = 11` |\n| R3 | Changed files captured at commit/push, persisted per task, exposed, shown with repo/PR links | `changes_captured` durable event written by the commit/push steps; `GET /api/tasks/{id}/changes` |\n| R4 | The effective configuration an attempt ran under, secrets redacted, shown | `config_captured` durable event written once per attempt; read from the events response the page already holds |\n| R5 | Log pane filters by attempt, stage and level; absence stays distinct from an unreadable deployment | `logging.Query.Stage` + `ReadTaskLogRequest.stage = 9`; the pane keeps `disabled` and `found=false` apart |\n| R6 | Retry is reachable from the run view and produces a new attempt shown as a new run | Existing retry action, labelled as a NEW run whose confirm states the previous attempt's commits are discarded |\n| R7 | Raw JSON of the task record and its events for the selected attempt | `GET /api/tasks/{id}/debug` |\n| R8 | Deep-linkable, reload-safe per-task detail page that keeps existing URLs working | `/tasks/{id}` route beside the existing `/tasks?task=N` and `/tasks?status=...` |\n| R9 | Design polish: hierarchy, tokens, both themes, responsive rail, a11y, loading/empty/error states | UI lane; measured at 480px and 700px in both themes |\n| R10 | Documentation of record | This document plus `docs/architecture/observability.md` |\n| R11 | Red-first tests for every new behaviour, full gate, `task ui`, forced `go build ./...`, `go test -race` on touched packages | Per lane; the anti-cost-cutting requirement lives here |\n\n## Attempt attribution: a column, not a guess\n\n`events.Event.Attempt`, persisted by `internal/store` as the `events.attempt`\ncolumn (`internal/store/events.go`, `eventsSchema`), is a real column,\n`NOT NULL DEFAULT 0`. It was chosen over segmenting the stream on `task_queued` /\n`task_retried` because a fold would have to guess which side of a boundary an\nevent belongs to when the daemon restarts mid-attempt, when `RecoverStale`\nrequeues, or when two attempts interleave across a crash. A guess rendered as\nstructure is exactly the false fidelity this surface exists to avoid; a column\nis durable, queryable and ordered by construction.\n\n**`0` means \"not attributable\".** It is every row written before this change\nplus the deliberately task-agnostic producers. It is not an attempt number and\nis never rendered as one. The attempts endpoint reports the count of\nunattributed events so the page can say so instead of presenting old history as\nattempt 1.\n\n## Migration against an existing `archie.db`\n\nThe store's migrator (`migrateTasks` in `internal/store/store.go`) already reads\n`PRAGMA table_info` through `tableColumns` and applies a presence-gated\n`ALTER TABLE ... ADD COLUMN` list. This change adds an `events` arm: a\n`tableColumns(ctx, tx, \"events\")` read beside the other two, and the entry\n`ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`.\n\nThree consequences a future maintainer must not get wrong:\n\n- `eventsSchema` is `CREATE TABLE IF NOT EXISTS` (`internal/store/events.go`),\n so on an existing database it is a **no-op**. The migrator arm is the only\n thing that adds the column there. This is why the red test builds a raw\n SQLite file with the pre-change `events` DDL and must fail before the arm\n exists: eveLine truncated
},
{
"url": "/dev/prds/task-run-master-detail/",
"title": "Task run detail as a master-detail split pane",
"section": "PRDs",
"body": "# Task run detail as a master-detail split pane\n\n**Status:** Approved\n**Authority:** the panel contracts stay as ratified in\n`docs/prds/task-run-detail.md`; this document changes only the run page's\narrangement of them.\n**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution, the\nlog stage filter, the per-panel honesty rules).\n\n## Decision\n\nThe run page's five tabs become two panes. The stage rail is the **master**,\nalways visible on the left. The four context panels — log, changed files,\nconfiguration, debug — are the **inspector** on the right, and their tab bar\nmoves into the inspector. The \"Stages\" tab stops existing.\n\nSelecting a stage switches the inspector to the log tab and sets the log\npane's stage filter to that stage. Changing the filter afterwards is the\noperator's choice and is not overridden; rail selection never touches the\nlevel filter. Clicking the selected stage again returns the filter to all\nstages. A stage with no name is rendered but not selectable.\n\nSwitching attempts resets the stage filter to all stages: a selection was\ncommanded on the attempt it was made on, and a different attempt presents a\ndifferent stage list. Changed files, configuration and debug stay\nattempt-scoped; a stage selection never scopes them.\n\n## What does not change\n\n- No new endpoint, RPC, table or configuration field. Every read is one the\n page already makes.\n- The URL contract: `tab` and `attempt` ride in the query string and survive\n a reload. Log filters are not part of the URL; a reload returns the log to\n all stages. `tab=stages` stays a valid URL and renders the log tab; the\n page never generates it again.\n- Attempt attribution, the log stage filter's coverage limit and every\n honesty rule in `task-run-detail.md` still apply: each pane states what it\n cannot show under that document's rendering rules.\n- The task header and the attempt selector sit above both panes.\n\n## Arrangement\n\n- Left pane: fixed-width rail (20rem) with the attempt's stage rows. Status,\n duration, error, the stage's agent report, the attempt's status badge and\n start time, and the attempt-attribution footnotes render in the rail.\n- Right pane: the inspector's tab bar plus the selected panel, filling the\n remaining width.\n- Below the shell's 900px frame breakpoint the rail stacks above the\n inspector; neither pane is hidden.\n- Keyboard: the rail keeps its list semantics and each stage row is a real\n button, so selection and deselection work without a pointer; the inspector\n keeps the WAI-ARIA tabs pattern the tab bar already provides.\n\n## Acceptance\n\n1. The rail is visible without opening any tab, and no \"Stages\" trigger exists.\n2. Clicking a stage opens the log filtered to that stage; clicking it again\n shows all stages.\n3. After a stage selection, a filter change made by the operator is kept, and\n the level filter survives the selection.\n4. Switching attempts resets the stage filter to all stages, and no rail row\n on the new attempt renders as selected unless the operator selected it\n there.\n5. `tab=stages` loads and renders the log tab.\n6. Every inspector tab and attempt deep-link survives a reload.\n7. A stage is selectable and deselectable by keyboard, and the selection\n mirrors the log pane's stage filter.\n8. Below 900px the rail stacks above the inspector.\n9. `task check` passes clean and `ui/dist` matches the sources."
},
{
"url": "/dev/prds/ui-service-boundary/",
"title": "UI Service boundary and configuration ownership",
@@ -715,6 +721,10 @@
"title": "Per-run task detail: attempts, stages, changes, config, debug",
"url": "/dev/prds/task-run-detail/"
},
{
"title": "Task run detail as a master-detail split pane",
"url": "/dev/prds/task-run-master-detail/"
},
{
"title": "UI Service boundary and configuration ownership",
"url": "/dev/prds/ui-service-boundary/"
+25
View File
@@ -0,0 +1,25 @@
# 1.39.0
Released 2026-09-23. [All news](index.md)
### archied
- **Archie now acts on review comments left on its own pull requests.** A
requested-changes review (or a standalone comment) on a PR Archie opened
dispatches a remediation run: the smallest change that satisfies the
feedback, committed to the same PR branch and answered in the review
thread. Approved reviews never remediate, each reaction is its own round,
and the exchange is bounded by the repo's `max_retries` before Archie stops
and says so on the PR.
- **The task run page is a master-detail view.** The run's stage rail and
detail panels sit beside the run list, so one run's timeline is visible
without leaving the page.
- **Live activity groups related updates instead of stacking them by event
kind**, so a burst of progress on one task reads as one story, and the
stage filter resets when you switch attempts.
- Contrast fixes on the info and subtle text tokens clear WCAG AA.
### archie-agent
- The review-reaction remediation path is part of this image; a host that
runs the agent should `docker compose pull agent` to pick it up.
+27
View File
@@ -0,0 +1,27 @@
# 1.40.0
Released 2026-09-23. [All news](index.md)
### archied
- **Every park now says what kind of intervention it needs.** A parked task
is classified as `needs you` (a decision or fix only an operator can
supply), `transient` (an environment problem -- container pool, storage,
transport -- retry once it is fixed), or `terminal` (the repository or
identity cannot act; retrying cannot succeed). The class shows beside the
Parked badge on the dashboard, so "needs you" reads as a request rather
than a failure.
- **Operator retries and review-remediation rounds now have separate
budgets.** An operator's manual retries no longer draw down the rounds
Archie may spend addressing review feedback on its pull requests, and a
round-cap park no longer makes a later retry re-park immediately.
- **`latest` now names the newest release. A push to `main` that is not a
release publishes `edge` and `sha-<commit>` instead. A host that was
following `main` by pulling `latest` stops advancing at this release --
switch it to `edge` to keep tracking `main`, or leave it on `latest` to
follow releases.**
### archie-agent
- The park-classification wire format is part of this image; a host that
runs the agent should `docker compose pull agent` to pick it up.
+2
View File
@@ -4,6 +4,8 @@ Release notes, newest first.
## 2026-09-23
- [1.40.0](1.40.0.md)
- [1.39.0](1.39.0.md)
- [1.38.0](1.38.0.md)
## 2026-09-22
+4
View File
@@ -48,8 +48,10 @@
"/news/archie/1.37.0/": "/news/1.37.0/",
"/news/archie/1.37.1/": "/news/1.37.1/",
"/news/archie/1.38.0/": "/news/1.38.0/",
"/news/archie/1.39.0/": "/news/1.39.0/",
"/news/archie/1.4.0/": "/news/1.4.0/",
"/news/archie/1.4.1/": "/news/1.4.1/",
"/news/archie/1.40.0/": "/news/1.40.0/",
"/news/archie/1.5.0/": "/news/1.5.0/",
"/news/archie/1.6.0/": "/news/1.6.0/",
"/news/archie/1.7.0/": "/news/1.7.0/",
@@ -115,8 +117,10 @@
"/news/archied/1.37.0/": "/news/1.37.0/",
"/news/archied/1.37.1/": "/news/1.37.1/",
"/news/archied/1.38.0/": "/news/1.38.0/",
"/news/archied/1.39.0/": "/news/1.39.0/",
"/news/archied/1.4.0/": "/news/1.4.0/",
"/news/archied/1.4.1/": "/news/1.4.1/",
"/news/archied/1.40.0/": "/news/1.40.0/",
"/news/archied/1.5.0/": "/news/1.5.0/",
"/news/archied/1.6.0/": "/news/1.6.0/",
"/news/archied/1.7.0/": "/news/1.7.0/",
+10
View File
@@ -1,4 +1,14 @@
[
{
"version": "1.40.0",
"date": "2026-09-23",
"body": "### archied\n\n- **Every park now says what kind of intervention it needs.** A parked task\n is classified as `needs you` (a decision or fix only an operator can\n supply), `transient` (an environment problem -- container pool, storage,\n transport -- retry once it is fixed), or `terminal` (the repository or\n identity cannot act; retrying cannot succeed). The class shows beside the\n Parked badge on the dashboard, so \"needs you\" reads as a request rather\n than a failure.\n- **Operator retries and review-remediation rounds now have separate\n budgets.** An operator's manual retries no longer draw down the rounds\n Archie may spend addressing review feedback on its pull requests, and a\n round-cap park no longer makes a later retry re-park immediately.\n- **`latest` now names the newest release. A push to `main` that is not a\n release publishes `edge` and `sha-<commit>` instead. A host that was\n following `main` by pulling `latest` stops advancing at this release --\n switch it to `edge` to keep tracking `main`, or leave it on `latest` to\n follow releases.**\n\n### archie-agent\n\n- The park-classification wire format is part of this image; a host that\n runs the agent should `docker compose pull agent` to pick it up."
},
{
"version": "1.39.0",
"date": "2026-09-23",
"body": "### archied\n\n- **Archie now acts on review comments left on its own pull requests.** A\n requested-changes review (or a standalone comment) on a PR Archie opened\n dispatches a remediation run: the smallest change that satisfies the\n feedback, committed to the same PR branch and answered in the review\n thread. Approved reviews never remediate, each reaction is its own round,\n and the exchange is bounded by the repo's `max_retries` before Archie stops\n and says so on the PR.\n- **The task run page is a master-detail view.** The run's stage rail and\n detail panels sit beside the run list, so one run's timeline is visible\n without leaving the page.\n- **Live activity groups related updates instead of stacking them by event\n kind**, so a burst of progress on one task reads as one story, and the\n stage filter resets when you switch attempts.\n- Contrast fixes on the info and subtle text tokens clear WCAG AA.\n\n### archie-agent\n\n- The review-reaction remediation path is part of this image; a host that\n runs the agent should `docker compose pull agent` to pick it up."
},
{
"version": "1.38.0",
"date": "2026-09-23",
+5
View File
@@ -3,6 +3,11 @@
**Status:** Approved
**Date:** 2026-09-21
**Beads issue:** `archie-core-2ncm.2`
**Superseded in part:** `docs/prds/release-stream-and-commit-rules.md` supersedes the
sections "Source of truth" and "Two components" below. There is now one release
stream: a single `CHANGELOG.md` carries every release section, the per-component
`CHANGELOG.archied.md` and `CHANGELOG.archie.md` are deleted, and one `vX.Y.Z` tag
names a release. The rest of this document still holds.
A public news page and a release-notes page for every version. Both are derived
from the changelogs the release process already produces, so publishing a
+69
View File
@@ -0,0 +1,69 @@
# Task run detail as a master-detail split pane
**Status:** Approved
**Authority:** the panel contracts stay as ratified in
`docs/prds/task-run-detail.md`; this document changes only the run page's
arrangement of them.
**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution, the
log stage filter, the per-panel honesty rules).
## Decision
The run page's five tabs become two panes. The stage rail is the **master**,
always visible on the left. The four context panels — log, changed files,
configuration, debug — are the **inspector** on the right, and their tab bar
moves into the inspector. The "Stages" tab stops existing.
Selecting a stage switches the inspector to the log tab and sets the log
pane's stage filter to that stage. Changing the filter afterwards is the
operator's choice and is not overridden; rail selection never touches the
level filter. Clicking the selected stage again returns the filter to all
stages. A stage with no name is rendered but not selectable.
Switching attempts resets the stage filter to all stages: a selection was
commanded on the attempt it was made on, and a different attempt presents a
different stage list. Changed files, configuration and debug stay
attempt-scoped; a stage selection never scopes them.
## What does not change
- No new endpoint, RPC, table or configuration field. Every read is one the
page already makes.
- The URL contract: `tab` and `attempt` ride in the query string and survive
a reload. Log filters are not part of the URL; a reload returns the log to
all stages. `tab=stages` stays a valid URL and renders the log tab; the
page never generates it again.
- Attempt attribution, the log stage filter's coverage limit and every
honesty rule in `task-run-detail.md` still apply: each pane states what it
cannot show under that document's rendering rules.
- The task header and the attempt selector sit above both panes.
## Arrangement
- Left pane: fixed-width rail (20rem) with the attempt's stage rows. Status,
duration, error, the stage's agent report, the attempt's status badge and
start time, and the attempt-attribution footnotes render in the rail.
- Right pane: the inspector's tab bar plus the selected panel, filling the
remaining width.
- Below the shell's 900px frame breakpoint the rail stacks above the
inspector; neither pane is hidden.
- Keyboard: the rail keeps its list semantics and each stage row is a real
button, so selection and deselection work without a pointer; the inspector
keeps the WAI-ARIA tabs pattern the tab bar already provides.
## Acceptance
1. The rail is visible without opening any tab, and no "Stages" trigger exists.
2. Clicking a stage opens the log filtered to that stage; clicking it again
shows all stages.
3. After a stage selection, a filter change made by the operator is kept, and
the level filter survives the selection.
4. Switching attempts resets the stage filter to all stages, and no rail row
on the new attempt renders as selected unless the operator selected it
there.
5. `tab=stages` loads and renders the log tab.
6. Every inspector tab and attempt deep-link survives a reload.
7. A stage is selectable and deselectable by keyboard, and the selection
mirrors the log pane's stage filter.
8. Below 900px the rail stacks above the inspector.
9. `task check` passes clean and `ui/dist` matches the sources.
+10 -2
View File
@@ -169,8 +169,16 @@ echo "==> Building native archie binaries..."
# refuses to self-update (internal/releaseupdate.ErrUnknownInstallType)
# rather than guess whether /update's configured install command is
# even the right kind of update for a script-built native binary.
GATEWAY_VERSION="$(git describe --tags --match 'archied/v*' 2>/dev/null | sed 's|^archied/v||' || echo dev)"
RUNTIME_VERSION="$(git describe --tags --match 'archie/v*' 2>/dev/null | sed 's|^archie/v||' || echo dev)"
# A from-source build is not a release, and CI is the only thing that stamps
# one: the version a release carries is written into the artifact CI
# publishes -- the zip's binaries and the container image -- and is never
# derived from whatever tags a local checkout happens to have. Deriving it
# here made a source-built host claim a release it was not running, and made
# the stamp a function of the commit graph, which is the one input a
# content-checksum build cache cannot see (archie-core-pdq2). A source build
# says `dev`; its traceability is the checkout it came from.
GATEWAY_VERSION="dev"
RUNTIME_VERSION="dev"
LDFLAGS="-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion=${GATEWAY_VERSION}"
LDFLAGS="${LDFLAGS} -X github.com/samcharles93/archie-core/internal/app/archied.runtimeVersion=${RUNTIME_VERSION}"
LDFLAGS="${LDFLAGS} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary"
+17 -1
View File
@@ -185,6 +185,9 @@ type boot struct {
lastReload func() config.ReloadStatus
natsClient *nats.Client
// reactionClient pulls the ARCHIE_REACTIONS fan-out stream; the daemon
// drains it each cycle to turn review reactions into remediate runs.
reactionClient *nats.Client
// natsURL is the endpoint the daemon's own client connected with at
// startup. For external mode it is cfg.NATS.URL; for embedded mode it is
// the embedded server's ClientURL(). Recorded so Daemon.ConnectedNATS
@@ -552,6 +555,7 @@ func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embed
// is the deliverable. A future producer (bead archie-core-8li9.3) will
// need its own publisher surface, wired when that step lands.
b.addCleanup(func() { reactionClient.Close() })
b.reactionClient = reactionClient
log.Info("nats connected", "url", url, "task_stream", nats.DefaultStreamName, "reaction_stream", nats.DefaultReactionStreamName)
return nil
}
@@ -1289,6 +1293,7 @@ func (b *boot) buildDaemon() {
Storage: b.storeBackend,
Log: log,
Tasks: b.natsClient,
Reactions: b.reactionClient,
WorktreeGrants: b.worktreeGrants,
StateStoreGrants: b.stateStoreGrants,
ContainerPool: b.containerPool,
@@ -1362,7 +1367,18 @@ func (b *boot) setupForgeWebhook() {
"engine", cfg.Forge.WebhookSecret.Engine, "key", cfg.Forge.WebhookSecret.Key, "err", err)
return
}
receiver := forgewebhook.New(secretValue, cfg.Dispatch.Trigger, cfg.Label, cfg.BotUser, b.d.PublishTask, log)
// The reaction publisher is the consumer's supply side: the same typed
// reaction the poll produces, keyed source-independently, so webhook and
// poll deliveries of one review dedup (pr-review-remediation.md
// decision 2).
publishReaction := func(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error {
payload, err := reaction.Encode()
if err != nil {
return err
}
return b.d.Tasks.PublishUnique(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
}
receiver := forgewebhook.New(secretValue, cfg.Dispatch.Trigger, cfg.Label, cfg.BotUser, b.d.PublishTask, publishReaction, log)
host, port := parseListenAddr(cfg.Forge.WebhookAddr, "0.0.0.0", 8645)
addr := fmt.Sprintf("%s:%d", host, port)
srv := &http.Server{Addr: addr, Handler: receiver}
@@ -2,14 +2,11 @@ package archied
import (
"context"
"errors"
"strings"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
@@ -137,23 +134,25 @@ func TestStateStoreServerOptionsTolerateTheDialersKeepalive(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
elapsed, recvErr := holdWatch(t, tc.opts, keepaliveWindow)
elapsed, recvErr, survived := holdWatch(t, tc.opts, keepaliveWindow)
// The server never writes, so the stream can only end because the
// window ran out or because the connection was torn down under it.
expired := streamEndedByWindow(recvErr)
t.Logf("watch ended after %s with %v", elapsed, recvErr)
if tc.tornDown {
if recvErr == nil || expired {
// connection was torn down under it, or because it outlived the window.
// Which one happened is the select in holdWatch, not the error the
// window's closure surfaces: see holdWatch for why reading the error
// made this case flaky.
t.Logf("watch lasted %s, survived the window: %v, ended with %v", elapsed, survived, recvErr)
if survived {
if tc.tornDown {
t.Fatalf("the dialer's watch was still open after %s: the default EnforcementPolicy (MinTime 5m) must strike pings that arrive 10s apart and answer with GOAWAY too_many_pings, so this case is not reaching the strike budget and the case below would prove nothing", keepaliveWindow)
}
if !strings.Contains(recvErr.Error(), "too_many_pings") {
t.Fatalf("the dialer's watch ended after %s with %v: want GOAWAY too_many_pings, not some other connection loss", elapsed, recvErr)
}
return
}
if recvErr == nil || !expired {
if !tc.tornDown {
t.Fatalf("the dialer's watch ended after %s: %v\nA watch carrying no traffic must survive on the pings staterpc.Dial sends; a server policy that strikes them answers a quiet connection with a dead one at ~40s, which is worse than the keepalive it was added for", elapsed, recvErr)
}
if !strings.Contains(recvErr.Error(), "too_many_pings") {
t.Fatalf("the dialer's watch ended after %s with %v: want GOAWAY too_many_pings, not some other connection loss", elapsed, recvErr)
}
})
}
}
@@ -172,11 +171,30 @@ func (w *quietWatch) Watch(_ *controlpb.WatchRequest, stream controlpb.ControlPl
return stream.Context().Err()
}
// keepaliveSlack keeps the stream's own deadline clear of the observation window.
// They must not be the same duration. The question holdWatch answers is whether
// the link outlives the window, and with the two identical the client deadline
// resolves microseconds after the timer either way: Recv returns
// DeadlineExceeded and the answer becomes a race between two timers rather than
// a fact about the link. Measured -- the same 50s window reported the healthy
// case as "ended" at 49.998s while the timer was still pending.
const keepaliveSlack = 5 * time.Second
// holdWatch serves opts over bufconn, dials it with the shipped dialer
// (staterpc.Dial, so the client keepalive is exactly the one the daemon, the
// dashboard and the agent container run), holds one watch stream open for
// window, and reports how long the stream lasted and how it ended.
func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (time.Duration, error) {
// window, and reports how long the stream lasted, how it ended, and whether it
// outlived the window.
//
// That last report is the property under test, and it is decided by which arm of
// a select wins rather than by the flavour of the error the window's closure
// surfaces. Reading the error instead -- asking for DeadlineExceeded -- made the
// tolerant case flaky under load: the client deadline, the server's stream
// context and the transport all resolve within microseconds of one another, so a
// watch that was still perfectly open was reported as Canceled or Unavailable,
// and a healthy link failed a test about unhealthy links. Measured on a loaded
// 16-core host at 49.999s into a 50s window.
func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (time.Duration, error, bool) {
t.Helper()
listener := bufconn.Listen(1 << 20)
watch := &quietWatch{started: make(chan struct{})}
@@ -194,7 +212,7 @@ func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (ti
})
client := dialStateStore(t, listener, restartAdminToken)
ctx, cancel := context.WithTimeout(t.Context(), window)
ctx, cancel := context.WithTimeout(t.Context(), window+keepaliveSlack)
defer cancel()
stream, err := client.ControlPlane().Watch(ctx, &controlpb.WatchRequest{Kind: "any"})
if err != nil {
@@ -206,14 +224,17 @@ func holdWatch(t *testing.T, opts []grpc.ServerOption, window time.Duration) (ti
t.Fatal("the server never started the watch stream")
}
start := time.Now()
// The server never writes, so this returns only when the window ends or the
// connection dies.
_, recvErr := stream.Recv()
return time.Since(start), recvErr
}
// streamEndedByWindow reports whether err is the window running out rather than
// the connection being torn down under it.
func streamEndedByWindow(err error) bool {
return err != nil && (errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded)
// Buffered so the receiving goroutine cannot outlive the call: cancel runs on
// the way out, Recv returns, and the send still has somewhere to land.
recv := make(chan error, 1)
go func() {
_, err := stream.Recv()
recv <- err
}()
select {
case err := <-recv:
return time.Since(start), err, false
case <-time.After(window):
return time.Since(start), nil, true
}
}
File diff suppressed because it is too large. Load diff
@@ -37,9 +37,13 @@ const (
StateStoreService_Transition_FullMethodName = "/state.v1.StateStoreService/Transition"
StateStoreService_Update_FullMethodName = "/state.v1.StateStoreService/Update"
StateStoreService_Requeue_FullMethodName = "/state.v1.StateStoreService/Requeue"
StateStoreService_ParkTask_FullMethodName = "/state.v1.StateStoreService/ParkTask"
StateStoreService_RecoverStale_FullMethodName = "/state.v1.StateStoreService/RecoverStale"
StateStoreService_ArchiveTask_FullMethodName = "/state.v1.StateStoreService/ArchiveTask"
StateStoreService_RetryTask_FullMethodName = "/state.v1.StateStoreService/RetryTask"
StateStoreService_BeginRemediation_FullMethodName = "/state.v1.StateStoreService/BeginRemediation"
StateStoreService_UpdateReviewPayload_FullMethodName = "/state.v1.StateStoreService/UpdateReviewPayload"
StateStoreService_SetReviewCursors_FullMethodName = "/state.v1.StateStoreService/SetReviewCursors"
StateStoreService_TaskByIssue_FullMethodName = "/state.v1.StateStoreService/TaskByIssue"
StateStoreService_OpenTaskByPR_FullMethodName = "/state.v1.StateStoreService/OpenTaskByPR"
StateStoreService_TaskByID_FullMethodName = "/state.v1.StateStoreService/TaskByID"
@@ -120,10 +124,14 @@ type StateStoreServiceClient interface {
Transition(ctx context.Context, in *TransitionRequest, opts ...grpc.CallOption) (*TransitionResponse, error)
Update(ctx context.Context, in *UpdateRequest, opts ...grpc.CallOption) (*UpdateResponse, error)
Requeue(ctx context.Context, in *RequeueRequest, opts ...grpc.CallOption) (*RequeueResponse, error)
ParkTask(ctx context.Context, in *ParkTaskRequest, opts ...grpc.CallOption) (*ParkTaskResponse, error)
RecoverStale(ctx context.Context, in *RecoverStaleRequest, opts ...grpc.CallOption) (*RecoverStaleResponse, error)
// Archive / Retry
ArchiveTask(ctx context.Context, in *ArchiveTaskRequest, opts ...grpc.CallOption) (*ArchiveTaskResponse, error)
RetryTask(ctx context.Context, in *RetryTaskRequest, opts ...grpc.CallOption) (*RetryTaskResponse, error)
BeginRemediation(ctx context.Context, in *BeginRemediationRequest, opts ...grpc.CallOption) (*BeginRemediationResponse, error)
UpdateReviewPayload(ctx context.Context, in *UpdateReviewPayloadRequest, opts ...grpc.CallOption) (*UpdateReviewPayloadResponse, error)
SetReviewCursors(ctx context.Context, in *SetReviewCursorsRequest, opts ...grpc.CallOption) (*SetReviewCursorsResponse, error)
// Queries
TaskByIssue(ctx context.Context, in *TaskByIssueRequest, opts ...grpc.CallOption) (*TaskByIssueResponse, error)
OpenTaskByPR(ctx context.Context, in *OpenTaskByPRRequest, opts ...grpc.CallOption) (*OpenTaskByPRResponse, error)
@@ -402,6 +410,16 @@ func (c *stateStoreServiceClient) Requeue(ctx context.Context, in *RequeueReques
return out, nil
}
func (c *stateStoreServiceClient) ParkTask(ctx context.Context, in *ParkTaskRequest, opts ...grpc.CallOption) (*ParkTaskResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ParkTaskResponse)
err := c.cc.Invoke(ctx, StateStoreService_ParkTask_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) RecoverStale(ctx context.Context, in *RecoverStaleRequest, opts ...grpc.CallOption) (*RecoverStaleResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RecoverStaleResponse)
@@ -432,6 +450,36 @@ func (c *stateStoreServiceClient) RetryTask(ctx context.Context, in *RetryTaskRe
return out, nil
}
func (c *stateStoreServiceClient) BeginRemediation(ctx context.Context, in *BeginRemediationRequest, opts ...grpc.CallOption) (*BeginRemediationResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(BeginRemediationResponse)
err := c.cc.Invoke(ctx, StateStoreService_BeginRemediation_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) UpdateReviewPayload(ctx context.Context, in *UpdateReviewPayloadRequest, opts ...grpc.CallOption) (*UpdateReviewPayloadResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateReviewPayloadResponse)
err := c.cc.Invoke(ctx, StateStoreService_UpdateReviewPayload_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) SetReviewCursors(ctx context.Context, in *SetReviewCursorsRequest, opts ...grpc.CallOption) (*SetReviewCursorsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetReviewCursorsResponse)
err := c.cc.Invoke(ctx, StateStoreService_SetReviewCursors_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) TaskByIssue(ctx context.Context, in *TaskByIssueRequest, opts ...grpc.CallOption) (*TaskByIssueResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(TaskByIssueResponse)
@@ -917,10 +965,14 @@ type StateStoreServiceServer interface {
Transition(context.Context, *TransitionRequest) (*TransitionResponse, error)
Update(context.Context, *UpdateRequest) (*UpdateResponse, error)
Requeue(context.Context, *RequeueRequest) (*RequeueResponse, error)
ParkTask(context.Context, *ParkTaskRequest) (*ParkTaskResponse, error)
RecoverStale(context.Context, *RecoverStaleRequest) (*RecoverStaleResponse, error)
// Archive / Retry
ArchiveTask(context.Context, *ArchiveTaskRequest) (*ArchiveTaskResponse, error)
RetryTask(context.Context, *RetryTaskRequest) (*RetryTaskResponse, error)
BeginRemediation(context.Context, *BeginRemediationRequest) (*BeginRemediationResponse, error)
UpdateReviewPayload(context.Context, *UpdateReviewPayloadRequest) (*UpdateReviewPayloadResponse, error)
SetReviewCursors(context.Context, *SetReviewCursorsRequest) (*SetReviewCursorsResponse, error)
// Queries
TaskByIssue(context.Context, *TaskByIssueRequest) (*TaskByIssueResponse, error)
OpenTaskByPR(context.Context, *OpenTaskByPRRequest) (*OpenTaskByPRResponse, error)
@@ -1073,6 +1125,9 @@ func (UnimplementedStateStoreServiceServer) Update(context.Context, *UpdateReque
func (UnimplementedStateStoreServiceServer) Requeue(context.Context, *RequeueRequest) (*RequeueResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Requeue not implemented")
}
func (UnimplementedStateStoreServiceServer) ParkTask(context.Context, *ParkTaskRequest) (*ParkTaskResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ParkTask not implemented")
}
func (UnimplementedStateStoreServiceServer) RecoverStale(context.Context, *RecoverStaleRequest) (*RecoverStaleResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RecoverStale not implemented")
}
@@ -1082,6 +1137,15 @@ func (UnimplementedStateStoreServiceServer) ArchiveTask(context.Context, *Archiv
func (UnimplementedStateStoreServiceServer) RetryTask(context.Context, *RetryTaskRequest) (*RetryTaskResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RetryTask not implemented")
}
func (UnimplementedStateStoreServiceServer) BeginRemediation(context.Context, *BeginRemediationRequest) (*BeginRemediationResponse, error) {
return nil, status.Error(codes.Unimplemented, "method BeginRemediation not implemented")
}
func (UnimplementedStateStoreServiceServer) UpdateReviewPayload(context.Context, *UpdateReviewPayloadRequest) (*UpdateReviewPayloadResponse, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateReviewPayload not implemented")
}
func (UnimplementedStateStoreServiceServer) SetReviewCursors(context.Context, *SetReviewCursorsRequest) (*SetReviewCursorsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetReviewCursors not implemented")
}
func (UnimplementedStateStoreServiceServer) TaskByIssue(context.Context, *TaskByIssueRequest) (*TaskByIssueResponse, error) {
return nil, status.Error(codes.Unimplemented, "method TaskByIssue not implemented")
}
@@ -1553,6 +1617,24 @@ func _StateStoreService_Requeue_Handler(srv interface{}, ctx context.Context, de
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ParkTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ParkTaskRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ParkTask(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ParkTask_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ParkTask(ctx, req.(*ParkTaskRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RecoverStale_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RecoverStaleRequest)
if err := dec(in); err != nil {
@@ -1607,6 +1689,60 @@ func _StateStoreService_RetryTask_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_BeginRemediation_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BeginRemediationRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).BeginRemediation(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_BeginRemediation_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).BeginRemediation(ctx, req.(*BeginRemediationRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_UpdateReviewPayload_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateReviewPayloadRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).UpdateReviewPayload(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_UpdateReviewPayload_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).UpdateReviewPayload(ctx, req.(*UpdateReviewPayloadRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SetReviewCursors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetReviewCursorsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SetReviewCursors(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SetReviewCursors_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SetReviewCursors(ctx, req.(*SetReviewCursorsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_TaskByIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TaskByIssueRequest)
if err := dec(in); err != nil {
@@ -2421,6 +2557,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "Requeue",
Handler: _StateStoreService_Requeue_Handler,
},
{
MethodName: "ParkTask",
Handler: _StateStoreService_ParkTask_Handler,
},
{
MethodName: "RecoverStale",
Handler: _StateStoreService_RecoverStale_Handler,
@@ -2433,6 +2573,18 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "RetryTask",
Handler: _StateStoreService_RetryTask_Handler,
},
{
MethodName: "BeginRemediation",
Handler: _StateStoreService_BeginRemediation_Handler,
},
{
MethodName: "UpdateReviewPayload",
Handler: _StateStoreService_UpdateReviewPayload_Handler,
},
{
MethodName: "SetReviewCursors",
Handler: _StateStoreService_SetReviewCursors_Handler,
},
{
MethodName: "TaskByIssue",
Handler: _StateStoreService_TaskByIssue_Handler,
+109 -49
View File
@@ -25,6 +25,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
"github.com/samcharles93/archie-core/internal/events"
@@ -34,6 +35,7 @@ import (
"github.com/samcharles93/archie-core/internal/plugin"
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/taskrun"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools"
"github.com/samcharles93/archie-core/internal/worktree"
)
@@ -132,7 +134,20 @@ type Daemon struct {
// NATS startup is mandatory (there is no broker-off execution mode), so
// production composition always sets it. Nil appears only in tests and
// is handled fail-closed at the publish/run sites.
Tasks TaskBus
Tasks TaskBus
// reactionConsumer is built lazily by drainReactions and kept for its
// lifetime drop counter.
reactionConsumer *reactionConsumer
// reactionPublisher is built lazily by scanPRReviews; an indirection
// only so tests can swap the delivery without the bus.
reactionPublisher ReactionPublisher
// Reactions pulls the review-reaction fan-out stream
// (docs/prds/pr-review-remediation.md). Each cycle it is drained into
// queued remediate runs before the task drain, so a reaction can be
// claimed in the same pass that carried it. Optional: nil disables the
// reaction consumer (tests, or a deployment without the reaction
// stream).
Reactions ReactionSource
WorktreeGrants WorktreeGrantIssuer
// StateStoreGrants issues per-task State Store credentials for container
// env (see containerEnv). Required whenever ConnectedStateStore.URL is
@@ -486,7 +501,9 @@ func (d *Daemon) pollForIdentity(ctx context.Context, id *IdentityRunner) {
func (d *Daemon) maintainAndDrain(ctx context.Context) {
d.cleanupExpiredStorage(ctx)
d.reconcilePRs(ctx)
d.scanPRReviews(ctx)
d.dispatchBindings(ctx)
d.drainReactions(ctx)
if d.Tasks != nil {
d.drainNATS(ctx)
}
@@ -560,7 +577,9 @@ func (d *Daemon) Cycle(ctx context.Context) {
d.cleanupExpiredStorage(ctx)
d.poll(ctx)
d.reconcilePRs(ctx)
d.scanPRReviews(ctx)
d.dispatchBindings(ctx)
d.drainReactions(ctx)
if d.Tasks != nil {
d.drainNATS(ctx)
}
@@ -778,6 +797,40 @@ func (d *Daemon) resolveBindingRepo(b binding.Binding) (string, string, bool) {
return "", "", false
}
// drainReactions turns available review reactions into queued remediate
// runs. It runs before the task drain so a reaction queued in this pass can
// be claimed by it; the consumer is built lazily once, so its drop counter
// spans the process lifetime.
func (d *Daemon) drainReactions(ctx context.Context) {
if d.Reactions == nil || d.Store == nil {
return
}
if d.reactionConsumer == nil {
d.reactionConsumer = newReactionConsumer(
// The store's owned-PR lookup is the authorization boundary: a
// reaction only ever causes work against a PR archie opened and
// still owns (pr-review-remediation.md decision 3).
d.Store,
d.Store,
d.botUserForTask,
d.Log,
)
}
if _, err := d.reactionConsumer.drain(ctx, d.Reactions, maxReactionsPerCycle); err != nil {
d.Log.Error("reaction drain failed", "err", err)
}
}
// botUserForTask resolves the bot login that owns task, so the reaction
// consumer can exclude Archie's own comments. Identity-derived for
// multi-identity deployments, the global forge bot user otherwise.
func (d *Daemon) botUserForTask(task *workflowtask.Task) string {
if runner := d.identityFor(task); runner != nil {
return runner.Cfg.BotUser
}
return d.Cfg.Get().BotUser
}
// drainNATS processes tasks from NATS, falling back to SQLite ClaimNext for
// requeued tasks (waiting_human approval, retry-parked) that didn't come
// through a NATS publish.
@@ -994,7 +1047,7 @@ func (d *Daemon) processNATSTask(ctx context.Context, msg eventbus.Message) {
return
}
if ok, reason := d.identityMayAct(ctx, tm.Identity); !ok {
if ok, reason, _ := d.identityMayAct(ctx, tm.Identity); !ok {
d.Log.Error("nats intake rejected: "+reason, "subject", msg.Subject())
if err := msg.Ack(); err != nil {
d.Log.Warn("ack failed", "err", err)
@@ -1141,36 +1194,11 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
trees := d.treesFor(task)
repo, ok := d.repoFor(task)
if !ok {
d.parkRunningTask(ctx, task.ID, "repo no longer in config")
d.parkRunningTask(ctx, task.ID, "repo no longer in config", taskstate.ParkTerminal)
return
}
if d.ContainerPool == nil {
const reason = "managed agent container pool is unavailable; refusing to run this task on the host"
d.Log.Error("task parked: managed worker unavailable", "task", task.ID,
"hint", "enable containers and make the archie-agent image available, then retry the task")
if err := d.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusParked, reason); err != nil {
d.Log.Warn("managed worker park transition failed", "task", task.ID, "err", err)
return
}
d.recordPark(ctx, task.ID, reason)
d.emit(events.Event{
Kind: events.KindParked, TaskID: task.ID, Attempt: task.Attempt,
Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason,
})
return
}
if d.Tasks == nil {
const reason = "agent task transport is unavailable; refusing to run this task on the host"
d.Log.Error("task parked: agent task transport unavailable", "task", task.ID)
if err := d.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusParked, reason); err != nil {
d.Log.Warn("agent task transport park transition failed", "task", task.ID, "err", err)
return
}
d.recordPark(ctx, task.ID, reason)
d.emit(events.Event{
Kind: events.KindParked, TaskID: task.ID, Attempt: task.Attempt,
Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason,
})
if d.ContainerPool == nil || d.Tasks == nil {
d.parkCapabilityUnavailable(ctx, task, repo)
return
}
@@ -1190,7 +1218,7 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
_, branch, err = trees.Prepare(ctx, task.Owner, task.Repo, repo.BaseBranch(), task.IssueNumber, task.Title, task.Body, task.Labels)
if err != nil {
d.Log.Error("worktree prepare failed", "err", err)
d.parkRunningTask(ctx, task.ID, "worktree prepare failed: "+err.Error())
d.parkRunningTask(ctx, task.ID, "worktree prepare failed: "+err.Error(), taskstate.ParkTransient)
return
}
task.Branch = branch
@@ -1284,7 +1312,7 @@ func (d *Daemon) acquireTaskContainer(
) (*container.Container, func(), bool) {
park := func(reason string, err error) {
d.Log.Error(reason, "err", err)
d.parkRunningTask(ctx, task.ID, reason+": "+err.Error())
d.parkRunningTask(ctx, task.ID, reason+": "+err.Error(), taskstate.ParkTransient)
}
// Write task.json -- the container's boot-time brief.
@@ -1302,7 +1330,7 @@ func (d *Daemon) acquireTaskContainer(
// normal operation, Storage is always set when ContainerPool is set.
if d.Storage == nil {
d.Log.Error("storage backend is nil -- cannot acquire container")
d.parkRunningTask(ctx, task.ID, "storage backend not configured")
d.parkRunningTask(ctx, task.ID, "storage backend not configured", taskstate.ParkTransient)
return nil, nil, false
}
@@ -1355,9 +1383,38 @@ func (d *Daemon) acquireTaskContainer(
return ctr, revokeStateStoreGrant, true
}
// parkCapabilityUnavailable parks a task whose daemon-side capability is
// missing (container pool or task transport): both are environmental, so
// the park class is transient and the KindParked event carries the class
// for the dashboard. The reason distinguishes the two in logs and events.
func (d *Daemon) parkCapabilityUnavailable(ctx context.Context, task *workflow.Task, repo config.Repo) {
var reason string
if d.ContainerPool == nil {
reason = "managed agent container pool is unavailable; refusing to run this task on the host"
d.Log.Error("task parked: managed worker unavailable", "task", task.ID,
"hint", "enable containers and make the archie-agent image available, then retry the task")
} else {
reason = "agent task transport is unavailable; refusing to run this task on the host"
d.Log.Error("task parked: agent task transport unavailable", "task", task.ID)
}
if err := d.Store.ParkTask(ctx, task.ID, workflow.StatusRunning, reason, taskstate.ParkTransient); err != nil {
d.Log.Warn("capability park transition failed", "task", task.ID, "err", err)
return
}
d.recordPark(ctx, task.ID, reason)
d.emit(events.Event{
Kind: events.KindParked, TaskID: task.ID, Attempt: task.Attempt,
Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason,
Data: map[string]any{"park_class": taskstate.ParkTransient},
})
}
// parkRunningTask transitions a task from running to parked using a context
// detached from caller cancellation, with a bounded timeout.
//
// The park carries the caller's taskstate.ParkClass: every call site states
// what kind of intervention its park needs, and the store normalizes the
// class, so an unclassified caller cannot silently mislabel a park.
// When a task fails or is cancelled (e.g. via /stop or dashboard Stop), ctx is
// already cancelled. Writing terminal state using the cancelled ctx fails
// immediately in SQLite transactions and silently leaves the task row 'running'
@@ -1368,14 +1425,14 @@ func (d *Daemon) acquireTaskContainer(
// The transition remains guarded from StatusRunning: if the worker already
// recorded a terminal state over storerpc, storecontract.ErrStaleTransition is returned
// and ignored. Unexpected store errors are logged as warnings.
func (d *Daemon) parkRunningTask(ctx context.Context, taskID int64, reason string) {
func (d *Daemon) parkRunningTask(ctx context.Context, taskID int64, reason string, class taskstate.ParkClass) {
if d.Store == nil {
return
}
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err := d.Store.Transition(writeCtx, taskID, workflow.StatusRunning, workflow.StatusParked, reason); err != nil {
if err := d.Store.ParkTask(writeCtx, taskID, workflow.StatusRunning, reason, class); err != nil {
if !errors.Is(err, storecontract.ErrStaleTransition) {
d.Log.Warn("terminal park transition failed", "task", taskID, "reason", reason, "err", err)
}
@@ -1422,13 +1479,13 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
if d.WorktreeGrants == nil {
const reason = "worktree publication grants are unavailable"
d.Log.Error(reason, "task", task.ID)
d.parkRunningTask(ctx, task.ID, reason)
d.parkRunningTask(ctx, task.ID, reason, taskstate.ParkTransient)
return
}
grant, revoke, err := d.WorktreeGrants.Issue(task)
if err != nil {
d.Log.Error("worktree publication grant failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, "worktree publication grant failed: "+err.Error())
d.parkRunningTask(ctx, task.ID, "worktree publication grant failed: "+err.Error(), taskstate.ParkTransient)
return
}
defer revoke()
@@ -1437,7 +1494,7 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
d.captureAttemptConfig(ctx, task, taskCfg)
if err := d.pinWorkflowDefinition(ctx, task); err != nil {
d.Log.Error("pin workflow definition failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, "pin workflow definition: "+err.Error())
d.parkRunningTask(ctx, task.ID, "pin workflow definition: "+err.Error(), taskstate.ParkTransient)
return
}
req := taskrun.Request{
@@ -1454,26 +1511,26 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
data, err := json.Marshal(req)
if err != nil {
d.Log.Error("taskrun encode failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, "taskrun encode failed: "+err.Error())
d.parkRunningTask(ctx, task.ID, "taskrun encode failed: "+err.Error(), taskstate.ParkTransient)
return
}
reply, err := d.requestTaskRun(ctx, task.ID, data)
if err != nil {
d.Log.Error("taskrun request failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, "taskrun request failed: "+err.Error())
d.parkRunningTask(ctx, task.ID, "taskrun request failed: "+err.Error(), taskstate.ParkTransient)
return
}
var resp taskrun.Response
if err := json.Unmarshal(reply, &resp); err != nil {
d.Log.Error("taskrun decode response failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, "taskrun decode response failed: "+err.Error())
d.parkRunningTask(ctx, task.ID, "taskrun decode response failed: "+err.Error(), taskstate.ParkTransient)
return
}
if resp.Error != "" {
d.Log.Error("taskrun run failed", "task", task.ID, "err", resp.Error)
d.parkRunningTask(ctx, task.ID, "taskrun run failed: "+resp.Error)
d.parkRunningTask(ctx, task.ID, "taskrun run failed: "+resp.Error, taskstate.ParkTransient)
return
}
@@ -1783,6 +1840,9 @@ func (d *Daemon) identityFor(task *workflow.Task) *IdentityRunner {
}
// identityMayAct reports whether the identity a task carries may be acted on.
// A denial also carries the park class the task would need: a name that no
// longer resolves is fixable by re-adding the identity (transient), while a
// retired or deactivated identity is a deliberate operator state (terminal).
// An empty identity is the single-identity root and always may act. A
// non-empty identity must resolve to a configured runner and pass the
// lifecycle check; otherwise the returned reason says why it may not. This is
@@ -1790,29 +1850,29 @@ func (d *Daemon) identityFor(task *workflow.Task) *IdentityRunner {
// credential-side behaviour: a task naming an identity archie no longer knows
// -- renamed, retired, or deleted in the control plane -- must park, never
// fall back to the root forge's credential.
func (d *Daemon) identityMayAct(ctx context.Context, name string) (bool, string) {
func (d *Daemon) identityMayAct(ctx context.Context, name string) (bool, string, taskstate.ParkClass) {
if name == "" {
return true, ""
return true, "", ""
}
runner := d.identityFor(&workflow.Task{Identity: name})
if runner == nil {
return false, "identity " + name + " no longer resolves"
return false, "identity " + name + " no longer resolves", taskstate.ParkTransient
}
if !d.identityActive(ctx, runner.ID) {
return false, "identity " + runner.Name + " may not act"
return false, "identity " + runner.Name + " may not act", taskstate.ParkTerminal
}
return true, ""
return true, "", ""
}
// parkIfIdentityUnresolvable parks task when its non-empty identity cannot be
// acted on, reporting whether it did. An empty identity is the root
// single-identity path and never parks here.
func (d *Daemon) parkIfIdentityUnresolvable(ctx context.Context, task *workflow.Task) bool {
ok, reason := d.identityMayAct(ctx, task.Identity)
ok, reason, class := d.identityMayAct(ctx, task.Identity)
if ok {
return false
}
d.parkRunningTask(ctx, task.ID, reason)
d.parkRunningTask(ctx, task.ID, reason, class)
return true
}
+3 -2
View File
@@ -32,6 +32,7 @@ import (
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskrun"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/worktree"
)
@@ -120,7 +121,7 @@ func TestParkRunningTaskRecordsItsReasonInTheTasksOwnLog(t *testing.T) {
defer closeLog()
const reason = "worktree prepare failed: checkout branch fix/42-x: reference not found"
d.parkRunningTask(ctx, task.ID, reason)
d.parkRunningTask(ctx, task.ID, reason, taskstate.ParkTransient)
page, err := d.TaskLogs.TaskLog(ctx, task.ID, task.Attempt, logging.Query{})
if err != nil {
@@ -166,7 +167,7 @@ func TestParkDoesNotRecordAParkThatLosesTheRace(t *testing.T) {
closeLog := d.openTaskLog(task)
defer closeLog()
d.parkRunningTask(ctx, task.ID, "worktree prepare failed: simulated")
d.parkRunningTask(ctx, task.ID, "worktree prepare failed: simulated", taskstate.ParkTransient)
page, err := d.TaskLogs.TaskLog(ctx, task.ID, task.Attempt, logging.Query{})
if err != nil {
+234
View File
@@ -0,0 +1,234 @@
package daemon
import (
"context"
"errors"
"fmt"
"log/slog"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
)
// ReactionSource is the pull surface the reaction consumer needs: fetch one
// message from the reaction stream, or eventbus.ErrNoMessage when it is
// drained. Narrow on purpose -- the consumer never publishes and never
// subscribes.
type ReactionSource interface {
Fetch(ctx context.Context) (eventbus.Message, error)
}
// maxReactionsPerCycle bounds one drain pass. Reactions are row updates, not
// agent runs, but an unbounded drain could hold the dispatch loop hostage
// behind a burst; anything past the bound waits for the next cycle.
const maxReactionsPerCycle = 32
// remediableReviewStates are the review states a remediation unit addresses.
// approved is a decision-5 exclusion (recording, not remediating; merging
// stays an operator action) and dismissed is withdrawn feedback.
var remediableReviewStates = map[string]bool{
"requested_changes": true,
"commented": true,
}
// reactionConsumer turns forge review reactions on Archie-owned PRs into
// queued remediate runs. It implements the consumer half of
// docs/prds/pr-review-remediation.md decisions 3 and 5: resolve the PR to
// the task that owns it (the authorization boundary), never react to
// Archie's own comments, collect a review's comments into one unit while it
// is pending, and rely on the guarded store transition for dedup.
type reactionConsumer struct {
lookup workintake.ReviewTaskLookup
remediations storecontract.RemediationStarter
botUser func(*workflowtask.Task) string
log *slog.Logger
dropped int64
}
func newReactionConsumer(
lookup workintake.ReviewTaskLookup,
remediations storecontract.RemediationStarter,
botUser func(*workflowtask.Task) string,
log *slog.Logger,
) *reactionConsumer {
return &reactionConsumer{lookup: lookup, remediations: remediations, botUser: botUser, log: log}
}
// drain fetches and handles reactions until the stream is idle or the
// per-cycle bound is reached, returning how many messages it handled.
func (c *reactionConsumer) drain(ctx context.Context, src ReactionSource, limit int) (int, error) {
handled := 0
for handled < limit {
msg, err := src.Fetch(ctx)
if err != nil {
if errors.Is(err, eventbus.ErrNoMessage) {
return handled, nil
}
return handled, fmt.Errorf("fetch reaction: %w", err)
}
if ctx.Err() != nil {
return handled, ctx.Err()
}
c.handle(ctx, msg)
handled++
}
return handled, nil
}
// handle processes one reaction to a terminal outcome: Ack on every decided
// path (drop, dedup, or work queued), Nak only on a transient store failure
// the next delivery can succeed against.
func (c *reactionConsumer) handle(ctx context.Context, msg eventbus.Message) {
envelope, err := workintake.DecodeReviewComment(msg.Data())
if err != nil {
c.log.Error("review reaction decode failed", "subject", msg.Subject(), "err", err)
_ = msg.Ack() // it will never decode on redelivery
return
}
task, err := c.lookup.OpenTaskByPR(ctx, envelope.Owner, envelope.Repo, envelope.PRNumber)
if err != nil {
c.log.Error("review reaction lookup failed", "owner", envelope.Owner, "repo", envelope.Repo, "pr", envelope.PRNumber, "err", err)
_ = msg.Nak()
return
}
if task == nil {
// The resolver counts this: a reaction that does not resolve to a
// live task Archie owns is dropped, never work.
c.drop(msg, "no live task owns this PR")
return
}
if c.botUser(task) != "" && envelope.Author == c.botUser(task) {
// Decision 5: only Archie's own comments are excluded, so its
// ReplyToReview replies never retrigger it. Every other author --
// human or bot -- is actionable.
c.drop(msg, "reaction is archie's own comment")
return
}
switch envelope.Kind {
case workintake.ReviewReactionReview:
c.handleReview(ctx, msg, task, envelope)
case workintake.ReviewReactionComment:
c.handleComment(ctx, msg, task, envelope)
default:
c.drop(msg, "unknown reaction kind")
}
}
func (c *reactionConsumer) handleReview(ctx context.Context, msg eventbus.Message, task *workflowtask.Task, e workintake.ReviewCommentEnvelope) {
if !remediableReviewStates[e.State] {
// approved: no remediation, and never auto-merge (decision 5). The
// review state is visible on the forge itself.
c.drop(msg, fmt.Sprintf("review state %q does not trigger remediation", e.State))
return
}
unit := workflow.ReviewUnit{ReviewID: e.ReviewID, Author: e.Author, State: e.State, Body: e.Body}
payload, err := workflow.EncodeReviewUnit(unit)
if err != nil {
c.log.Error("review unit encode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if err := c.remediations.BeginRemediation(ctx, task.ID, payload); err != nil {
if errors.Is(err, storecontract.ErrStaleTransition) {
// Already queued or claimed: a re-delivered review, or a second
// reaction for a review whose unit is pending. The guarded
// transition is the dedup.
c.log.Debug("remediation already pending", "task", task.ID, "review", e.ReviewID)
_ = msg.Ack()
return
}
c.log.Error("BeginRemediation failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
c.log.Info("review reaction queued a remediation", "task", task.ID, "pr", fmt.Sprintf("%s/%s#%d", e.Owner, e.Repo, e.PRNumber), "review", e.ReviewID, "state", e.State)
_ = msg.Ack()
}
func (c *reactionConsumer) handleComment(ctx context.Context, msg eventbus.Message, task *workflowtask.Task, e workintake.ReviewCommentEnvelope) {
if e.ReviewID == 0 {
// Decision 5: a standalone comment with no parent review is its own
// unit of one.
unit := workflow.ReviewUnit{Comments: []workflow.ReviewUnitComment{{
CommentID: e.CommentID, Path: e.Path, Line: e.Line, Body: e.Body,
}}}
payload, err := workflow.EncodeReviewUnit(unit)
if err != nil {
c.log.Error("review unit encode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if err := c.remediations.BeginRemediation(ctx, task.ID, payload); err != nil {
if errors.Is(err, storecontract.ErrStaleTransition) {
_ = msg.Ack()
return
}
c.log.Error("BeginRemediation failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
_ = msg.Ack()
return
}
// A comment with a parent review is collected into that review's pending
// unit, never dispatched alone. Once the unit has been claimed, its input
// is frozen: a late comment is dropped, and the round cap bounds the
// exchange if the reviewer re-reviews.
if task.Status != workflow.StatusQueued || task.Workflow != "remediate" {
c.drop(msg, "parent review's unit is no longer pending")
return
}
unit, err := workflow.DecodeReviewUnit(task.ReviewPayload)
if err != nil {
if errors.Is(err, workflow.ErrNoReviewPayload) {
c.drop(msg, "queued remediation carries no review unit")
return
}
c.log.Error("review payload decode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if unit.ReviewID != e.ReviewID {
c.drop(msg, "comment's parent review is not the pending unit")
return
}
for _, existing := range unit.Comments {
if existing.CommentID == e.CommentID {
_ = msg.Ack() // re-delivery of an already-collected comment
return
}
}
unit.Comments = append(unit.Comments, workflow.ReviewUnitComment{
CommentID: e.CommentID, Path: e.Path, Line: e.Line, Body: e.Body,
})
payload, err := workflow.EncodeReviewUnit(unit)
if err != nil {
c.log.Error("review unit encode failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
if err := c.remediations.UpdateReviewPayload(ctx, task.ID, payload); err != nil {
if errors.Is(err, storecontract.ErrStaleTransition) {
// Claimed between the read and the write: the unit is frozen.
_ = msg.Ack()
return
}
c.log.Error("UpdateReviewPayload failed", "task", task.ID, "err", err)
_ = msg.Nak()
return
}
_ = msg.Ack()
}
func (c *reactionConsumer) drop(msg eventbus.Message, reason string) {
c.dropped++
c.log.Info("review reaction dropped", "subject", msg.Subject(), "reason", reason)
_ = msg.Ack()
}
+371
View File
@@ -0,0 +1,371 @@
package daemon
import (
"context"
"errors"
"log/slog"
"sync"
"testing"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
)
// ---- fakes ----
type fakeReactionSource struct {
mu sync.Mutex
pending []eventbus.Message
fetchErr error
}
func (f *fakeReactionSource) Fetch(ctx context.Context) (eventbus.Message, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.fetchErr != nil {
return nil, f.fetchErr
}
if len(f.pending) == 0 {
return nil, eventbus.ErrNoMessage
}
m := f.pending[0]
f.pending = f.pending[1:]
return m, nil
}
type fakeReactionMessage struct {
data []byte
subject string
mu sync.Mutex
acked bool
nakked bool
}
func (m *fakeReactionMessage) Data() []byte { return m.data }
func (m *fakeReactionMessage) Subject() string { return m.subject }
func (m *fakeReactionMessage) Ack() error {
m.mu.Lock()
defer m.mu.Unlock()
m.acked = true
return nil
}
func (m *fakeReactionMessage) Nak() error {
m.mu.Lock()
defer m.mu.Unlock()
m.nakked = true
return nil
}
func (m *fakeReactionMessage) wasAcked() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.acked
}
func (m *fakeReactionMessage) wasNakked() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.nakked
}
type fakeRemediations struct {
begun []string // payloads handed to BeginRemediation, in order
updated []string
beginErr error
}
func (f *fakeRemediations) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
if f.beginErr != nil {
return f.beginErr
}
f.begun = append(f.begun, payload)
return nil
}
func (f *fakeRemediations) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
f.updated = append(f.updated, payload)
return nil
}
func (f *fakeRemediations) SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error {
return nil
}
type fakeReviewLookup struct {
task *workflowtask.Task
err error
// sequence, when set, is consulted before task, so a test can model the
// store's fresh read per message (e.g. a unit that queued between two
// reactions).
sequence func(call int) (*workflowtask.Task, error)
calls int
}
func (f *fakeReviewLookup) OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflowtask.Task, error) {
f.calls++
if f.sequence != nil {
return f.sequence(f.calls)
}
return f.task, f.err
}
// ---- helpers ----
func reviewEnvelopeJSON(kind string, reviewID, commentID int64, author, state, body string) []byte {
e := workintake.ReviewCommentEnvelope{
Owner: "acme", Repo: "widgets", PRNumber: 42,
Kind: workintake.ReviewReactionKind(kind),
ReviewID: reviewID, CommentID: commentID,
Author: author, State: state, Body: body,
}
data, err := e.Encode()
if err != nil {
panic(err)
}
return data
}
func ownedTask(status, workflowName, payload string) *workflowtask.Task {
t := &workflowtask.Task{
ID: 7, Owner: "acme", Repo: "widgets", PRNumber: 42,
Status: status, Workflow: workflowName, ReviewPayload: payload,
}
return t
}
func newConsumer(task *workflowtask.Task, remediations *fakeRemediations) *reactionConsumer {
return newReactionConsumer(
&fakeReviewLookup{task: task},
remediations,
func(*workflowtask.Task) string { return "archie-bot" },
slog.New(slog.DiscardHandler),
)
}
// ---- tests ----
func TestReactionConsumerReviewEventStartsARemediation(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "please fix x")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 1 {
t.Fatalf("BeginRemediation calls = %d, want 1", len(remediations.begun))
}
unit, err := workflow.DecodeReviewUnit(remediations.begun[0])
if err != nil {
t.Fatal(err)
}
if unit.ReviewID != 7 || unit.State != "requested_changes" || unit.Body != "please fix x" {
t.Errorf("unit = %+v, want the review's own coordinates", unit)
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerApprovedReviewDoesNotRemediate(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "approved", "lgtm")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 {
t.Errorf("BeginRemediation called for an approved review")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerOwnCommentNeverRetriggers(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 0, 9, "archie-bot", "", "my own reply")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 || len(remediations.updated) != 0 {
t.Errorf("own comment triggered work: begun=%d updated=%d", len(remediations.begun), len(remediations.updated))
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerCommentAppendsToThePendingUnitOfItsReview(t *testing.T) {
remediations := &fakeRemediations{}
pending := ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"state":"requested_changes"}`)
c := newConsumer(pending, remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "fix the loop")}
c.handle(context.Background(), msg)
if len(remediations.updated) != 1 {
t.Fatalf("UpdateReviewPayload calls = %d, want 1", len(remediations.updated))
}
unit, err := workflow.DecodeReviewUnit(remediations.updated[0])
if err != nil {
t.Fatal(err)
}
if unit.ReviewID != 7 || len(unit.Comments) != 1 || unit.Comments[0].CommentID != 9 {
t.Errorf("appended unit = %+v, want comment 9 under review 7", unit)
}
// The parent review's summary survives the append.
if unit.State != "requested_changes" {
t.Errorf("unit state = %q, want the parent review's state preserved", unit.State)
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerDuplicateCommentIsNotAppendedTwice(t *testing.T) {
remediations := &fakeRemediations{}
pending := ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"comments":[{"comment_id":9,"body":"fix the loop"}]}`)
c := newConsumer(pending, remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "fix the loop")}
c.handle(context.Background(), msg)
if len(remediations.updated) != 0 {
t.Errorf("UpdateReviewPayload called for a comment the unit already carries")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerLateCommentAfterDispatchIsDropped(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
// A comment carrying a parent review id, but the task is not a queued
// remediation for it: the unit already dispatched.
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 9, "alice", "", "late comment")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 || len(remediations.updated) != 0 {
t.Errorf("late comment mutated store state: begun=%d updated=%d", len(remediations.begun), len(remediations.updated))
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerStandaloneCommentIsItsOwnUnit(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("comment", 0, 12, "alice", "", "nit: rename")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 1 {
t.Fatalf("BeginRemediation calls = %d, want 1", len(remediations.begun))
}
unit, err := workflow.DecodeReviewUnit(remediations.begun[0])
if err != nil {
t.Fatal(err)
}
if len(unit.Comments) != 1 || unit.Comments[0].CommentID != 12 {
t.Errorf("unit = %+v, want one standalone comment", unit)
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerUnresolvablePRIsDropped(t *testing.T) {
remediations := &fakeRemediations{}
// nil task: the PR does not belong to an archie-owned task.
c := newConsumer(nil, remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "unrelated")}
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 {
t.Errorf("reaction for a foreign PR started work")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerInvalidEnvelopeIsAckedNotRedelivered(t *testing.T) {
remediations := &fakeRemediations{}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: []byte(`{"owner":"acme"}`)} // no kind, no ids
c.handle(context.Background(), msg)
if len(remediations.begun) != 0 {
t.Errorf("invalid envelope started work")
}
if !msg.wasAcked() {
t.Error("message was not acked")
}
}
func TestReactionConsumerTransientStoreErrorNaks(t *testing.T) {
remediations := &fakeRemediations{beginErr: errors.New("db unavailable")}
c := newConsumer(ownedTask(workflowtask.StatusPROpen, "implement", ""), remediations)
msg := &fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "please fix x")}
c.handle(context.Background(), msg)
if !msg.wasNakked() {
t.Error("transient failure was not nakked for redelivery")
}
if msg.wasAcked() {
t.Error("transient failure was acked")
}
}
func TestReactionConsumerDrainsUntilIdle(t *testing.T) {
remediations := &fakeRemediations{}
// The lookup reads the row fresh per message: the review event queues the
// remediation, so the comment event resolves against the queued unit.
lookup := &fakeReviewLookup{sequence: func(call int) (*workflowtask.Task, error) {
if call == 1 {
return ownedTask(workflowtask.StatusPROpen, "implement", ""), nil
}
return ownedTask(workflowtask.StatusQueued, "remediate", `{"review_id":7,"state":"requested_changes","body":"one"}`), nil
}}
c := newReactionConsumer(lookup, remediations, func(*workflowtask.Task) string { return "archie-bot" }, slog.New(slog.DiscardHandler))
src := &fakeReactionSource{pending: []eventbus.Message{
&fakeReactionMessage{data: reviewEnvelopeJSON("review", 7, 0, "alice", "requested_changes", "one")},
&fakeReactionMessage{data: reviewEnvelopeJSON("comment", 7, 8, "alice", "", "one-a")},
}}
n, err := c.drain(context.Background(), src, 8)
if err != nil {
t.Fatal(err)
}
if n != 2 {
t.Errorf("handled = %d, want 2", n)
}
// The review queued the unit; the comment appended to it.
if len(remediations.begun) != 1 || len(remediations.updated) != 1 {
t.Errorf("begun=%d updated=%d, want 1/1", len(remediations.begun), len(remediations.updated))
}
unit, err := workflow.DecodeReviewUnit(remediations.updated[0])
if err != nil {
t.Fatal(err)
}
if len(unit.Comments) != 1 || unit.Comments[0].CommentID != 8 {
t.Errorf("appended unit = %+v, want comment 8 collected under review 7", unit)
}
}
// compile-time interface checks
var (
_ workintake.ReviewTaskLookup = (*fakeReviewLookup)(nil)
_ storecontract.RemediationStarter = (*fakeRemediations)(nil)
)
+141
View File
@@ -0,0 +1,141 @@
package daemon
import (
"context"
"fmt"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/forge"
)
// ReactionPublisher delivers one reaction to the reaction stream. The
// composition root wires it to the task bus's PublishUnique against the
// reaction subject, so webhook and poll deliveries of the same record dedup
// on the envelope's source-independent key.
type ReactionPublisher func(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error
// scanPRReviewReactions is the poll backstop's core for one PR (decision 2):
// list review activity since the task's persisted cursors, publish every
// non-own record as a reaction, and return the advanced cursors. The cursors
// advance past every record seen -- skipped own comments included -- so a
// record is listed once and never re-listed on a later scan. On a publish
// failure the error carries: the caller keeps the old cursors, and the next
// scan re-fetches the records it did not get to (PublishUnique's dedup
// absorbs any re-delivery).
func scanPRReviewReactions(
ctx context.Context,
reader forge.PullRequestReviewReader,
task *workflowtask.Task,
botUser string,
reviewCursor, commentCursor int64,
publish ReactionPublisher,
) (int64, int64, error) {
newReviewCursor, newCommentCursor := reviewCursor, commentCursor
reviews, err := reader.ListReviews(ctx, task.Owner, task.Repo, task.PRNumber, reviewCursor)
if err != nil {
return reviewCursor, commentCursor, err
}
for _, r := range reviews {
if r.ID > newReviewCursor {
newReviewCursor = r.ID
}
if botUser != "" && r.Author == botUser {
continue
}
reaction := workintake.ReviewCommentEnvelope{
Owner: task.Owner, Repo: task.Repo, PRNumber: task.PRNumber,
Kind: workintake.ReviewReactionReview,
ReviewID: r.ID, Author: r.Author, State: r.State, Body: r.Body,
}
if err := publish(ctx, reaction); err != nil {
return reviewCursor, commentCursor, fmt.Errorf("publish review %d: %w", r.ID, err)
}
}
comments, err := reader.ListReviewComments(ctx, task.Owner, task.Repo, task.PRNumber, commentCursor)
if err != nil {
return reviewCursor, commentCursor, err
}
for _, cm := range comments {
if cm.ID > newCommentCursor {
newCommentCursor = cm.ID
}
if botUser != "" && cm.Author == botUser {
continue
}
reaction := workintake.ReviewCommentEnvelope{
Owner: task.Owner, Repo: task.Repo, PRNumber: task.PRNumber,
Kind: workintake.ReviewReactionComment,
ReviewID: cm.ReviewID,
CommentID: cm.ID,
Author: cm.Author, Body: cm.Body, Path: cm.Path, Line: cm.Line,
}
if err := publish(ctx, reaction); err != nil {
return reviewCursor, commentCursor, fmt.Errorf("publish comment %d: %w", cm.ID, err)
}
}
return newReviewCursor, newCommentCursor, nil
}
// scanPRReviews runs the shared per-PR review scan over every open PR task
// (reconcilePRs's shape): one pass over all pr_open tasks, each scanned with
// the forge client its own identity owns. A forge without the review-reader
// capability is skipped, not an error. Wired after reconcilePRs so a PR
// that just left pr_open is not scanned for reactions in the same pass.
func (d *Daemon) scanPRReviews(ctx context.Context) {
if d.Store == nil || d.Tasks == nil {
return
}
tasks, err := d.Store.OpenPRs(ctx)
if err != nil {
d.Log.Error("review scan query failed", "err", err)
return
}
if d.reactionPublisher == nil {
d.reactionPublisher = d.publishReaction
}
for i := range tasks {
t := &tasks[i]
reader, ok := d.forgeFor(t).(forge.PullRequestReviewReader)
if !ok {
continue // the noop forge and any forge without the capability
}
d.scanOnePR(ctx, reader, t)
}
}
func (d *Daemon) scanOnePR(ctx context.Context, reader forge.PullRequestReviewReader, t *workflowtask.Task) {
// A forge read failure skips the task for this scan with its cursors
// unchanged: the next scan re-fetches, and PublishUnique's dedup covers
// anything the previous scan already published.
reviewCursor, commentCursor, err := scanPRReviewReactions(
ctx, reader, t, d.botUserForTask(t),
t.ReviewCursor, t.WatchCommentID, d.reactionPublisher)
if err != nil {
d.Log.Warn("review scan failed", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber, "err", err)
return
}
if reviewCursor == t.ReviewCursor && commentCursor == t.WatchCommentID {
return
}
if err := d.Store.SetReviewCursors(ctx, t.ID, reviewCursor, commentCursor); err != nil {
// A stale guard here means the task was claimed between the scan and
// the write; the next scan re-reads and re-lists from the old cursor,
// and PublishUnique plus the consumer's dedup absorb the repeats.
d.Log.Warn("review cursor persist failed", "task", t.ID, "err", err)
}
}
// publishReaction encodes one reaction and publishes it on the reaction
// subject with its source-independent idempotency key, so a webhook delivery
// and a poll record of the same review collapse into one.
func (d *Daemon) publishReaction(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error {
payload, err := reaction.Encode()
if err != nil {
return err
}
return d.Tasks.PublishUnique(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
}
+138
View File
@@ -0,0 +1,138 @@
package daemon
import (
"context"
"errors"
"testing"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/forge"
)
type fakeReviewReader struct {
reviews []forge.Review
comments []forge.ReviewComment
listErr error
}
func (f *fakeReviewReader) ListReviews(ctx context.Context, owner, repo string, number int, sinceID int64) ([]forge.Review, error) {
// The real implementations filter on the forge; the fake models the
// contract so "records at or below the cursor never come back" is
// actually exercised.
var out []forge.Review
for _, r := range f.reviews {
if r.ID > sinceID {
out = append(out, r)
}
}
return out, f.listErr
}
func (f *fakeReviewReader) ListReviewComments(ctx context.Context, owner, repo string, number int, sinceID int64) ([]forge.ReviewComment, error) {
var out []forge.ReviewComment
for _, c := range f.comments {
if c.ID > sinceID {
out = append(out, c)
}
}
return out, f.listErr
}
func (f *fakeReviewReader) ReplyToReview(ctx context.Context, owner, repo string, number int, inReplyTo int64, body string) error {
return nil
}
type recordingPublisher struct {
reactions []workintake.ReviewCommentEnvelope
err error
}
func (p *recordingPublisher) publish(ctx context.Context, e workintake.ReviewCommentEnvelope) error {
if p.err != nil {
return p.err
}
p.reactions = append(p.reactions, e)
return nil
}
func openTask(prNumber int, reviewCursor, commentCursor int64) *workflowtask.Task {
return &workflowtask.Task{ID: 7, Owner: "acme", Repo: "widgets", PRNumber: prNumber, Status: "pr_open", ReviewCursor: reviewCursor, WatchCommentID: commentCursor}
}
func TestScanPRReviewReactionsPublishesNewRecordsAndSkipsOwn(t *testing.T) {
reader := &fakeReviewReader{
reviews: []forge.Review{
{ID: 5, Author: "archie-bot", State: "requested_changes", Body: "mine"},
{ID: 7, Author: "alice", State: "requested_changes", Body: "please fix"},
},
comments: []forge.ReviewComment{
{ID: 9, ReviewID: 7, Author: "archie-bot", Body: "my reply"},
{ID: 11, ReviewID: 7, Author: "bob", Body: "also this", Path: "x.go", Line: 3},
},
}
publisher := &recordingPublisher{}
task := openTask(42, 0, 0)
reviewCursor, commentCursor, err := scanPRReviewReactions(
context.Background(), reader, task, "archie-bot", 0, 0, publisher.publish)
if err != nil {
t.Fatal(err)
}
// The own review and own reply are excluded; alice's review and bob's
// comment are the two actionable records.
if len(publisher.reactions) != 2 {
t.Fatalf("published = %d, want 2", len(publisher.reactions))
}
if publisher.reactions[0].Kind != workintake.ReviewReactionReview || publisher.reactions[0].ReviewID != 7 {
t.Errorf("first reaction = %+v, want alice's review 7", publisher.reactions[0])
}
if publisher.reactions[1].Kind != workintake.ReviewReactionComment || publisher.reactions[1].CommentID != 11 {
t.Errorf("second reaction = %+v, want bob's comment 11", publisher.reactions[1])
}
if publisher.reactions[1].ReviewID != 7 {
t.Errorf("comment reaction ReviewID = %d, want 7 (collected under its review)", publisher.reactions[1].ReviewID)
}
if publisher.reactions[1].Body != "also this" || publisher.reactions[1].Path != "x.go" || publisher.reactions[1].Line != 3 {
t.Errorf("comment payload = %+v, want the comment's own content", publisher.reactions[1])
}
// Cursors advance past every record seen, own or not: a cursor that
// stalls on a skipped record would re-list it every scan forever.
if reviewCursor != 7 || commentCursor != 11 {
t.Errorf("cursors = (%d, %d), want (7, 11)", reviewCursor, commentCursor)
}
}
func TestScanPRReviewReactionsSkipRecordsAtOrBelowTheCursors(t *testing.T) {
reader := &fakeReviewReader{
reviews: []forge.Review{{ID: 5, Author: "alice", State: "requested_changes", Body: "old"}},
comments: []forge.ReviewComment{{ID: 6, ReviewID: 5, Author: "bob", Body: "old comment"}},
}
publisher := &recordingPublisher{}
reviewCursor, commentCursor, err := scanPRReviewReactions(
context.Background(), reader, openTask(42, 5, 6), "archie-bot", 5, 6, publisher.publish)
if err != nil {
t.Fatal(err)
}
if len(publisher.reactions) != 0 {
t.Errorf("published %d reactions for records at or below the cursors", len(publisher.reactions))
}
if reviewCursor != 5 || commentCursor != 6 {
t.Errorf("cursors = (%d, %d), want unchanged (5, 6)", reviewCursor, commentCursor)
}
}
func TestScanPRReviewReactionsKeepsCursorsOnPublishFailure(t *testing.T) {
reader := &fakeReviewReader{
reviews: []forge.Review{{ID: 7, Author: "alice", State: "requested_changes", Body: "fix"}},
}
publisher := &recordingPublisher{err: errors.New("bus unavailable")}
_, _, err := scanPRReviewReactions(
context.Background(), reader, openTask(42, 0, 0), "archie-bot", 0, 0, publisher.publish)
if err == nil {
t.Fatal("publish error was swallowed; the cursors must not advance past unpublished records")
}
}
+2 -1
View File
@@ -25,6 +25,7 @@ import (
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskrun"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/worktree"
)
@@ -445,7 +446,7 @@ func TestParkRunningTaskGuardedAndLogging(t *testing.T) {
_ = s.Close()
}
d.parkRunningTask(callCtx, task.ID, "simulated park reason")
d.parkRunningTask(callCtx, task.ID, "simulated park reason", taskstate.ParkTransient)
logOutput := buf.String()
if tt.wantWarning {
@@ -32,10 +32,12 @@ import (
// Consumers depend on TaskStore, never on a concrete type.
type TaskStore interface {
TaskLifecycle
TaskParker
TaskEvents
TaskQueries
TaskArchiver
TaskRetryer
RemediationStarter
}
// TaskLifecycle manages the core task state machine and enqueuing.
@@ -53,6 +55,16 @@ type TaskLifecycle interface {
RecoverStale(ctx context.Context) (int64, error)
}
// TaskParker is the classified park write, kept off TaskLifecycle so that
// interface stays under the repo's 8-method cap. It mirrors Transition with
// a park class attached (taskstate.ParkClass); the class is normalized
// store-side, so an empty or unknown value becomes needs_human rather than
// an error -- a park that predates classification must not fail because its
// caller did not know the vocabulary.
type TaskParker interface {
ParkTask(ctx context.Context, taskID int64, from, detail, class string) 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.
@@ -66,6 +78,22 @@ type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) 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. UpdateReviewPayload appends late-arriving comments
// to a still-queued unit. Both guards are the reaction consumer's dedup and
// are documented in docs/prds/pr-review-remediation.md decisions 3 and 5.
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
}
// TaskQueries groups read-only task accessors.
type TaskQueries interface {
TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
+9 -6
View File
@@ -155,19 +155,22 @@ func StageResumeWorktree() Stage {
// StageRemediationRoundCap enforces the hard stop on an unbounded
// remediate/re-review exchange (decision 5, "bounding the exchange").
// Task.RetryCount doubles as the remediation round counter here: on the
// Task.RemediationRounds is the remediation's own budget, separate from
// RetryCount (the operator's): one shared counter made N operator retries
// eat the review-remediation budget and vice versa, and let a repo-level
// round cap re-park a task an operator had just legally retried. On the
// cap it parks the task and posts one comment explaining why, without
// running the builder; under the cap it counts this round and proceeds.
func StageRemediationRoundCap() Stage {
return Stage{Name: "round-cap", Run: func(ctx context.Context, tc *TaskContext) error {
maxRounds := tc.Repo.EffectiveMaxRetries(tc.Cfg.MaxRetries)
if maxRounds > 0 && tc.Task.RetryCount >= maxRounds {
detail := fmt.Sprintf("remediation round cap reached (%d/%d); stopping and parking for an operator", tc.Task.RetryCount, maxRounds)
if maxRounds > 0 && tc.Task.RemediationRounds >= maxRounds {
detail := fmt.Sprintf("remediation round cap reached (%d/%d); stopping and parking for an operator", tc.Task.RemediationRounds, maxRounds)
postRemediationComment(ctx, tc, "Archie has stopped remediating this review: "+detail+".")
tc.Outcome = Outcome{Status: StatusParked, Detail: clip(detail, remediationRoundCapBytes)}
return nil
}
tc.Task.RetryCount++
tc.Task.RemediationRounds++
return nil
}}
}
@@ -272,7 +275,7 @@ func StageRemediationReply() Stage {
if tc.BuildNoChanges {
summary = "Reviewed -- no code change was required."
}
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", summary, tc.Task.RetryCount)
reply := fmt.Sprintf("%s\n\n---\n*archie remediation, round %d*", summary, tc.Task.RemediationRounds)
if id, ok := tc.reviewUnit.replyTarget(); ok {
if err := tc.Forge.ReplyToReview(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, id, reply); err != nil {
@@ -283,7 +286,7 @@ func StageRemediationReply() Stage {
}
tc.Task.ReviewPayload = ""
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RetryCount)}
tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("remediated review round %d", tc.Task.RemediationRounds)}
return nil
}}
}
+11 -11
View File
@@ -70,14 +70,14 @@ func TestStageResumeWorktreeResumesOntoTheTaskBranch(t *testing.T) {
func TestStageRemediationRoundCapCountsARoundUnderTheCap(t *testing.T) {
forge := &fakeForge{}
tc := &TaskContext{
Task: &Task{ID: 1, RetryCount: 1}, Repo: config.Repo{MaxRetries: 3}, Forge: forge,
Task: &Task{ID: 1, RemediationRounds: 1}, Repo: config.Repo{MaxRetries: 3}, Forge: forge,
Log: slog.New(slog.DiscardHandler),
}
if err := StageRemediationRoundCap().Run(t.Context(), tc); err != nil {
t.Fatalf("StageRemediationRoundCap: %v", err)
}
if tc.Task.RetryCount != 2 {
t.Fatalf("RetryCount = %d, want 2", tc.Task.RetryCount)
if tc.Task.RemediationRounds != 2 {
t.Fatalf("RemediationRounds = %d, want 2", tc.Task.RemediationRounds)
}
if tc.Outcome.Status != "" {
t.Fatalf("Outcome = %+v, want zero value (workflow continues)", tc.Outcome)
@@ -90,14 +90,14 @@ func TestStageRemediationRoundCapCountsARoundUnderTheCap(t *testing.T) {
func TestStageRemediationRoundCapParksAtTheCapAndPostsOneComment(t *testing.T) {
forge := &fakeForge{}
tc := &TaskContext{
Task: &Task{ID: 1, RetryCount: 3, PRNumber: 9}, Repo: config.Repo{MaxRetries: 3}, Forge: forge,
Task: &Task{ID: 1, RemediationRounds: 3, PRNumber: 9}, Repo: config.Repo{MaxRetries: 3}, Forge: forge,
Log: slog.New(slog.DiscardHandler),
}
if err := StageRemediationRoundCap().Run(t.Context(), tc); err != nil {
t.Fatalf("StageRemediationRoundCap: %v", err)
}
if tc.Task.RetryCount != 3 {
t.Fatalf("RetryCount = %d, want unchanged at 3", tc.Task.RetryCount)
if tc.Task.RemediationRounds != 3 {
t.Fatalf("RemediationRounds = %d, want unchanged at 3", tc.Task.RemediationRounds)
}
if tc.Outcome.Status != StatusParked {
t.Fatalf("Outcome.Status = %q, want parked", tc.Outcome.Status)
@@ -109,7 +109,7 @@ func TestStageRemediationRoundCapParksAtTheCapAndPostsOneComment(t *testing.T) {
func TestStageRemediationRoundCapZeroMeansUnlimited(t *testing.T) {
tc := &TaskContext{
Task: &Task{ID: 1, RetryCount: 50}, Repo: config.Repo{}, Cfg: config.Config{MaxRetries: 0},
Task: &Task{ID: 1, RemediationRounds: 50}, Repo: config.Repo{}, Cfg: config.Config{MaxRetries: 0},
Forge: &fakeForge{}, Log: slog.New(slog.DiscardHandler),
}
if err := StageRemediationRoundCap().Run(t.Context(), tc); err != nil {
@@ -118,8 +118,8 @@ func TestStageRemediationRoundCapZeroMeansUnlimited(t *testing.T) {
if tc.Outcome.Status == StatusParked {
t.Fatal("Outcome = parked, want no cap enforced when max_retries is unset")
}
if tc.Task.RetryCount != 51 {
t.Fatalf("RetryCount = %d, want 51", tc.Task.RetryCount)
if tc.Task.RemediationRounds != 51 {
t.Fatalf("RemediationRounds = %d, want 51", tc.Task.RemediationRounds)
}
}
@@ -240,8 +240,8 @@ func TestRemediateEndToEndAddressesCommentsAndReplies(t *testing.T) {
if forge.replyCommentID != 10 {
t.Fatalf("replyCommentID = %d, want 10", forge.replyCommentID)
}
if task.RetryCount != 1 {
t.Fatalf("RetryCount = %d, want 1 (one round consumed)", task.RetryCount)
if task.RemediationRounds != 1 {
t.Fatalf("RemediationRounds = %d, want 1 (one round consumed)", task.RemediationRounds)
}
if task.ReviewPayload != "" {
t.Fatalf("ReviewPayload = %q, want cleared", task.ReviewPayload)
+20 -2
View File
@@ -64,9 +64,16 @@ type Task struct {
// (parking-to-queued transitions). When it reaches the configured
// max_retries the daemon moves the task to StatusDead.
RetryCount int `json:"retry_count"`
// WatchCommentID: replies to the issue after this comment are the
// human input a waiting_human task is blocked on.
// WatchCommentID is the poll backstop's high-water mark over forge
// review-comment IDs for this task (pr-review-remediation.md decision
// 2's persisted per-task cursor; the comment-watch design it was
// created for never shipped, and the field carries the cursor now).
WatchCommentID int64 `json:"watch_comment_id"`
// ReviewCursor is the poll backstop's high-water mark over forge
// review IDs. It is deliberately separate from WatchCommentID: review
// and comment IDs are independent forge sequences, and one combined
// cursor would silently skip reviews once a larger comment ID landed.
ReviewCursor int64 `json:"review_cursor"`
// Source is "forge" (default; a real forge issue backs this task) or
// "chat" (created via /spawn with no forge issue). Workflow stages
// and daemon reconciliation must skip forge-only operations (issue
@@ -93,6 +100,17 @@ type Task struct {
// the remediation round counter for this same task, bounded by the
// repo's existing max_retries (decision 5's round cap).
ReviewPayload string `json:"review_payload"`
// ParkClass is the producer-recorded answer to "what kind of
// intervention does this park need?" (taskstate.ParkClass). Set at the
// park site, never inferred from reason text; needs_human is the
// default an unclassified park reads as.
ParkClass string `json:"park_class"`
// RemediationRounds counts review-triggered remediation rounds,
// bounded by the repo's max_retries (pr-review-remediation.md
// decision 5). Deliberately separate from RetryCount, the operator
// budget: one shared counter made N operator retries eat the
// review-remediation budget and vice versa.
RemediationRounds int `json:"remediation_rounds"`
// CreatedAt and UpdatedAt are the SQLite row timestamps, exposed so
// callers can show a task's age and last activity. They are written by
// column defaults and the UPDATE statements, never by the caller.
+9 -1
View File
@@ -123,6 +123,7 @@ type Review struct {
ID int64
Author string
State string // one of the ReviewState* constants
Body string // the review's own top-level summary; empty for a bare verdict
SubmittedAt time.Time
}
@@ -131,7 +132,14 @@ type Review struct {
// the whole file. InReplyTo is the parent comment ID on GitHub; Gitea's
// inline comments are flat under a review, so it is 0 there.
type ReviewComment struct {
ID int64
ID int64
// ReviewID is the review this comment belongs to. It is what lets a
// comment be collected into its review's remediation unit instead of
// starting one of its own (pr-review-remediation.md decision 5); a
// standalone comment carries 0. GitHub carries it on the comment;
// Gitea's flat comment list is walked per review, so the mapping comes
// from the walk.
ReviewID int64
Author string
Body string
Path string
+2
View File
@@ -188,6 +188,7 @@ func (c *GiteaClient) ListReviews(ctx context.Context, owner, repo string, numbe
ID: r.ID,
Author: giteaReviewAuthor(r.Reviewer),
State: normalizeGiteaReviewState(r.State),
Body: r.Body,
SubmittedAt: r.Submitted,
})
}
@@ -219,6 +220,7 @@ func (c *GiteaClient) ListReviewComments(ctx context.Context, owner, repo string
}
out = append(out, ReviewComment{
ID: cm.ID,
ReviewID: rv.ID,
Author: giteaReviewAuthor(cm.Reviewer),
Body: cm.Body,
Path: cm.Path,
+2
View File
@@ -207,6 +207,7 @@ func (c *GitHubClient) ListReviews(ctx context.Context, owner, repo string, numb
ID: r.GetID(),
Author: r.GetUser().GetLogin(),
State: normalizeReviewState(r.GetState()),
Body: r.GetBody(),
SubmittedAt: r.GetSubmittedAt().Time,
})
}
@@ -237,6 +238,7 @@ func (c *GitHubClient) ListReviewComments(ctx context.Context, owner, repo strin
}
out = append(out, ReviewComment{
ID: cm.GetID(),
ReviewID: cm.GetPullRequestReviewID(),
Author: cm.GetUser().GetLogin(),
Body: cm.GetBody(),
Path: cm.GetPath(),
+201
View File
@@ -0,0 +1,201 @@
package webhook
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/google/go-github/v78/github"
"github.com/samcharles93/archie-core/internal/domain/workintake"
)
// reviewEvent builds a signed pull_request_review delivery, GitHub's
// low-latency path for "a human reacted to archie's PR" (decision 2).
func reviewEvent(t *testing.T, action string, mutate func(*github.PullRequestReviewEvent)) *http.Request {
t.Helper()
ev := &github.PullRequestReviewEvent{
Action: new(action),
Review: &github.PullRequestReview{
ID: new(int64(7)),
State: new("requested_changes"),
Body: new("please fix the loop"),
User: &github.User{Login: new("alice")},
},
PullRequest: &github.PullRequest{Number: new(42)},
Repo: &github.Repository{
Name: new("widgets"),
Owner: &github.User{Login: new("acme")},
},
}
if mutate != nil {
mutate(ev)
}
payload, err := json.Marshal(ev)
if err != nil {
t.Fatal(err)
}
return signedRequest(t, testSecret, "pull_request_review", payload)
}
func reviewCommentEvent(t *testing.T, action string, mutate func(*github.PullRequestReviewCommentEvent)) *http.Request {
t.Helper()
ev := &github.PullRequestReviewCommentEvent{
Action: new(action),
Comment: &github.PullRequestComment{
ID: new(int64(11)),
PullRequestReviewID: new(int64(7)),
Body: new("also this"),
Path: new("x.go"),
Line: new(3),
User: &github.User{Login: new("bob")},
},
PullRequest: &github.PullRequest{Number: new(42)},
Repo: &github.Repository{
Name: new("widgets"),
Owner: &github.User{Login: new("acme")},
},
}
if mutate != nil {
mutate(ev)
}
payload, err := json.Marshal(ev)
if err != nil {
t.Fatal(err)
}
return signedRequest(t, testSecret, "pull_request_review_comment", payload)
}
func serveReaction(t *testing.T, r *Receiver, req *http.Request) (*httptest.ResponseRecorder, []workintake.ReviewCommentEnvelope) {
t.Helper()
var published []workintake.ReviewCommentEnvelope
r.reactionPublish = func(_ context.Context, e workintake.ReviewCommentEnvelope) error {
published = append(published, e)
return nil
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec, published
}
func newReactionReceiver() *Receiver {
return New(testSecret, "label", testLabel, testBot, nil, nil, nil)
}
func TestReceiverPublishesASubmittedReviewAsAReaction(t *testing.T) {
r := newReactionReceiver()
rec, published := serveReaction(t, r, reviewEvent(t, "submitted", nil))
if rec.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", rec.Code)
}
if len(published) != 1 {
t.Fatalf("published = %d, want 1", len(published))
}
e := published[0]
if e.Kind != workintake.ReviewReactionReview || e.ReviewID != 7 || e.Owner != "acme" || e.Repo != "widgets" || e.PRNumber != 42 {
t.Errorf("reaction = %+v, want review 7 on acme/widgets#42", e)
}
if e.State != "requested_changes" || e.Body != "please fix the loop" || e.Author != "alice" {
t.Errorf("reaction content = %+v, want the review's own state/body/author", e)
}
// The idempotency key is kinded (decision 3): a review ID and a comment
// ID come from independent forge sequences and must never collide.
if e.IdempotencyKey() == "" {
t.Error("reaction carried no idempotency key")
}
}
func TestReceiverPublishesACreatedCommentAsAReaction(t *testing.T) {
r := newReactionReceiver()
rec, published := serveReaction(t, r, reviewCommentEvent(t, "created", nil))
if rec.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", rec.Code)
}
if len(published) != 1 {
t.Fatalf("published = %d, want 1", len(published))
}
e := published[0]
if e.Kind != workintake.ReviewReactionComment || e.CommentID != 11 || e.ReviewID != 7 {
t.Errorf("reaction = %+v, want comment 11 collected under review 7", e)
}
}
func TestReceiverIgnoresNonActionReviewActivity(t *testing.T) {
tests := []struct {
name string
kind string
action string
}{
{"dismissed review", "review", "dismissed"},
{"edited review", "review", "edited"},
{"deleted review", "review", "deleted"},
{"edited comment", "comment", "edited"},
{"deleted comment", "comment", "deleted"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := newReactionReceiver()
var req *http.Request
if tt.kind == "review" {
req = reviewEvent(t, tt.action, nil)
} else {
req = reviewCommentEvent(t, tt.action, nil)
}
rec, published := serveReaction(t, r, req)
if rec.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", rec.Code)
}
if len(published) != 0 {
t.Errorf("published %d reactions for action %q", len(published), tt.action)
}
})
}
}
func TestReceiverReactionWithoutTheCapabilityIsUntouched(t *testing.T) {
// A receiver composed without the reaction publisher (nil) must not
// panic or publish when a review event arrives: the reaction path is an
// optional capability, the issue path is the receiver's core contract.
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
rec := httptest.NewRecorder()
r.ServeHTTP(rec, reviewEvent(t, "submitted", nil))
if rec.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", rec.Code)
}
}
func TestReceiverRateLimitsReactionDeliveries(t *testing.T) {
r := newReactionReceiver()
// Drive the limiter to its per-window ceiling with one remote, then
// assert the next reaction from that remote is refused with 429 while a
// different remote still passes.
remote := "10.0.0.1:1234"
for i := range reactionRateLimit {
req := reviewEvent(t, "submitted", nil)
req.RemoteAddr = remote
rec, _ := serveReaction(t, r, req)
if rec.Code != http.StatusAccepted {
t.Fatalf("delivery %d within the window: status = %d, want 202", i+1, rec.Code)
}
}
req := reviewEvent(t, "submitted", nil)
req.RemoteAddr = remote
rec, published := serveReaction(t, r, req)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("over-limit status = %d, want 429", rec.Code)
}
if len(published) != 0 {
t.Errorf("over-limit delivery published %d reactions", len(published))
}
otherReq := reviewEvent(t, "submitted", nil)
otherReq.RemoteAddr = "10.0.0.2:1234"
rec, published = serveReaction(t, r, otherReq)
if rec.Code != http.StatusAccepted || len(published) != 1 {
t.Errorf("different remote blocked: status = %d, published = %d", rec.Code, len(published))
}
}
+176 -31
View File
@@ -55,37 +55,67 @@ const maxBodyBytes = 1 << 20 // 1 MiB
// (*daemon.Daemon).PublishTask, the same enqueue path the poller uses.
type PublishFunc func(ctx context.Context, task workintake.TaskEnvelope) error
// ReactionPublishFunc delivers one decoded review reaction to the reaction
// stream (pr-review-remediation.md decision 2's webhook producer). The
// composition root wires it to PublishUnique against the envelope's reaction
// subject, so a webhook delivery and a poll record of the same review dedup
// on the envelope's source-independent key. The reaction path carries no
// dispatch predicate: eligibility is the consumer's owned-PR lookup.
type ReactionPublishFunc func(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error
// reactionRateLimit bounds reaction deliveries per remote source per window
// (decision 6's per-source rate limiting, due now that the receiver carries a
// second event family). It guards spend, not authorization: the owned-task
// guard at the consumer remains the authorization boundary.
const (
reactionRateLimit = 60
reactionRateWindow = time.Minute
reactionRateBucketTTL = 5 * time.Minute
)
// Receiver is the HTTP handler for forge webhooks. It verifies the signature,
// decodes the event, applies the shared dispatch predicate, and publishes
// matched issues.
type Receiver struct {
secret string
trigger string
label string
botUser string
publish PublishFunc
log *slog.Logger
secret string
trigger string
label string
botUser string
publish PublishFunc
reactionPublish ReactionPublishFunc
log *slog.Logger
mu sync.Mutex
startedAt time.Time
lastReceivedAt time.Time
deliveries uint64
publishes uint64
mu sync.Mutex
startedAt time.Time
lastReceivedAt time.Time
deliveries uint64
publishes uint64
reactionPublishes uint64
reactionLimiter map[string]*reactionWindow
}
// reactionWindow is one remote's fixed-window rate budget.
type reactionWindow struct {
start time.Time
count int
}
// New returns an unstarted Receiver.
func New(secret, trigger, label, botUser string, publish PublishFunc, log *slog.Logger) *Receiver {
func New(secret, trigger, label, botUser string, publish PublishFunc, reactionPublish ReactionPublishFunc, log *slog.Logger) *Receiver {
if log == nil {
log = slog.New(slog.DiscardHandler)
}
return &Receiver{
secret: secret,
trigger: trigger,
label: label,
botUser: botUser,
publish: publish,
log: log.With("component", "forge-webhook"),
startedAt: time.Now(),
secret: secret,
trigger: trigger,
label: label,
botUser: botUser,
publish: publish,
reactionPublish: reactionPublish,
reactionLimiter: map[string]*reactionWindow{},
log: log.With("component", "forge-webhook"),
startedAt: time.Now(),
}
}
@@ -96,10 +126,11 @@ func New(secret, trigger, label, botUser string, publish PublishFunc, log *slog.
// Publishes counts only what the dispatch predicate turned into work.
// LastReceivedAt is nil until the first authenticated delivery arrives.
type Status struct {
StartedAt time.Time `json:"started_at"`
LastReceivedAt *time.Time `json:"last_received_at"`
Deliveries uint64 `json:"deliveries"`
Publishes uint64 `json:"publishes"`
StartedAt time.Time `json:"started_at"`
LastReceivedAt *time.Time `json:"last_received_at"`
Deliveries uint64 `json:"deliveries"`
Publishes uint64 `json:"publishes"`
ReactionPublishes uint64 `json:"reaction_publishes"`
}
// Status returns a snapshot of the receiver's activity counters.
@@ -107,9 +138,10 @@ func (r *Receiver) Status() Status {
r.mu.Lock()
defer r.mu.Unlock()
s := Status{
StartedAt: r.startedAt,
Deliveries: r.deliveries,
Publishes: r.publishes,
StartedAt: r.startedAt,
Deliveries: r.deliveries,
Publishes: r.publishes,
ReactionPublishes: r.reactionPublishes,
}
if !r.lastReceivedAt.IsZero() {
last := r.lastReceivedAt
@@ -136,6 +168,13 @@ func (r *Receiver) recordPublish() {
r.publishes++
}
// recordReactionPublish marks one delivery as having produced a reaction.
func (r *Receiver) recordReactionPublish() {
r.mu.Lock()
defer r.mu.Unlock()
r.reactionPublishes++
}
// ServeHTTP handles one forge webhook delivery. GitHub only ever POSTs here,
// so any GET is answered with the receiver's Status instead -- an operator
// (or a monitor) can curl the same address the webhook is configured against
@@ -177,14 +216,23 @@ func (r *Receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// independent of whether it turns out to be dispatch-eligible.
r.recordDelivery()
issueEvent, ok := event.(*github.IssuesEvent)
if !ok {
// Not an issue event (ping, pull_request, etc.). Acknowledge and
// ignore -- this receiver only turns issue activity into work.
switch e := event.(type) {
case *github.IssuesEvent:
r.serveIssueEvent(w, req, e)
case *github.PullRequestReviewEvent:
r.serveReviewEvent(w, req, e)
case *github.PullRequestReviewCommentEvent:
r.serveReviewCommentEvent(w, req, e)
default:
// Not an event this receiver decodes (ping, push, etc.).
// Acknowledge and ignore.
w.WriteHeader(http.StatusAccepted)
return
}
}
// serveIssueEvent is the receiver's original contract: an eligible issue
// event becomes a task envelope on the task path.
func (r *Receiver) serveIssueEvent(w http.ResponseWriter, req *http.Request, issueEvent *github.IssuesEvent) {
task, ok := r.taskFromEvent(issueEvent)
if !ok {
// Delivered but not eligible work (PR, closed, unrelated action,
@@ -203,6 +251,103 @@ func (r *Receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusAccepted)
}
// serveReviewEvent turns a submitted review into a reaction, the webhook
// half of decision 2: the same typed reaction the poller produces, so
// PublishUnique dedups the two sources. Only "submitted" carries a verdict
// or summary to remediate; edited and dismissed restate or withdraw one.
func (r *Receiver) serveReviewEvent(w http.ResponseWriter, req *http.Request, e *github.PullRequestReviewEvent) {
if e.GetAction() != "submitted" || e.GetReview() == nil {
w.WriteHeader(http.StatusAccepted)
return
}
if !r.allowReactionDelivery(req.RemoteAddr) {
r.log.Warn("reaction rate limit exceeded", "remote", req.RemoteAddr)
http.Error(w, "rate limited", http.StatusTooManyRequests)
return
}
if r.reactionPublish == nil {
w.WriteHeader(http.StatusAccepted)
return
}
review := e.GetReview()
reaction := workintake.ReviewCommentEnvelope{
Owner: e.GetRepo().GetOwner().GetLogin(),
Repo: e.GetRepo().GetName(),
PRNumber: e.GetPullRequest().GetNumber(),
Kind: workintake.ReviewReactionReview,
ReviewID: review.GetID(),
Author: review.GetUser().GetLogin(),
State: review.GetState(),
Body: review.GetBody(),
}
r.deliverReaction(w, req, reaction)
}
// serveReviewCommentEvent publishes an inline comment as a reaction. The
// comment carries its parent review's ID, so the consumer can collect it
// into that review's unit (decision 5) rather than starting a round of its
// own.
func (r *Receiver) serveReviewCommentEvent(w http.ResponseWriter, req *http.Request, e *github.PullRequestReviewCommentEvent) {
if e.GetAction() != "created" || e.GetComment() == nil {
w.WriteHeader(http.StatusAccepted)
return
}
if !r.allowReactionDelivery(req.RemoteAddr) {
r.log.Warn("reaction rate limit exceeded", "remote", req.RemoteAddr)
http.Error(w, "rate limited", http.StatusTooManyRequests)
return
}
if r.reactionPublish == nil {
w.WriteHeader(http.StatusAccepted)
return
}
comment := e.GetComment()
reaction := workintake.ReviewCommentEnvelope{
Owner: e.GetRepo().GetOwner().GetLogin(),
Repo: e.GetRepo().GetName(),
PRNumber: e.GetPullRequest().GetNumber(),
Kind: workintake.ReviewReactionComment,
ReviewID: comment.GetPullRequestReviewID(),
CommentID: comment.GetID(),
Author: comment.GetUser().GetLogin(),
Body: comment.GetBody(),
Path: comment.GetPath(),
Line: comment.GetLine(),
}
r.deliverReaction(w, req, reaction)
}
func (r *Receiver) deliverReaction(w http.ResponseWriter, req *http.Request, reaction workintake.ReviewCommentEnvelope) {
if err := r.reactionPublish(req.Context(), reaction); err != nil {
r.log.Error("publish reaction", "key", reaction.IdempotencyKey(), "err", err)
http.Error(w, "publish failed", http.StatusInternalServerError)
return
}
r.recordReactionPublish()
w.WriteHeader(http.StatusAccepted)
}
// allowReactionDelivery consumes one reaction slot for the remote source.
// A fixed window keeps the bookkeeping trivial; the failure mode is a burst
// slightly over one window, which the consumer's dedup and round cap bound.
func (r *Receiver) allowReactionDelivery(remote string) bool {
now := time.Now()
r.mu.Lock()
defer r.mu.Unlock()
for k, v := range r.reactionLimiter {
if now.Sub(v.start) > reactionRateBucketTTL {
delete(r.reactionLimiter, k)
}
}
w, ok := r.reactionLimiter[remote]
if !ok || now.Sub(w.start) > reactionRateWindow {
r.reactionLimiter[remote] = &reactionWindow{start: now, count: 0}
w = r.reactionLimiter[remote]
}
w.count++
return w.count <= reactionRateLimit
}
// taskFromEvent decodes a GitHub issues event into a task envelope, or
// reports (zero, false) when the event is not eligible work.
func (r *Receiver) taskFromEvent(event *github.IssuesEvent) (workintake.TaskEnvelope, bool) {
+5 -5
View File
@@ -207,7 +207,7 @@ func TestReceiverPublishesMatchingIssue(t *testing.T) {
// The receiver always trusts testSecret; tc.secret is what the
// request is signed with, so a case can sign with the wrong (or no)
// secret to exercise rejection.
r := New(testSecret, tc.trigger, tc.cfgLabel, testBot, nil, nil)
r := New(testSecret, tc.trigger, tc.cfgLabel, testBot, nil, nil, nil)
rec, published := serve(t, r, signedRequest(t, tc.secret, tc.eventType, payload))
if rec.Code != tc.wantStatus {
@@ -228,7 +228,7 @@ func TestPublishedEnvelopeCarriesIssueIdentityAndKind(t *testing.T) {
if err != nil {
t.Fatalf("marshal event: %v", err)
}
r := New(testSecret, "label", testLabel, testBot, nil, nil)
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
_, published := serve(t, r, signedRequest(t, testSecret, "issues", payload))
if len(published) != 1 {
@@ -259,7 +259,7 @@ func TestPublishedEnvelopeCarriesIssueIdentityAndKind(t *testing.T) {
// the endpoint with a bad signature manufacture a false "receiver is alive
// and busy" signal.
func TestReceiverStatusTracksAuthenticatedDeliveries(t *testing.T) {
r := New(testSecret, "label", testLabel, testBot, nil, nil)
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
before := r.Status()
if before.Deliveries != 0 || before.Publishes != 0 {
@@ -327,7 +327,7 @@ func TestReceiverStatusTracksAuthenticatedDeliveries(t *testing.T) {
// payload really was dispatch-eligible) but must not count as a publish --
// otherwise Status would report work that never actually reached the queue.
func TestReceiverStatusDoesNotCountFailedPublish(t *testing.T) {
r := New(testSecret, "label", testLabel, testBot, nil, nil)
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
r.publish = func(context.Context, workintake.TaskEnvelope) error {
return errors.New("publish unavailable")
}
@@ -358,7 +358,7 @@ func TestReceiverStatusDoesNotCountFailedPublish(t *testing.T) {
// separate health-check subsystem: any GET is answered with the JSON status
// body, since GitHub only ever POSTs to this receiver.
func TestReceiverServesStatusOnGET(t *testing.T) {
r := New(testSecret, "label", testLabel, testBot, nil, nil)
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
ev := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
})
@@ -111,6 +111,11 @@ func (c *Client) Requeue(ctx context.Context, taskID int64, fromStatus, wf strin
return unmapError(err)
}
func (c *Client) ParkTask(ctx context.Context, taskID int64, from, detail, class string) error {
_, err := c.client.ParkTask(ctx, &pb.ParkTaskRequest{TaskId: taskID, From: from, Detail: detail, Class: class})
return unmapError(err)
}
func (c *Client) RecoverStale(ctx context.Context) (int64, error) {
r, err := c.client.RecoverStale(ctx, &pb.RecoverStaleRequest{})
if err != nil {
@@ -134,6 +139,21 @@ func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf str
return unmapError(err)
}
func (c *Client) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
_, err := c.client.BeginRemediation(ctx, &pb.BeginRemediationRequest{TaskId: taskID, Payload: payload})
return unmapError(err)
}
func (c *Client) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
_, err := c.client.UpdateReviewPayload(ctx, &pb.UpdateReviewPayloadRequest{TaskId: taskID, Payload: payload})
return unmapError(err)
}
func (c *Client) SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error {
_, err := c.client.SetReviewCursors(ctx, &pb.SetReviewCursorsRequest{TaskId: taskID, ReviewCursor: reviewCursor, CommentCursor: commentCursor})
return unmapError(err)
}
// Queries
func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) {
@@ -172,6 +172,35 @@ func TestStateStoreConformance(t *testing.T) {
t.Fatalf("Transition stale = %v, want ErrStaleTransition", err)
}
// Remediation starter: the guarded transition carries the review
// unit, and both guards are the wire contract (the sentinel must
// survive the hop for the reaction consumer's dedup to work).
if err := c.Transition(ctx, task.ID, "running", "pr_open", "PR opened"); err != nil {
t.Fatalf("Transition to pr_open: %v", err)
}
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); err != nil {
t.Fatalf("BeginRemediation: %v", err)
}
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); !errors.Is(err, store.ErrStaleTransition) {
t.Fatalf("BeginRemediation stale = %v, want ErrStaleTransition", err)
}
remediated, err := c.TaskByID(ctx, task.ID)
if err != nil || remediated == nil {
t.Fatalf("TaskByID after BeginRemediation: %+v %v", remediated, err)
}
if remediated.Status != "queued" || remediated.Workflow != "remediate" || remediated.ReviewPayload != `{"review_id":7}` {
t.Fatalf("BeginRemediation row = status:%q workflow:%q payload:%q", remediated.Status, remediated.Workflow, remediated.ReviewPayload)
}
if err := c.UpdateReviewPayload(ctx, task.ID, `{"review_id":7,"comments":[{"comment_id":9}]}`); err != nil {
t.Fatalf("UpdateReviewPayload: %v", err)
}
if err := c.Transition(ctx, task.ID, "queued", "running", "claimed"); err != nil {
t.Fatalf("claim: %v", err)
}
if err := c.UpdateReviewPayload(ctx, task.ID, `{}`); !errors.Is(err, store.ErrStaleTransition) {
t.Fatalf("UpdateReviewPayload stale = %v, want ErrStaleTransition", err)
}
// TaskQueries: found=false is not an error.
missing, err := c.TaskByID(ctx, task.ID+999999)
if err != nil || missing != nil {
@@ -262,6 +291,46 @@ func TestStateStoreConformance(t *testing.T) {
if _, err := c.RecoverStale(ctx); err != nil {
t.Fatalf("RecoverStale: %v", err)
}
// Classified park: the guarded transition carries the park class,
// and both guards are the wire contract (the stale sentinel must
// survive the hop for the daemon's park-with-retry loop to detect
// a concurrent terminal write).
if err := c.Transition(ctx, claimed.ID, "queued", "running", "claimed"); err != nil {
t.Fatalf("re-claim for ParkTask: %v", err)
}
if err := c.ParkTask(ctx, claimed.ID, "running", "container pool unavailable", "transient"); err != nil {
t.Fatalf("ParkTask: %v", err)
}
parked, err := c.TaskByID(ctx, claimed.ID)
if err != nil || parked == nil {
t.Fatalf("TaskByID after ParkTask: %+v %v", parked, err)
}
if parked.Status != "parked" || parked.ParkClass != "transient" || parked.ParkReason != "container pool unavailable" {
t.Fatalf("ParkTask row = status:%q class:%q reason:%q", parked.Status, parked.ParkClass, parked.ParkReason)
}
if err := c.ParkTask(ctx, claimed.ID, "running", "late park", "transient"); !errors.Is(err, store.ErrStaleTransition) {
t.Fatalf("ParkTask stale = %v, want ErrStaleTransition", err)
}
// An unclassified park normalizes to needs_human store-side rather
// than failing: a caller that predates the class vocabulary must
// not be unable to park.
if err := c.Requeue(ctx, claimed.ID, "parked", ""); err != nil {
t.Fatalf("Requeue after park: %v", err)
}
if err := c.Transition(ctx, claimed.ID, "queued", "running", "claimed"); err != nil {
t.Fatalf("re-claim 2: %v", err)
}
if err := c.ParkTask(ctx, claimed.ID, "running", "unclassified park", ""); err != nil {
t.Fatalf("ParkTask unclassified: %v", err)
}
parked2, err := c.TaskByID(ctx, claimed.ID)
if err != nil || parked2 == nil {
t.Fatalf("TaskByID after unclassified park: %+v %v", parked2, err)
}
if parked2.ParkClass != "needs_human" {
t.Fatalf("unclassified park class = %q, want needs_human", parked2.ParkClass)
}
byClaim, err := c.ClaimByIssue(ctx, "acme", "widget", 999999)
if err != nil || byClaim != nil {
t.Fatalf("ClaimByIssue missing: %+v %v", byClaim, err)
@@ -177,6 +177,13 @@ func (s *server) Requeue(ctx context.Context, r *pb.RequeueRequest) (*pb.Requeue
return &pb.RequeueResponse{}, nil
}
func (s *server) ParkTask(ctx context.Context, r *pb.ParkTaskRequest) (*pb.ParkTaskResponse, error) {
if err := s.deps.Tasks.ParkTask(ctx, r.TaskId, r.From, r.Detail, r.Class); err != nil {
return nil, s.logErr("ParkTask", err)
}
return &pb.ParkTaskResponse{}, nil
}
func (s *server) RecoverStale(ctx context.Context, _ *pb.RecoverStaleRequest) (*pb.RecoverStaleResponse, error) {
n, err := s.deps.Tasks.RecoverStale(ctx)
if err != nil {
@@ -202,6 +209,27 @@ func (s *server) RetryTask(ctx context.Context, r *pb.RetryTaskRequest) (*pb.Ret
return &pb.RetryTaskResponse{}, nil
}
func (s *server) BeginRemediation(ctx context.Context, r *pb.BeginRemediationRequest) (*pb.BeginRemediationResponse, error) {
if err := s.deps.Tasks.BeginRemediation(ctx, r.TaskId, r.Payload); err != nil {
return nil, s.logErr("BeginRemediation", err)
}
return &pb.BeginRemediationResponse{}, nil
}
func (s *server) UpdateReviewPayload(ctx context.Context, r *pb.UpdateReviewPayloadRequest) (*pb.UpdateReviewPayloadResponse, error) {
if err := s.deps.Tasks.UpdateReviewPayload(ctx, r.TaskId, r.Payload); err != nil {
return nil, s.logErr("UpdateReviewPayload", err)
}
return &pb.UpdateReviewPayloadResponse{}, nil
}
func (s *server) SetReviewCursors(ctx context.Context, r *pb.SetReviewCursorsRequest) (*pb.SetReviewCursorsResponse, error) {
if err := s.deps.Tasks.SetReviewCursors(ctx, r.TaskId, r.ReviewCursor, r.CommentCursor); err != nil {
return nil, s.logErr("SetReviewCursors", err)
}
return &pb.SetReviewCursorsResponse{}, nil
}
// Queries
func (s *server) TaskByIssue(ctx context.Context, r *pb.TaskByIssueRequest) (*pb.TaskByIssueResponse, error) {
@@ -68,6 +68,9 @@ func taskProto(t *task.Task) *pb.Task { //nolint:dupl // mirror-image field-by-f
BindingId: t.BindingID, BindingVersion: int64(t.BindingVersion),
CreatedAt: timestamp(t.CreatedAt), UpdatedAt: timestamp(t.UpdatedAt),
ReviewPayload: t.ReviewPayload,
ReviewCursor: t.ReviewCursor,
ParkClass: t.ParkClass,
RemediationRounds: int32(t.RemediationRounds),
WorkflowDefinitionVersion: t.WorkflowDefinitionVersion,
WorkflowDefinitionDigest: t.WorkflowDefinitionDigest,
WorkflowDefinitionYaml: t.WorkflowDefinitionYAML,
@@ -88,6 +91,9 @@ func taskValue(t *pb.Task) *task.Task { //nolint:dupl // see taskProto above
BindingID: t.BindingId, BindingVersion: int(t.BindingVersion),
CreatedAt: timeValue(t.CreatedAt), UpdatedAt: timeValue(t.UpdatedAt),
ReviewPayload: t.ReviewPayload,
ReviewCursor: t.ReviewCursor,
ParkClass: t.ParkClass,
RemediationRounds: int(t.RemediationRounds),
WorkflowDefinitionVersion: t.WorkflowDefinitionVersion,
WorkflowDefinitionDigest: t.WorkflowDefinitionDigest,
WorkflowDefinitionYAML: t.WorkflowDefinitionYaml,
+76 -2
View File
@@ -4,6 +4,7 @@ import (
"bufio"
"database/sql"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"os"
@@ -574,7 +575,11 @@ func writeFakeCommand(t *testing.T, dir, name, body string) {
type watchdogRun struct {
components string
curl string
env map[string]string
// systemctl replaces the fake systemctl on PATH, so a case can observe or
// condition what the watchdog does between units. Empty keeps the inert
// `exit 0` stub.
systemctl string
env map[string]string
}
func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, []string) {
@@ -610,7 +615,11 @@ func runUpdateWatchdog(t *testing.T, run watchdogRun) (Report, string, []string)
t.Fatal(err)
}
}
writeFakeCommand(t, fakeDir, "systemctl", `exit 0`)
systemctl := run.systemctl
if systemctl == "" {
systemctl = `exit 0`
}
writeFakeCommand(t, fakeDir, "systemctl", systemctl)
if run.curl != "" {
writeFakeCommand(t, fakeDir, "curl", run.curl)
}
@@ -985,3 +994,68 @@ func TestUpdateInstallWritesABareAgentVersionSidecar(t *testing.T) {
t.Fatalf("sidecar = %q, want %q", recorded, "1.10.0\n")
}
}
// freeAddress reserves a loopback address nothing is listening on and releases
// it, so a case can hand the watchdog a State Store target whose port stays
// closed until the fake State Store binds it.
func freeAddress(t *testing.T) string {
t.Helper()
var listen net.ListenConfig
listener, err := listen.Listen(t.Context(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
address := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
return address
}
// TestUpdateWatchdogWaitsForTheStateStoreBeforeStartingArchied pins why an
// ordered start is not enough on its own.
//
// `systemctl --user start` returns once the process is forked, not once its port
// accepts. On a real 1.37.1 -> 1.38.0 update the State Store's unit reported
// started while it was still binding, archied started next, dialled a closed
// port, exited 1, and was rescued only by systemd's Restart=on-failure seven
// seconds later -- behind a "build and install succeeded" line, on a unit that
// need not carry that restart policy at all.
//
// The fake State Store binds its port two seconds AFTER systemctl returns, which
// is the race. The fake systemctl for archied records whether the port was open
// at the moment it was asked to start, so a watchdog that starts archied without
// waiting says so in the call log rather than passing quietly.
func TestUpdateWatchdogWaitsForTheStateStoreBeforeStartingArchied(t *testing.T) {
target := freeAddress(t)
_, _, calls := runUpdateWatchdog(t, watchdogRun{
components: "daemon",
curl: `exit 1`,
systemctl: `
printf '%s\n' "systemctl $*" >> "$ARCHIE_TEST_CALLS"
case "$*" in
*"restart archie-state-store.service")
# Bind two seconds late, then hold the port: the State Store's unit returning
# before its listener exists is the whole failure being guarded against.
( sleep 2; exec python3 -c "import os,socket,time; h,p=os.environ['ARCHIE_UPDATE_STATE_STORE_TARGET'].rsplit(':',1); s=socket.socket(); s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1); s.bind((h,int(p))); s.listen(8); time.sleep(30)" ) >/dev/null 2>&1 &
;;
*"restart archied.service")
if ! (exec 3<>"/dev/tcp/${ARCHIE_UPDATE_STATE_STORE_TARGET%:*}/${ARCHIE_UPDATE_STATE_STORE_TARGET##*:}") 2>/dev/null; then
printf '%s\n' 'archied started before the state store accepted' >> "$ARCHIE_TEST_CALLS"
fi
;;
esac
exit 0`,
env: map[string]string{
"ARCHIE_UPDATE_HEALTH_TIMEOUT": "0",
"ARCHIE_UPDATE_UNITS": "archie-state-store archie-gateway archied",
"ARCHIE_UPDATE_STATE_STORE_TARGET": target,
"ARCHIE_UPDATE_STATE_STORE_TIMEOUT": "15",
},
})
assertCallContains(t, calls, "restart archie-state-store.service")
assertCallContains(t, calls, "restart archie-gateway.service")
assertCallContains(t, calls, "restart archied.service")
assertCallAbsent(t, calls, "archied started before the state store accepted")
}
+220
View File
@@ -0,0 +1,220 @@
package store
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// prOpenTask inserts a task and walks it to the state a reaction resolves
// against: the task opened its PR and is idle waiting for review.
func prOpenTask(t *testing.T, s *Store, owner, repo string, prNumber int) int64 {
t.Helper()
ok, err := s.EnqueueIssue(t.Context(), owner, repo, 1, "title", "body", "", "")
if err != nil {
t.Fatal(err)
}
if !ok {
t.Fatal("enqueue: task already tracked")
}
task, err := s.TaskByIssue(t.Context(), owner, repo, 1)
if err != nil || task == nil {
t.Fatalf("TaskByIssue = (%v, %v)", task, err)
}
task.PRNumber = prNumber
task.Status = workflow.StatusPROpen
if err := s.Transition(t.Context(), task.ID, workflow.StatusQueued, workflow.StatusPROpen, "PR opened"); err != nil {
t.Fatal(err)
}
if err := s.Update(t.Context(), task); err != nil {
t.Fatal(err)
}
return task.ID
}
func TestBeginRemediationMovesAnOpenPRTaskToQueuedRemediate(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); err != nil {
t.Fatalf("BeginRemediation: %v", err)
}
got, err := s.TaskByID(t.Context(), id)
if err != nil {
t.Fatal(err)
}
if got.Status != workflow.StatusQueued {
t.Errorf("status = %q, want queued", got.Status)
}
if got.Workflow != "remediate" {
t.Errorf("workflow = %q, want remediate", got.Workflow)
}
if got.ReviewPayload != `{"review_id":7}` {
t.Errorf("review_payload = %q, want the carried unit", got.ReviewPayload)
}
if got.ParkReason != "" || got.Stage != "" {
t.Errorf("park_reason/stage = %q/%q, want both empty", got.ParkReason, got.Stage)
}
}
func TestBeginRemediationRefusesAnAlreadyClaimedTask(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); err != nil {
t.Fatal(err)
}
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); !errors.Is(err, ErrStaleTransition) {
t.Errorf("second BeginRemediation err = %v, want ErrStaleTransition", err)
}
}
func TestBeginRemediationRefusesNonOpenPRStatuses(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.Transition(t.Context(), id, workflow.StatusPROpen, workflow.StatusParked, "gate failed"); err != nil {
t.Fatal(err)
}
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); !errors.Is(err, ErrStaleTransition) {
t.Errorf("BeginRemediation on parked err = %v, want ErrStaleTransition", err)
}
}
func TestUpdateReviewPayloadAppendsOnlyWhileARemediationIsQueued(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.BeginRemediation(t.Context(), id, `{"review_id":7}`); err != nil {
t.Fatal(err)
}
if err := s.UpdateReviewPayload(t.Context(), id, `{"review_id":7,"comments":[{"comment_id":9}]}`); err != nil {
t.Fatalf("UpdateReviewPayload while queued: %v", err)
}
got, err := s.TaskByID(t.Context(), id)
if err != nil {
t.Fatal(err)
}
if got.ReviewPayload != `{"review_id":7,"comments":[{"comment_id":9}]}` {
t.Errorf("review_payload = %q, want the appended unit", got.ReviewPayload)
}
// Claim the task: the remediation is running, and a payload written under
// it would race the builder's input.
if _, err := s.ClaimNext(t.Context()); err != nil {
t.Fatal(err)
}
if err := s.UpdateReviewPayload(t.Context(), id, `{"review_id":7,"comments":[{"comment_id":10}]}`); !errors.Is(err, ErrStaleTransition) {
t.Errorf("UpdateReviewPayload while running err = %v, want ErrStaleTransition", err)
}
}
// TestParkTaskWritesItsClassification pins the classified park write: the
// class is recorded at the park site in the same guarded write, and an
// unclassified park defaults to needs_human.
func TestParkTaskWritesItsClassification(t *testing.T) {
s := openTest(t)
ctx := t.Context()
if _, err := s.EnqueueIssue(ctx, "acme", "widgets", 1, "t", "b", "", ""); err != nil {
t.Fatal(err)
}
task, _ := s.TaskByIssue(ctx, "acme", "widgets", 1)
if _, err := s.ClaimNext(ctx); err != nil {
t.Fatal(err)
}
if err := s.ParkTask(ctx, task.ID, workflow.StatusRunning, "container acquire failed", "transient"); err != nil {
t.Fatalf("ParkTask: %v", err)
}
got, err := s.TaskByID(ctx, task.ID)
if err != nil {
t.Fatal(err)
}
if got.Status != workflow.StatusParked || got.ParkReason != "container acquire failed" {
t.Errorf("park row = status:%q reason:%q", got.Status, got.ParkReason)
}
if got.ParkClass != "transient" {
t.Errorf("park_class = %q, want transient", got.ParkClass)
}
// Requeue clears the class with the reason: a stale class on a queued
// task would group a live task with parked ones.
if err := s.Requeue(ctx, task.ID, workflow.StatusParked, ""); err != nil {
t.Fatal(err)
}
got, _ = s.TaskByID(ctx, task.ID)
if got.ParkClass != "needs_human" || got.ParkReason != "" {
t.Errorf("after requeue: class=%q reason=%q, want cleared", got.ParkClass, got.ParkReason)
}
}
func TestParkTaskRejectsAnUnknownClass(t *testing.T) {
s := openTest(t)
ctx := t.Context()
if _, err := s.EnqueueIssue(ctx, "acme", "widgets", 1, "t", "b", "", ""); err != nil {
t.Fatal(err)
}
task, _ := s.TaskByIssue(ctx, "acme", "widgets", 1)
if _, err := s.ClaimNext(ctx); err != nil {
t.Fatal(err)
}
// An unknown class normalizes to needs_human rather than persisting a
// value no consumer knows how to group.
if err := s.ParkTask(ctx, task.ID, workflow.StatusRunning, "x", "urgent"); err != nil {
t.Fatal(err)
}
got, _ := s.TaskByID(ctx, task.ID)
if got.ParkClass != "needs_human" {
t.Errorf("park_class = %q, want the needs_human fallback", got.ParkClass)
}
}
func TestParkTaskStaleGuard(t *testing.T) {
s := openTest(t)
ctx := t.Context()
if _, err := s.EnqueueIssue(ctx, "acme", "widgets", 1, "t", "b", "", ""); err != nil {
t.Fatal(err)
}
task, _ := s.TaskByIssue(ctx, "acme", "widgets", 1)
// Still queued, not running: the from guard must refuse.
if err := s.ParkTask(ctx, task.ID, workflow.StatusRunning, "x", "transient"); !errors.Is(err, ErrStaleTransition) {
t.Errorf("ParkTask stale err = %v, want ErrStaleTransition", err)
}
}
func TestTransitionToParkedDefaultsTheClass(t *testing.T) {
s := openTest(t)
ctx := t.Context()
if _, err := s.EnqueueIssue(ctx, "acme", "widgets", 1, "t", "b", "", ""); err != nil {
t.Fatal(err)
}
task, _ := s.TaskByIssue(ctx, "acme", "widgets", 1)
if _, err := s.ClaimNext(ctx); err != nil {
t.Fatal(err)
}
// The generic transition is the workflow engine's park path: every
// unclassified park reads as operator-actionable.
if err := s.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusParked, "gate failed"); err != nil {
t.Fatal(err)
}
got, _ := s.TaskByID(ctx, task.ID)
if got.ParkClass != "needs_human" {
t.Errorf("park_class = %q, want the needs_human default", got.ParkClass)
}
}
func TestUpdateCarriesRemediationRounds(t *testing.T) {
s := openTest(t)
ctx := t.Context()
if _, err := s.EnqueueIssue(ctx, "acme", "widgets", 1, "t", "b", "", ""); err != nil {
t.Fatal(err)
}
task, _ := s.TaskByIssue(ctx, "acme", "widgets", 1)
task.RemediationRounds = 2
if err := s.Update(ctx, task); err != nil {
t.Fatal(err)
}
got, _ := s.TaskByID(ctx, task.ID)
if got.RemediationRounds != 2 {
t.Errorf("remediation_rounds = %d, want 2", got.RemediationRounds)
}
}
+45
View File
@@ -0,0 +1,45 @@
package store
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// TestOpenPRsCarriesReviewCursors pins the poll backstop's read side: the
// per-PR scan reads each task's persisted review and comment cursors, so a
// daemon restart resumes where the last scan stopped instead of re-listing
// every review the forge has ever returned.
func TestOpenPRsCarriesReviewCursors(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.SetReviewCursors(t.Context(), id, 100, 200); err != nil {
t.Fatalf("SetReviewCursors: %v", err)
}
tasks, err := s.OpenPRs(t.Context())
if err != nil || len(tasks) != 1 {
t.Fatalf("OpenPRs = (%d tasks, %v), want 1", len(tasks), err)
}
if tasks[0].ReviewCursor != 100 {
t.Errorf("ReviewCursor = %d, want 100", tasks[0].ReviewCursor)
}
if tasks[0].WatchCommentID != 200 {
t.Errorf("WatchCommentID = %d, want 200 (the review-comment cursor)", tasks[0].WatchCommentID)
}
}
// TestSetReviewCursorsGuardsOnStatus pins the write side: cursors only move
// while the task is idle in pr_open. A cursor written under a running or
// parked task would desync from what its remediation run has consumed.
func TestSetReviewCursorsRefusesNonOpenPRStatuses(t *testing.T) {
s := openTest(t)
id := prOpenTask(t, s, "acme", "widgets", 42)
if err := s.Transition(t.Context(), id, workflow.StatusPROpen, workflow.StatusParked, "gate failed"); err != nil {
t.Fatal(err)
}
if err := s.SetReviewCursors(t.Context(), id, 5, 6); !errors.Is(err, ErrStaleTransition) {
t.Errorf("SetReviewCursors on parked err = %v, want ErrStaleTransition", err)
}
}
+146 -13
View File
@@ -18,6 +18,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
type Store struct {
@@ -101,6 +102,9 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
sql string
}{
{"tasks", "watch_comment_id", `ALTER TABLE tasks ADD COLUMN watch_comment_id INTEGER NOT NULL DEFAULT 0`},
{"tasks", "review_cursor", `ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0`},
{"tasks", "park_class", `ALTER TABLE tasks ADD COLUMN park_class TEXT NOT NULL DEFAULT 'needs_human'`},
{"tasks", "remediation_rounds", `ALTER TABLE tasks ADD COLUMN remediation_rounds INTEGER NOT NULL DEFAULT 0`},
{"tasks", "retry_count", `ALTER TABLE tasks ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0`},
{"tasks", "source", `ALTER TABLE tasks ADD COLUMN source TEXT NOT NULL DEFAULT 'forge'`},
{"tasks", "identity", `ALTER TABLE tasks ADD COLUMN identity TEXT NOT NULL DEFAULT ''`},
@@ -294,6 +298,8 @@ CREATE TABLE IF NOT EXISTS tasks (
attempt INTEGER NOT NULL DEFAULT 0,
park_reason TEXT NOT NULL DEFAULT '',
watch_comment_id INTEGER NOT NULL DEFAULT 0,
park_class TEXT NOT NULL DEFAULT 'needs_human',
remediation_rounds INTEGER NOT NULL DEFAULT 0,
retry_count INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT 'forge',
identity TEXT NOT NULL DEFAULT '',
@@ -380,7 +386,7 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at`,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, park_class, remediation_rounds, created_at, updated_at`,
owner, repo, owner, repo, syntheticIssueNumberBase-1, title, body, wf, identity)
return scanTask(row)
}
@@ -422,7 +428,7 @@ func (s *Store) ClaimNext(ctx context.Context) (*workflow.Task, error) {
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at`,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, park_class, remediation_rounds, created_at, updated_at`,
workflow.StatusRunning, workflow.StatusQueued)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
@@ -439,6 +445,7 @@ func scanTask(row *sql.Row) (*workflow.Task, error) {
&t.WatchCommentID, &t.RetryCount, &t.Source, &t.Identity,
&t.BindingID, &t.BindingVersion, &t.ReviewPayload,
&t.WorkflowDefinitionVersion, &t.WorkflowDefinitionDigest, &t.WorkflowDefinitionYAML,
&t.ParkClass, &t.RemediationRounds,
sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt})
if err != nil {
return nil, err
@@ -458,7 +465,7 @@ func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at`,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, park_class, remediation_rounds, created_at, updated_at`,
workflow.StatusRunning, owner, repo, number, workflow.StatusQueued)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
@@ -487,9 +494,11 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
UPDATE tasks
SET status=?,
park_reason=CASE WHEN ?=? THEN ? ELSE park_reason END,
park_class=CASE WHEN ?=? THEN ? ELSE park_class END,
updated_at=datetime('now')
WHERE id=? AND status=?`,
to, to, workflow.StatusParked, clip(detail, 4000), taskID, from)
to, to, workflow.StatusParked, clip(detail, 4000),
to, to, taskstate.ParkNeedsHuman, taskID, from)
if err != nil {
return err
}
@@ -511,21 +520,143 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
return tx.Commit()
}
// ParkTask is the classified park write: the same guarded running->parked
// transition Transition performs, carrying the park class the site chose.
// The class is normalized here so an unknown value persists as needs_human
// -- the safe misread is "an operator should look at this".
func (s *Store) ParkTask(ctx context.Context, taskID int64, from, detail, class string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
UPDATE tasks
SET status=?,
park_reason=?,
park_class=?,
updated_at=datetime('now')
WHERE id=? AND status=?`,
workflow.StatusParked, clip(detail, 4000),
taskstate.NormalizeParkClass(class), taskID, from)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`,
taskID, from, workflow.StatusParked, clip(detail, 4000)); err != nil {
return err
}
return tx.Commit()
}
// Update persists mutable task fields written by workflows.
func (s *Store) Update(ctx context.Context, t *workflow.Task) error {
_, err := s.db.ExecContext(ctx, `
UPDATE tasks SET workflow=?, stage=?, branch=?, plan=?, notes=?,
pr_number=?, tokens_used=?, iterations=?, park_reason=?,
watch_comment_id=?, retry_count=?, review_payload=?, workflow_definition_version=?,
watch_comment_id=?, retry_count=?, remediation_rounds=?, review_payload=?, workflow_definition_version=?,
workflow_definition_digest=?, workflow_definition_yaml=?, updated_at=datetime('now')
WHERE id=?`,
t.Workflow, t.Stage, t.Branch, t.Plan, t.Notes,
t.PRNumber, t.TokensUsed, t.Iterations, clip(t.ParkReason, 4000),
t.WatchCommentID, t.RetryCount, t.ReviewPayload, t.WorkflowDefinitionVersion,
t.WatchCommentID, t.RetryCount, t.RemediationRounds, t.ReviewPayload, t.WorkflowDefinitionVersion,
t.WorkflowDefinitionDigest, t.WorkflowDefinitionYAML, t.ID)
return err
}
// BeginRemediation transitions an Archie-owned open-PR task into a queued
// remediate run carrying the JSON-encoded review unit. The guarded update is
// the reaction consumer's dedup: a re-delivered reaction, or a second
// consumer racing the first, fails the status guard instead of starting a
// second round. The unit is written in the same transaction, so a task can
// never be claimed into a remediate run whose payload has not landed.
func (s *Store) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
UPDATE tasks SET status=?, workflow=?, stage='', park_reason='', park_class='needs_human', review_payload=?,
updated_at=datetime('now')
WHERE id=? AND status=?`, workflow.StatusQueued, "remediate", clip(payload, 4000), taskID, workflow.StatusPROpen)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`,
taskID, workflow.StatusPROpen, workflow.StatusQueued, "review reaction queued remediation"); err != nil {
return err
}
return tx.Commit()
}
// UpdateReviewPayload replaces a queued remediation's review unit: the
// reaction consumer appends late-arriving comments of the same review while
// the unit is still pending. The guarded update is the boundary — once a
// run is claimed, its input is frozen; a late comment is dropped by the
// caller rather than racing the builder's mission.
func (s *Store) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
res, err := s.db.ExecContext(ctx, `
UPDATE tasks SET review_payload=?, updated_at=datetime('now')
WHERE id=? AND status=? AND workflow=?`,
clip(payload, 4000), taskID, workflow.StatusQueued, "remediate")
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
return nil
}
// SetReviewCursors persists the poll backstop's per-task high-water marks.
// The pr_open guard keeps a cursor from moving while a remediation run owns
// the task: the run's next round re-reads the cursors the scan wrote, and a
// write under a running task would desync them from what was consumed.
func (s *Store) SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error {
res, err := s.db.ExecContext(ctx, `
UPDATE tasks SET review_cursor=?, watch_comment_id=?, updated_at=datetime('now')
WHERE id=? AND status=?`,
reviewCursor, commentCursor, taskID, workflow.StatusPROpen)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
return nil
}
// TaskByIssue returns the task tracking an issue, or nil.
func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
@@ -533,7 +664,7 @@ func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int)
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, park_class, remediation_rounds, created_at, updated_at
FROM tasks WHERE owner=? AND repo=? AND issue_number=?`, owner, repo, number)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
@@ -549,7 +680,7 @@ func (s *Store) OpenTaskByPR(ctx context.Context, owner, repo string, number int
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, park_class, remediation_rounds, created_at, updated_at
FROM tasks
WHERE owner=? AND repo=? AND pr_number=? AND status=?`,
owner, repo, number, workflow.StatusPROpen)
@@ -569,7 +700,7 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, err
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, park_class, remediation_rounds, created_at, updated_at
FROM tasks WHERE id=?`, taskID)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
@@ -595,7 +726,7 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, wf string
res, err := tx.ExecContext(ctx, `
UPDATE tasks SET status=?,
workflow=CASE WHEN ?='' THEN workflow ELSE ? END,
stage='', park_reason='', updated_at=datetime('now')
stage='', park_reason='', park_class='needs_human', updated_at=datetime('now')
WHERE id=? AND status=?`, workflow.StatusQueued, wf, wf, taskID, fromStatus)
if err != nil {
return err
@@ -631,7 +762,7 @@ func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf stri
res, err := tx.ExecContext(ctx, `
UPDATE tasks SET status=?, retry_count=retry_count+1,
workflow=CASE WHEN ?='' THEN workflow ELSE ? END,
stage='', park_reason='', updated_at=datetime('now')
stage='', park_reason='', park_class='needs_human', updated_at=datetime('now')
WHERE id=? AND status=?`, workflow.StatusQueued, wf, wf, taskID, fromStatus)
if err != nil {
return err
@@ -707,7 +838,8 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
// Narrowing this projection back silently sends those events out unattributed.
func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt,
review_cursor, watch_comment_id
FROM tasks WHERE status=?`, workflow.StatusPROpen)
if err != nil {
return nil, err
@@ -718,7 +850,8 @@ func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr erro
for rows.Next() {
var t workflow.Task
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.PRNumber,
&t.Status, &t.Source, &t.Identity, &t.Attempt); err != nil {
&t.Status, &t.Source, &t.Identity, &t.Attempt,
&t.ReviewCursor, &t.WatchCommentID); err != nil {
return nil, err
}
tasks = append(tasks, t)
+1 -1
View File
@@ -105,7 +105,7 @@ func TestOpenMigratesUnversionedTaskSchemas(t *testing.T) {
if err := rows.Err(); err != nil {
t.Fatal(err)
}
for _, name := range []string{"watch_comment_id", "retry_count", "source", "identity"} {
for _, name := range []string{"watch_comment_id", "retry_count", "source", "identity", "review_cursor"} {
if !got[name] {
t.Errorf("column %q was not migrated", name)
}
+35
View File
@@ -194,3 +194,38 @@ func ActionCatalog() []ActionMeta {
{ID: string(ActionOpenIssue), Label: "Open issue", Kind: "link"},
}
}
// Park classes: the producer-side answer to "what kind of intervention does
// this park need?" (docs/prds/pr-review-remediation.md's F2, the typed
// classification agent-system.md:327 acknowledges the data model lacks).
// The class is recorded at the park site, where the cause is known, and is
// never inferred later from reason text. It is part of the on-disk format.
const (
// ParkNeedsHuman parks need an operator decision: gate failures,
// review verdicts, diff caps, remediation round caps. It is the
// default, so an unclassified park always reads as operator-actionable.
ParkNeedsHuman ParkClass = "needs_human"
// ParkTransient parks are environmental: storage, container pool,
// grants, transport. Nothing about the work is wrong; a requeue can
// succeed. Nothing retries them automatically yet -- the class is
// recorded so a future retry pass has a safe, queryable input.
ParkTransient ParkClass = "transient"
// ParkTerminal parks cannot be retried into success: the repo left the
// config, the owning identity retired. An operator archives these.
ParkTerminal ParkClass = "terminal"
)
// ParkClass is the persisted park classification string.
type ParkClass = string
// NormalizeParkClass maps a park class written by a producer to the value
// the store persists. Empty and unknown fall back to NeedsHuman: the safe
// misread is "an operator should look at this", never "nothing to do".
func NormalizeParkClass(class string) ParkClass {
switch class {
case ParkTransient, ParkTerminal:
return class
default:
return ParkNeedsHuman
}
}
+21
View File
@@ -153,3 +153,24 @@ func TestActionsReturnsIndependentSlices(t *testing.T) {
t.Fatalf("mutating returned actions changed lifecycle table: %v", got)
}
}
func TestNormalizeParkClass(t *testing.T) {
tests := []struct {
name string
input string
want ParkClass
}{
{name: "empty defaults to needs_human", input: "", want: ParkNeedsHuman},
{name: "a known class passes through", input: ParkTransient, want: ParkTransient},
{name: "terminal passes through", input: ParkTerminal, want: ParkTerminal},
{name: "an unknown class falls back to needs_human", input: "urgent", want: ParkNeedsHuman},
{name: "case differences are not classes", input: "TRANSIENT", want: ParkNeedsHuman},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := NormalizeParkClass(tt.input); got != tt.want {
t.Errorf("NormalizeParkClass(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}
+47
View File
@@ -36,11 +36,15 @@ service StateStoreService {
rpc Transition(TransitionRequest) returns (TransitionResponse);
rpc Update(UpdateRequest) returns (UpdateResponse);
rpc Requeue(RequeueRequest) returns (RequeueResponse);
rpc ParkTask(ParkTaskRequest) returns (ParkTaskResponse);
rpc RecoverStale(RecoverStaleRequest) returns (RecoverStaleResponse);
// Archive / Retry
rpc ArchiveTask(ArchiveTaskRequest) returns (ArchiveTaskResponse);
rpc RetryTask(RetryTaskRequest) returns (RetryTaskResponse);
rpc BeginRemediation(BeginRemediationRequest) returns (BeginRemediationResponse);
rpc UpdateReviewPayload(UpdateReviewPayloadRequest) returns (UpdateReviewPayloadResponse);
rpc SetReviewCursors(SetReviewCursorsRequest) returns (SetReviewCursorsResponse);
// Queries
rpc TaskByIssue(TaskByIssueRequest) returns (TaskByIssueResponse);
@@ -245,6 +249,22 @@ message Task {
int64 workflow_definition_version = 28;
string workflow_definition_digest = 29;
string workflow_definition_yaml = 30;
// review_cursor is the poll backstop's high-water mark over forge review
// IDs for this task. It is separate from watch_comment_id (the review-
// comment cursor) because the two forge sequences are independent; one
// combined cursor would silently skip reviews once a larger comment ID
// landed (docs/prds/pr-review-remediation.md decision 2).
int64 review_cursor = 31;
// park_class is the producer-recorded answer to "what kind of
// intervention does this park need?" (taskstate.ParkClass:
// needs_human, transient, terminal). Store-side normalization makes
// empty and unknown values needs_human, so the class is advisory on
// the wire and authoritative only as recorded at the park site.
string park_class = 32;
// remediation_rounds counts review-triggered remediation rounds
// separately from retry_count, so an operator's manual retries no
// longer draw down the review-remediation budget (and vice versa).
int32 remediation_rounds = 33;
}
// Event mirrors internal/events.Event. Data is carried as a JSON object
@@ -411,6 +431,14 @@ message RequeueRequest {
}
message RequeueResponse {}
message ParkTaskRequest {
int64 task_id = 1;
string from = 2;
string detail = 3;
string class = 4;
}
message ParkTaskResponse {}
message RecoverStaleRequest {}
message RecoverStaleResponse { int64 count = 1; }
@@ -428,6 +456,25 @@ message RetryTaskRequest {
}
message RetryTaskResponse {}
message BeginRemediationRequest {
int64 task_id = 1;
string payload = 2;
}
message BeginRemediationResponse {}
message UpdateReviewPayloadRequest {
int64 task_id = 1;
string payload = 2;
}
message UpdateReviewPayloadResponse {}
message SetReviewCursorsRequest {
int64 task_id = 1;
int64 review_cursor = 2;
int64 comment_cursor = 3;
}
message SetReviewCursorsResponse {}
message TaskByIssueRequest {
string owner = 1;
string repo = 2;
+23
View File
@@ -80,6 +80,28 @@ AGENT_VERSION_FILE="${ARCHIE_AGENT_VERSION_FILE:-$BIN_DIR/archie-agent.version}"
AGENT_VERSION_BACKUP="${ARCHIE_AGENT_VERSION_BACKUP:-$BIN_DIR/archie-agent.version.prev}"
TASK_DB_PATH="${ARCHIE_TASK_DB_PATH:-$(configured_task_db_path)}"
TASK_DB_BACKUP="${ARCHIE_TASK_DB_BACKUP:-$BIN_DIR/archie-task-db.prev.sqlite}"
# The address the daemon dials for its state, so the watchdog can wait for it to
# accept connections before it starts archied. Read with the same narrow awk as
# the task database path and for the same reason: the daemon stays the authority
# on validation, and this script deliberately understands one scalar rather than
# parsing TOML. Scoped to [services.state] so the Gateway's own target cannot be
# mistaken for it, and exact on the key so target_token is not.
configured_state_store_target() {
awk '
/^[[:space:]]*\[services\.state\][[:space:]]*$/ { inside = 1; next }
/^[[:space:]]*\[/ { inside = 0 }
inside && /^[[:space:]]*target[[:space:]]*=/ {
value = $0
sub(/^[[:space:]]*target[[:space:]]*=[[:space:]]*/, "", value)
sub(/[[:space:]]*(#.*)?$/, "", value)
if (value ~ /^".*"$/) { sub(/^"/, "", value); sub(/"$/, "", value); print value }
else if (length(value) >= 2 && substr(value, 1, 1) == sprintf("%c", 39) && substr(value, length(value), 1) == sprintf("%c", 39)) print substr(value, 2, length(value) - 2)
exit
}
' "$CONFIG_PATH" 2>/dev/null || true
}
STATE_STORE_TARGET="${ARCHIE_UPDATE_STATE_STORE_TARGET:-$(configured_state_store_target)}"
# The archied release is a set of processes, not one binary. Listed in start
# order: the State Store owns archie.db and every other process dials it, the
@@ -355,6 +377,7 @@ systemd-run --user --unit=archied-update-restart --collect --quiet \
--setenv=ARCHIE_AGENT_VERSION_PREVIOUS_EXISTS="${AGENT_VERSION_PREVIOUS_EXISTS:-0}" \
--setenv=ARCHIE_TASK_DB_PATH="$TASK_DB_PATH" \
--setenv=ARCHIE_TASK_DB_BACKUP="$TASK_DB_BACKUP" \
--setenv=ARCHIE_UPDATE_STATE_STORE_TARGET="$STATE_STORE_TARGET" \
"$BIN_DIR/archie-update-watchdog"
case "$components" in
+51 -1
View File
@@ -31,6 +31,12 @@ COMPONENTS="${ARCHIE_UPDATE_COMPONENTS:-daemon,agent}"
UNITS="${ARCHIE_UPDATE_UNITS:-archied}"
BINARIES="${ARCHIE_UPDATE_BINARIES:-archied}"
# The State Store's address, so the start order below can mean "ready" rather than
# "launched". Empty when the config names none or the installed updater predates
# passing one -- waiting is then skipped, which is the previous behaviour.
STATE_STORE_TARGET="${ARCHIE_UPDATE_STATE_STORE_TARGET:-}"
STATE_STORE_TIMEOUT_SECONDS="${ARCHIE_UPDATE_STATE_STORE_TIMEOUT:-30}"
json_escape() {
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}
@@ -95,13 +101,57 @@ manage_unit() {
systemctl --user "$action" "$unit.service" || true
}
# port_accepts reports whether host:port accepts a connection. bash's /dev/tcp
# costs no process and no dependency, and accepting is exactly the signal this
# needs: the failure it guards against is `dial tcp ...: connect: connection
# refused`, which is the port not being bound at all.
port_accepts() {
(exec 3<>"/dev/tcp/${1%:*}/${1##*:}") 2>/dev/null
}
# wait_for_state_store blocks until the State Store accepts connections, or the
# budget runs out.
#
# Ordering the units is not enough on its own: `systemctl --user start` returns
# once the process is forked, not once its port accepts. Measured on a 1.37.1 ->
# 1.38.0 update, the State Store's unit reported started while it was still
# binding, archied was started next, dialled a closed port and exited 1, and only
# systemd's Restart=on-failure brought it back seven seconds later. A host whose
# unit lacks that restart policy gets a failed update behind a healthy-looking
# "build and install succeeded" line.
#
# A timeout does NOT fail the update. If the State Store never comes up, archied
# fails closed on its own and wait_healthy rolls the release back -- waiting is an
# optimisation for the ordinary case, and losing the race must stay a slower path
# to the same place rather than a second failure mode.
wait_for_state_store() {
[ -n "$STATE_STORE_TARGET" ] || {
echo "==> no State Store target known; starting the rest without waiting for it" >&2
return 0
}
local deadline=$((SECONDS + STATE_STORE_TIMEOUT_SECONDS))
while [ "$SECONDS" -lt "$deadline" ]; do
if port_accepts "$STATE_STORE_TARGET"; then
echo "==> $STATE_STORE_TARGET accepts connections"
return 0
fi
sleep 1
done
echo "==> $STATE_STORE_TARGET did not accept connections within ${STATE_STORE_TIMEOUT_SECONDS}s; starting the rest anyway" >&2
return 0
}
# start_units brings the deployment up in dependency order: the State Store
# before anything that dials it, the Gateway before archied and the UI.
# before anything that dials it, the Gateway before archied and the UI. The order
# sequences the calls; wait_for_state_store is what makes it mean "ready".
start_units() {
local unit rc=0
for unit in $UNITS; do
echo "==> restarting $unit.service"
manage_unit restart "$unit" || rc=1
if [ "$unit" = archie-state-store ]; then
wait_for_state_store
fi
done
return $rc
}
+98 -15
View File
@@ -27,6 +27,7 @@ package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
@@ -34,6 +35,7 @@ import (
"io/fs"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
@@ -410,8 +412,100 @@ func resolveLinks(relative, body string, urls map[string]string, slugs map[strin
// readPages reads the source of every page either set carries, keyed by its path
// relative to docs/.
func readPages(sourceDir string) (map[string]string, error) {
//
// The page list comes from the commit, not from the working tree: see
// sourcePages for why that distinction is the whole of this function's contract.
func readPages(repoRoot, sourceDir string) (map[string]string, error) {
relativePaths, err := sourcePages(repoRoot, sourceDir)
if err != nil {
return nil, err
}
bodies := map[string]string{}
for _, relative := range relativePaths {
if !published(relative) {
continue
}
body, err := os.ReadFile(filepath.Join(sourceDir, relative))
if err != nil {
return nil, fmt.Errorf("read %s: %w", relative, err)
}
bodies[relative] = string(body)
}
if len(bodies) == 0 {
return nil, fmt.Errorf("no published pages under %s", docsDir)
}
return bodies, nil
}
// sourcePages lists the published candidate pages, relative to docs/, choosing
// git over a directory walk whenever git can answer.
//
// The artifacts are committed beside their sources, so each one must be derived
// from the files the commit carries. A walk also sees an UNTRACKED page -- one no
// commit holds -- and then reported the artifact as stale, which sent the reader
// to regenerate an artifact that was already correct and would have committed a
// page belonging to no commit. That happened twice in one session, once to a
// migration branch and once to an unrelated writer staging a new PRD.
//
// The index counts as well as HEAD, deliberately: a page staged for this commit
// is about to be carried by it, so the artifact must include it and check must
// fail until it does. Only a file in neither tree is ignored -- and that is
// exactly the working-tree scratch this exists to exclude.
//
// Outside a git work tree there is no commit to disagree with, so the walk is
// the best answer available and is used unchanged, with a line saying so rather
// than a silence that reads as the stronger guarantee.
func sourcePages(repoRoot, sourceDir string) ([]string, error) {
pages, err := trackedPages(repoRoot, sourceDir)
if err == nil {
return pages, nil
}
fmt.Fprintf(os.Stderr, "docsite: %v; falling back to a directory walk, which cannot tell an untracked page from a committed one\n", err)
return walkedPages(sourceDir)
}
// trackedPages asks git for the .md files under docs/ that the index or HEAD
// carries.
func trackedPages(repoRoot, sourceDir string) ([]string, error) {
rel, err := filepath.Rel(repoRoot, sourceDir)
if err != nil {
return nil, fmt.Errorf("locate %s under %s: %w", docsDir, repoRoot, err)
}
rel = filepath.ToSlash(rel)
// -z because a path may contain anything but NUL; --cached so a page staged
// for this commit counts.
//
// A background context, deliberately rather than by omission: docsite is a
// short-lived CLI whose whole job is one synchronous git call, so there is no
// cancellation to propagate -- threading a context through load, write and
// check would add eight signatures to serve a rule whose subject is a request
// that can be abandoned. If docsite ever grows a long operation, the context
// becomes real and belongs in its signature.
out, err := exec.CommandContext(context.Background(), "git", "-C", repoRoot, "ls-files", "--cached", "-z", "--", rel).Output()
if err != nil {
return nil, fmt.Errorf("git ls-files %s: %w", rel, err)
}
var pages []string
for _, entry := range strings.Split(string(out), "\x00") {
if entry == "" {
continue
}
relative := strings.TrimPrefix(entry, rel+"/")
if relative == entry || !strings.HasSuffix(relative, ".md") {
continue
}
pages = append(pages, relative)
}
if len(pages) == 0 {
return nil, fmt.Errorf("git ls-files %s listed no Markdown", rel)
}
return pages, nil
}
// walkedPages is the gitless enumeration: every .md under the tree, tracked or
// not.
func walkedPages(sourceDir string) ([]string, error) {
var pages []string
err := filepath.WalkDir(sourceDir, func(filename string, entry fs.DirEntry, err error) error {
if err != nil {
return err
@@ -423,24 +517,13 @@ func readPages(sourceDir string) (map[string]string, error) {
if err != nil {
return err
}
relative = filepath.ToSlash(relative)
if !published(relative) {
return nil
}
body, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("read %s: %w", relative, err)
}
bodies[relative] = string(body)
pages = append(pages, filepath.ToSlash(relative))
return nil
})
if err != nil {
return nil, fmt.Errorf("walk %s: %w", docsDir, err)
}
if len(bodies) == 0 {
return nil, fmt.Errorf("no published pages under %s", docsDir)
}
return bodies, nil
return pages, nil
}
// setDocument pairs one set with the artifact generated for it.
@@ -455,7 +538,7 @@ type setDocument struct {
// link that crosses between them resolves to the base its target is served under.
func load(repoRoot string) ([]setDocument, error) {
sourceDir := filepath.Join(repoRoot, docsDir)
bodies, err := readPages(sourceDir)
bodies, err := readPages(repoRoot, sourceDir)
if err != nil {
return nil, err
}
+54
View File
@@ -2,6 +2,7 @@ package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -216,6 +217,59 @@ func TestCheckFailsOnAStaleArtifactAndLeavesTheTreeAlone(t *testing.T) {
}
}
// TestUntrackedPagesDoNotReachTheArtifact pins why the artifact is derived from
// the commit rather than from the working tree. docs:artifact:check runs in the
// gate and reads the sources from disk, so an untracked page under docs/ made
// the committed artifact look stale. The gate then demanded a regeneration that
// was already correct, and that regeneration would have committed a page no
// commit carries. It cost two sessions in one day: a migration branch, and an
// unrelated writer adding a PRD.
func TestUntrackedPagesDoNotReachTheArtifact(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "docs", "index.md"), "# Archie\n\nHello.\n")
writeFile(t, filepath.Join(root, "docs", "architecture", "policy.md"), "# Policy\n\nRules.\n")
gitIn(t, root, "init", "--quiet")
gitIn(t, root, "add", "docs/index.md", "docs/architecture/policy.md")
if err := write(root); err != nil {
t.Fatalf("write: %v", err)
}
// Untracked: no commit carries it, so the committed artifact is not required
// to contain it and check must not claim the artifact is stale.
writeFile(t, filepath.Join(root, "docs", "prds", "scratch.md"), "# Scratch\n\nNot committed.\n")
if err := check(root); err != nil {
t.Fatalf("check with an untracked page = %v, want it to pass", err)
}
// Staged: this commit is about to carry it, so the artifact must too.
gitIn(t, root, "add", "docs/prds/scratch.md")
if err := check(root); err == nil {
t.Fatal("check with a staged page = nil, want a failure: the artifact does not carry it")
}
if err := write(root); err != nil {
t.Fatalf("write: %v", err)
}
if err := check(root); err != nil {
t.Fatalf("check after regenerating for the staged page = %v, want it to pass", err)
}
}
// gitIn runs one git command in dir, failing loudly rather than skipping: task
// check already requires git for proto:lint, so a test that quietly passed
// without it would be asserting nothing.
func gitIn(t *testing.T, dir string, args ...string) {
t.Helper()
cmd := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...)
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=docsite", "GIT_AUTHOR_EMAIL=docsite@example.invalid",
"GIT_COMMITTER_NAME=docsite", "GIT_COMMITTER_EMAIL=docsite@example.invalid",
)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
}
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+1 -1
View File
@@ -1 +1 @@
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer theme{:root,:host{--font-sans:"Geist Variable", sans-serif;--color-black:#000;--spacing:.25rem;--container-xs:20rem;--container-sm:24remLine truncated
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer theme{:root,:host{--font-sans:"Geist Variable", sans-serif;--color-black:#000;--spacing:.25rem;--container-xs:20rem;--container-sm:24remLine truncated
+1 -1
View File
@@ -16,4 +16,4 @@ Defaulting to \`null\`.`),null)}function Tx(e){return Cx(e)&&!Number.isNaN(e)&&e
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:nT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>nT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=iT(c),u=e+1<n.length?iT(n[e+1]):null;if(l&&u&&aT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=iT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>nT(e)),rows:r.map(e=>e.map(e=>nT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:nT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:nT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function iT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function aT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var oT={class:`[overflow-wrap:anywhere]`},sT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},cT={class:`font-mono text-[0.85em]`},lT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},uT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},dT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},fT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},pT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},mT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},hT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},gT={key:8,class:`mb-2.5 last:mb-0`},_T=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>rT(t.text));return(e,t)=>(L(),R(`div`,oT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,sT,[B(`code`,cT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,lT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(eT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(eT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,uT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,dT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,fT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,pT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,mT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,gT,[V(eT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),vT={class:`truncate`},yT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,vT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),bT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},xT={class:`font-semibold text-foreground`},ST={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},CT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(yT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,bT,[V(A(Kd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,xT,O(n.value),1),r.value?(L(),R(`code`,ST,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),wT={key:0,class:`mb-2 grid gap-0.5 text-xs`},TT={key:2,class:`whitespace-pre-wrap`},ET=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,wT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(CT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(_T,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,TT,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),DT={class:`w-full self-center justify-self-center py-6 text-center`},OT={class:`grid gap-2`},kT=[`onClick`],AT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,DT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>cA?`${n.slice(0,cA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var uA=[`title`],dA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Dk(n.event)),a=G(()=>lA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?vO(n.event.at):`—`);return(e,t)=>(L(),z(A(aA),{class:D(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,uA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),fA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},pA=N({__name:`LiveActivityCard`,setup(e){let t=$T(),{activity:n,streamKind:r,streamState:i}=ad(ek());function a(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(uO),null,{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(pO),null,{default:j(()=>[...t[1]||=[H(`Last 50, newest first`,-1)]]),_:1}),V(A(dO),null,{default:j(()=>[V(A(XD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(fO),null,{default:j(()=>[B(`div`,fA,[V(A(rA),null,{default:j(()=>[V(A(sA),null,{default:j(()=>[V(A(aA),null,{default:j(()=>[V(A(oA),null,{default:j(()=>[...t[2]||=[H(`Event`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[3]||=[H(`Task`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[4]||=[H(`Detail`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[5]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(iA),null,{default:j(()=>[A(n).length?(L(!0),R(I,{key:1},P(A(n),(e,t)=>(L(),z(dA,{key:t,event:e,onOpen:a},null,8,[`event`]))),128)):(L(),z(A(aA),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(HD),null,{default:j(()=>[V(A(GD),null,{default:j(()=>[V(A(JD),null,{default:j(()=>[...t[6]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1}))]),_:1})]),_:1})])]),_:1})]),_:1}))}}),mA=N({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=QS(t,`class`);return(e,r)=>(L(),z(A(Ex),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Dx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`transform: translateX(-${100-(t.modelValue??0)}%);`)},null,8,[`style`])]),_:1},16,[`class`]))}}),hA=`archie.setup-complete.dismissed.v1`;function gA(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(hA),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function _A(e=globalThis.localStorage){e?.setItem?.(hA,`1`)}var vA={class:`text-lg font-semibold text-link`},yA={class:`flex flex-col gap-3`},bA={key:0,class:`mt-0.5 text-xs text-fg-subtle`},xA=N({__name:`SetupPanel`,setup(e){let t=k(gA(bk.value));M(bk,()=>{t.value=gA(bk.value)});let n=G(()=>bk.value?.steps??[]),r=G(()=>{let e=n.value.length;return e?Math.round((e-t.value.remaining.length)/e*100):0});function i(){_A(),t.value=gA(bk.value)}return(e,a)=>t.value.kind===`incomplete`?(L(),z(A(uO),{key:0},{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...a[0]||=[H(`Finish setting up`,-1)]]),_:1}),V(A(pO),null,{default:j(()=>[...a[1]||=[H(`Archie needs these before it can work on its own.`,-1)]]),_:1}),V(A(dO),null,{default:j(()=>[B(`span`,vA,O(r.value)+`%`,1)]),_:1})]),_:1}),V(A(fO),null,{default:j(()=>[V(A(mA),{"model-value":r.value,class:`mb-4`},null,8,[`model-value`]),B(`ul`,yA,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(`li`,{key:t,class:`flex items-start gap-3`},[B(`span`,{class:D([`mt-px grid size-[18px] flex-none place-items-center rounded-full border-[1.5px] border-border-strong text-xs text-fg-subtle`,e.done?`border-transparent bg-ok-soft text-ok`:``])},[e.done?(L(),z(A(bd),{key:0,class:`size-3`})):U(``,!0)],2),B(`div`,null,[B(`div`,{class:D([`text-sm`,e.done?`text-fg-muted line-through`:``])},O(e.title),3),e.detail?(L(),R(`div`,bA,O(e.detail),1)):U(``,!0)])]))),128))])]),_:1})]),_:1})):t.value.kind===`complete`?(L(),z(A(uO),{key:1},{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...a[2]||=[H(`Setup complete`Line truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>cA?`${n.slice(0,cA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var uA=[`title`],dA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Dk(n.event)),a=G(()=>lA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?vO(n.event.at):`—`);return(e,t)=>(L(),z(A(aA),{class:D(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,uA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function fA(e,t){return`${e}:${t??0}`}function pA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=fA(lA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var mA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},hA=[`aria-expanded`,`aria-label`,`onClick`],gA=[`title`],_A=N({__name:`LiveActivityCard`,setup(e){let t=$T(),{activity:n,streamKind:r,streamState:i}=ad(ek()),a=nn(new Set),o=G(()=>pA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return lA(e.representative)}function u(e){return e.representative.at?vO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(uO),null,{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(pO),null,{default:j(()=>[...t[1]||=[H(`Last 50, newest first`,-1)]]),_:1}),V(A(dO),null,{default:j(()=>[V(A(XD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(fO),null,{default:j(()=>[B(`div`,mA,[V(A(rA),null,{default:j(()=>[V(A(sA),null,{default:j(()=>[V(A(aA),null,{default:j(()=>[V(A(oA),null,{default:j(()=>[...t[2]||=[H(`Event`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[3]||=[H(`Task`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[4]||=[H(`Detail`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[5]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(iA),null,{default:j(()=>[A(n).length?U(``,!0):(L(),z(A(aA),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(HD),null,{default:j(()=>[V(A(GD),null,{default:j(()=>[V(A(JD),null,{default:j(()=>[...t[6]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),A(n).length?(L(!0),R(I,{key:1},P(o.value,e=>(L(),R(I,{key:e.key},[e.count===1?(L(),z(dA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(L(),R(I,{key:1},[V(A(aA),{class:D(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[B(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:lu(t=>s(e.key),[`stop`])},[c(e)?(L(),z(A(xd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(L(),z(A(Cd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),H(` `+O(e.label)+` `,1),V(A(XD),{variant:`idle`},{default:j(()=>[H(`×`+O(e.count),1)]),_:2},1024)],8,hA)]),_:2},1024),V(A($),{class:`font-mono`},{default:j(()=>[H(O(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},O(l(e).text),9,gA)]),_:2},1024),V(A($),null,{default:j(()=>[H(O(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(L(!0),R(I,{key:0},P(e.events,(t,n)=>(L(),z(dA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):U(``,!0)],64))],64))),128)):U(``,!0)]),_:1})]),_:1})])]),_:1})]),_:1}))}}),vA=N({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=QS(t,`class`);return(e,r)=>(L(),z(A(Ex),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Dx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`transform:Line truncated
+84 -3
View File
@@ -1,19 +1,54 @@
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { computed, reactive } from "vue";
import { useRouter } from "vue-router";
import { ChevronDown, ChevronRight } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ago } from "@/lib/format";
import { useLiveUpdatesStore } from "@/stores/live-updates";
import ActivityRow from "./ActivityRow.vue";
import { activityDetail } from "./activity-detail";
import { groupActivity, type ActivityGroup } from "./activity-group";
/** The last 50 events, newest first, with the stream's own state on the card. */
/**
* The last 50 events, newest first, with the stream's own state on the card.
* Runs of consecutive same-kind same-task events (the daemon's background
* telemetry) collapse into one group row carrying an ×N badge; expanding one
* reveals its events. The grouping lives in activity-group.ts and is tested
* there; this card only renders it.
*/
const router = useRouter();
const { activity, streamKind, streamState } = storeToRefs(useLiveUpdatesStore());
// Expansion is keyed on label:taskID, so a live run stays open as its events
// arrive, and a collapsed group re-collapses only when the run breaks.
const expanded = reactive(new Set<string>());
const groups = computed(() => groupActivity(activity.value));
function toggle(key: string) {
if (expanded.has(key)) expanded.delete(key);
else expanded.add(key);
}
function isOpen(group: ActivityGroup): boolean {
return expanded.has(group.key);
}
// The collapsed group row shows what its newest event would have shown, so
// expanding and collapsing moves no information.
function groupDetail(group: ActivityGroup) {
return activityDetail(group.representative);
}
function groupWhen(group: ActivityGroup) {
return group.representative.at ? ago(group.representative.at) : "\u2014";
}
function openTask(taskID: number) {
void router.push(`/tasks?task=${encodeURIComponent(taskID)}`);
}
@@ -56,10 +91,56 @@ function openTask(taskID: number) {
</Empty>
</TableCell>
</TableRow>
<ActivityRow v-for="(event, i) in activity" v-else :key="i" :event="event" @open="openTask" />
<template v-if="activity.length">
<template v-for="group in groups" :key="group.key">
<!-- A singleton is exactly the row the raw feed would show. -->
<ActivityRow v-if="group.count === 1" :event="group.representative" @open="openTask" />
<template v-else>
<!--
The group row keeps ActivityRow's link contract: when its
events resolve to a task, the row itself opens the task,
with the same focusable role="link" behaviour. The
disclosure button is a stop-propagated control inside the
first cell, so it never fights the row-level link.
-->
<TableRow
:class="group.taskID > 0 ? 'cursor-pointer' : ''"
:role="group.taskID > 0 ? 'link' : undefined"
:tabindex="group.taskID > 0 ? 0 : undefined"
:title="group.taskID > 0 ? 'Open task details' : undefined"
@click="group.taskID > 0 && openTask(group.taskID)"
@keydown.enter.prevent="group.taskID > 0 && openTask(group.taskID)"
@keydown.space.prevent="group.taskID > 0 && openTask(group.taskID)"
>
<TableCell class="font-medium">
<button
type="button"
class="inline-flex items-center gap-1 rounded hover:opacity-80"
:aria-expanded="isOpen(group)"
:aria-label="`${isOpen(group) ? 'Hide' : 'Show'} ${group.count} ${group.label} events`"
@click.stop="toggle(group.key)"
>
<ChevronDown v-if="isOpen(group)" class="size-3.5 shrink-0 text-fg-subtle" />
<ChevronRight v-else class="size-3.5 shrink-0 text-fg-subtle" />
{{ group.label }}
<Badge variant="idle">×{{ group.count }}</Badge>
</button>
</TableCell>
<TableCell class="font-mono">{{ group.taskID > 0 ? `#${group.taskID}` : "—" }}</TableCell>
<TableCell class="w-[55%] max-w-0">
<span class="block truncate" :title="groupDetail(group).truncated ? groupDetail(group).full : undefined">{{ groupDetail(group).text }}</span>
</TableCell>
<TableCell>{{ groupWhen(group) }}</TableCell>
</TableRow>
<template v-if="isOpen(group)">
<ActivityRow v-for="(event, i) in group.events" :key="`${group.key}:${i}`" :event="event" @open="openTask" />
</template>
</template>
</template>
</template>
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</template>
</template>
+61
View File
@@ -0,0 +1,61 @@
import type { ActivityEvent } from "./state";
import { activityDetail } from "./activity-detail.ts";
/**
* The live activity feed's grouping projection.
*
* The daemon emits high-frequency background telemetry that arrives as dozens
* of same-shape rows an hour — often as an interleave of kinds (a curator
* cycle emits curator_run, session-memory and curator_action events that all
* carry the same payload). Printed raw, the table stops being scannable and
* real milestones drown.
*
* The rule: a *run of consecutive* events sharing one task and one rendered
* detail collapses into a single group row. Kind is deliberately not part of
* the key — an interleave of kinds over one payload is one cycle of noise,
* not three events — so anything else stays on its own line, and a milestone
* is never merged with an event carrying different information. The grouping
* is consecutive, not global, so interleaved events keep their order and
* nothing is reordered under the operator.
*
* This is a pure view projection over the store's raw stream: the store keeps
* every event, and this module decides only how the feed presents them.
*/
/** One displayed row: either a single event (count 1) or a collapsed run. */
export interface ActivityGroup {
/** Stable identity of the run: the grouping key of its first event. */
key: string;
/** The resolved label the row shows, matching the Event column's fallback. */
label: string;
/** The task the group's events resolve to, or 0 for none. */
taskID: number;
/** How many events the group carries; 1 means an uncollapsed row. */
count: number;
/** The newest event of the run -- what the row shows while collapsed. */
representative: ActivityEvent;
/** Every event in the run, newest first. */
events: ActivityEvent[];
}
export function groupKey(detail: string, taskID: number | undefined): string {
return `${detail}:${taskID ?? 0}`;
}
export function groupActivity(events: ActivityEvent[]): ActivityGroup[] {
const groups: ActivityGroup[] = [];
for (const event of events) {
const label = event.kind || event.type || "event";
const taskID = Number(event.task_id) || 0;
const key = groupKey(activityDetail(event).text, taskID);
const last = groups[groups.length - 1];
if (last && last.key === key) {
last.count += 1;
last.events.push(event);
continue;
}
groups.push({ key, label, taskID, count: 1, representative: event, events: [event] });
}
return groups;
}
+12 -3
View File
@@ -147,7 +147,11 @@
--warn-soft: rgba(240, 182, 92, 0.16);
--danger: #F87A88;
--danger-soft: rgba(248, 122, 136, 0.16);
--info: #A76BF5;
/* #B08BF8, not the ring's #A76BF5: info doubles as badge text on
info-soft and as the log-level label, and #A76BF5 on info-soft over a
card is 4.29:1 -- under AA. On every surface it lands on (canvas, card,
glass, both softs) #B08BF8 clears 5.5:1. */
--info: #B08BF8;
--info-soft: rgba(167, 107, 245, 0.16);
--idle: #A79BB8;
--idle-soft: rgba(167, 155, 184, 0.16);
@@ -207,7 +211,9 @@
--ring: #8B5FBF;
--fg-muted: #635B6B;
--fg-subtle: #6E6577;
/* #675E6F, not #6E6577: subtle text also lands on the wash-composited
canvas, where #6E6577 is 4.44:1. */
--fg-subtle: #675E6F;
--ok: #0C7548;
--ok-soft: rgba(12, 117, 72, 0.10);
@@ -215,7 +221,10 @@
--warn-soft: rgba(138, 90, 18, 0.10);
--danger: #BE2C43;
--danger-soft: rgba(190, 44, 67, 0.10);
--info: #8B5FBF;
/* #6F47A6, not the ring's #8B5FBF: on the cream canvas #8B5FBF is
4.11:1 and 3.58:1 on info-soft. #6F47A6 clears 5.1:1 on every surface
info text lands on, light theme included. */
--info: #6F47A6;
--info-soft: rgba(139, 95, 191, 0.12);
--idle: #5A6270;
--idle-soft: rgba(90, 98, 112, 0.10);
+21 -1
View File
@@ -9,7 +9,7 @@ import PanelLoading from "./PanelLoading.vue";
import StageRow from "./StageRow.vue";
import { stageStatusMeta } from "./stage-rail";
import { useTaskRun } from "./use-task-run";
import type { AttemptsState } from "./task-run";
import type { AttemptsState, Stage } from "./task-run";
/**
* The per-attempt stage rail.
@@ -35,6 +35,24 @@ const attempt = computed(() => attempts.value.find((a) => Number(a.attempt) ===
const meta = computed(() => stageStatusMeta(attempt.value?.status));
const stages = computed(() => attempt.value?.stages || []);
/**
* Master-detail selection (docs/prds/task-run-master-detail.md): clicking a
* stage commands the inspector to the log tab with this stage's filter set.
* Clicking the selected stage clears the filter back to all stages. The
* selection is a command, not a binding: the operator can change the filter
* afterwards and the rail does not fight them. A stage with no name has
* nothing to filter on and is not selectable.
*/
function selectedStage(stage: Stage): boolean {
return run.tab === "log" && Boolean(stage.name) && run.filters.stage === stage.name;
}
function selectStage(stage: Stage): void {
if (!stage.name) return;
run.setFilters({ stage: selectedStage(stage) ? "" : stage.name, level: run.filters.level });
run.setTab("log");
}
/** An attempt's start is rendered as an absolute instant, never as "started 2
* days ago": on a still-running attempt a relative stamp reads as two days of
* work, which is exactly the elapsed-time claim the design forbids. */
@@ -81,6 +99,8 @@ const startedAt = computed(() => {
:stage="stage"
:attempt-number="attempt.attempt"
:events="run.events"
:selected="selectedStage(stage)"
@select="selectStage(stage)"
/>
</ol>
<Empty v-else>
+18 -4
View File
@@ -19,8 +19,11 @@ const props = defineProps<{
stage: Stage;
attemptNumber: number;
events: TaskEvent[] | null | undefined;
selected?: boolean;
}>();
const emit = defineEmits<{ select: [] }>();
const meta = computed(() => stageStatusMeta(props.stage.status));
const ran = computed(() => duration(props.stage.duration_ms));
const reports = computed(() => agentReports(props.events, props.attemptNumber, props.stage.name));
@@ -47,17 +50,28 @@ const nodeClass = computed(() =>
<template>
<li
class="relative grid grid-cols-[1.75rem_1fr] gap-2 pb-4 before:absolute before:top-4 before:bottom-0 before:left-[0.6875rem] before:w-px before:bg-border-strong last:before:hidden max-[700px]:grid-cols-1 max-[700px]:border-b max-[700px]:border-border max-[700px]:pb-3 max-[700px]:before:hidden"
:class="props.selected ? 'rounded-md bg-primary-soft' : ''"
>
<span :class="nodeClass" aria-hidden="true" class="max-[700px]:hidden" />
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<div class="min-w-0" :class="props.selected ? '-my-2 rounded-md py-2' : ''">
<!--
Selecting a stage commands the inspector to this stage's log (the
master-detail contract). The control is a real button so keyboard
activation works without the row carrying a second role.
-->
<button
type="button"
class="flex w-full flex-wrap items-center gap-2 rounded text-left"
:aria-pressed="props.selected ?? false"
@click="emit('select')"
>
<!-- A stage name is one unbroken token often enough that it has to be
allowed to break, or a long one pushes the status and duration off
the row. -->
<span class="min-w-0 font-mono font-medium break-words">{{ stage.name || "(unnamed stage)" }}</span>
<span class="min-w-0 font-mono font-medium break-words hover:underline" :class="props.selected ? 'text-primary' : ''">{{ stage.name || "(unnamed stage)" }}</span>
<Badge :variant="meta.kind">{{ meta.label }}</Badge>
<span class="text-xs text-fg-muted">{{ ran ? `ran for ${ran}` : "duration not recorded" }}</span>
</div>
</button>
<div
v-if="stage.error"
class="mt-2 rounded-sm border-l-[3px] border-danger bg-danger-soft px-3 py-2 text-sm break-words whitespace-pre-wrap text-fg-muted"
+28 -11
View File
@@ -12,6 +12,7 @@ import TaskHeader from "./TaskHeader.vue";
import TaskMetaBar from "./TaskMetaBar.vue";
import TaskNotes from "./TaskNotes.vue";
import TaskRunPanels from "./TaskRunPanels.vue";
import StageRail from "./StageRail.vue";
import { parseTaskId } from "./task-run";
import { provideTaskRun } from "./use-task-run";
@@ -24,11 +25,16 @@ import { provideTaskRun } from "./use-task-run";
* the query string, so every view of this page is a deep link that survives a
* reload -- /tasks/42?tab=changes&attempt=2.
*
* The page is a master-detail split pane (docs/prds/task-run-master-detail.md):
* the stage rail is the master and is always visible, the four context panels
* are the inspector and own the tab bar. Below the shell's 900px frame
* breakpoint the rail stacks above the inspector.
*
* This file composes the page and nothing else: the reads and the caches are
* use-task-run, the head, meta bar, notes, restart control, attempt selector,
* tab bar and panel area are each their own component. The router keys this
* component on the path (App.vue), so a different :id gets a fresh instance
* rather than diffing the last task's state in place.
* rail, tab bar and panel area are each their own component. The router keys
* this component on the path (App.vue), so a different :id gets a fresh
* instance rather than diffing the last task's state in place.
*/
const route = useRoute();
@@ -48,13 +54,24 @@ const run = provideTaskRun(taskId);
</TaskMetaBar>
<TaskNotes :id="rawId" />
<Card>
<CardContent>
<Tabs class="gap-4" :model-value="run.tab" @update:model-value="run.setTab">
<TabBar />
<TaskRunPanels :id="rawId" />
</Tabs>
</CardContent>
</Card>
<div class="grid items-start gap-4 min-[900px]:grid-cols-[20rem_minmax(0,1fr)]">
<!--
The master pane: the attempt's stage rail, always on screen. It owns
its own loading, failure and empty states, so the inspector never has
to speak for it.
-->
<aside aria-label="Run stages">
<StageRail :state="run.attempts" />
</aside>
<Card>
<CardContent>
<Tabs class="gap-4" :model-value="run.tab" @update:model-value="run.setTab">
<TabBar />
<TaskRunPanels :id="rawId" />
</Tabs>
</CardContent>
</Card>
</div>
</div>
</template>
+34 -1
View File
@@ -15,6 +15,7 @@ export interface Task {
pr_url?: string;
source?: string;
status?: string;
park_class?: string;
workflow?: string;
stage?: string;
attempt?: number;
@@ -51,6 +52,23 @@ const router = useRouter();
// knows renders with the right words and the right colour.
const label = computed(() => statusLabel(props.task.status ?? ""));
const kind = computed(() => statusKind(props.task.status ?? "") as StatusKind);
const parkClassLabels: Record<string, string> = {
needs_human: "needs you",
transient: "transient",
terminal: "terminal",
};
const parkClassLabel = computed(() => parkClassLabels[props.task.park_class ?? ""] ?? "");
const parkClassTitle = computed(() => {
switch (props.task.park_class) {
case "transient":
return "Environmental failure: a requeue can succeed";
case "terminal":
return "Retry cannot succeed: archive or re-create the work";
default:
return "An operator decision is needed";
}
});
const title = computed(() => props.task.title || "untitled task");
// Chat-sourced work has no forge issue behind it, so there is no page to open
@@ -129,7 +147,22 @@ function open() {
</RouterLink>
</TableCell>
<TableCell>
<Badge :variant="kind">{{ label }}</Badge>
<span class="inline-flex items-center gap-1">
<Badge :variant="kind">{{ label }}</Badge>
<!--
The park's class (taskstate.ParkClass), recorded at the park site:
it answers what kind of intervention this park needs, which the
bare Parked badge never could. A chip only when parked; a queued
or running task carries no class worth showing.
-->
<Badge
v-if="props.task.status === 'parked' && parkClassLabel"
variant="outline"
:title="parkClassTitle"
>
{{ parkClassLabel }}
</Badge>
</span>
</TableCell>
<TableCell class="text-fg-muted">{{ props.task.workflow || "—" }}</TableCell>
<TableCell class="text-fg-muted">{{ props.task.stage || "—" }}</TableCell>
+33 -39
View File
@@ -7,19 +7,18 @@ import ChangedFiles from "./ChangedFiles.vue";
import DebugView from "./DebugView.vue";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import StageRail from "./StageRail.vue";
import TaskLogs from "./TaskLogs.vue";
import { RUN_TABS } from "./task-run";
import { useTaskRun } from "./use-task-run";
/**
* The run page's panel area: one panel per tab, each reading the attempt the
* page has selected.
* The run page's inspector panels: one panel per tab, each reading the attempt
* the page has selected. The stage rail lives in the page's master pane and is
* not one of these tabs.
*
* The rail owns its own loading, failure and empty states. Every other panel is
* scoped to one attempt, and "no attempt" is a claim only a successful read of
* the run history can make -- a read still in flight is not a verdict either,
* and a failed read is reported as a failed read.
* Every panel is scoped to one attempt, and "no attempt" is a claim only a
* successful read of the run history can make -- a read still in flight is not
* a verdict either, and a failed read is reported as a failed read.
*/
const props = defineProps<{ id: string }>();
@@ -28,42 +27,37 @@ const run = useTaskRun();
<template>
<TabsContent v-for="tab in RUN_TABS" :key="tab.id" :value="tab.id">
<StageRail v-if="tab.id === 'stages'" :state="run.attempts" />
<PanelLoading v-if="run.attempts === undefined" label="Loading this task's attempts…" />
<template v-else>
<PanelLoading v-if="run.attempts === undefined" label="Loading this task's attempts…" />
<PanelError
v-else-if="run.attempts === null"
title="Could not load this task's attempts"
detail="The task's run history could not be read."
/>
<PanelError
v-else-if="run.attempts === null"
title="Could not load this task's attempts"
detail="The task's run history could not be read."
/>
<Empty v-else-if="run.attemptNumber == null">
<EmptyHeader>
<EmptyTitle>No attempt recorded</EmptyTitle>
</EmptyHeader>
</Empty>
<TaskLogs
v-else-if="tab.id === 'log'"
:state="run.logState"
:attempt="run.attemptNumber"
:stages="run.stageNames"
:filters="run.filters"
:task-id="props.id"
@filter="run.setFilters"
/>
<Empty v-else-if="run.attemptNumber == null">
<EmptyHeader>
<EmptyTitle>No attempt recorded</EmptyTitle>
</EmptyHeader>
</Empty>
<ChangedFiles v-else-if="tab.id === 'changes'" :state="run.changesState" :task="run.task" />
<TaskLogs
v-else-if="tab.id === 'log'"
:state="run.logState"
:attempt="run.attemptNumber"
:stages="run.stageNames"
:filters="run.filters"
:task-id="props.id"
@filter="run.setFilters"
/>
<AttemptConfig
v-else-if="tab.id === 'config'"
:events="run.events"
:attempt="run.attemptNumber"
/>
<ChangedFiles v-else-if="tab.id === 'changes'" :state="run.changesState" :task="run.task" />
<AttemptConfig
v-else-if="tab.id === 'config'"
:events="run.events"
:attempt="run.attemptNumber"
/>
<DebugView v-else-if="tab.id === 'debug'" :state="run.debugState" :attempt="run.attemptNumber" />
</template>
<DebugView v-else-if="tab.id === 'debug'" :state="run.debugState" :attempt="run.attemptNumber" />
</TabsContent>
</template>
+11 -1
View File
@@ -21,8 +21,12 @@ export interface TaskRunTab {
label: string;
}
/**
* The inspector's tabs. The stage rail is not one of them: it is the page's
* master pane, always visible, and selecting a stage commands the inspector
* to the log tab with that stage's filter set (docs/prds/task-run-master-detail.md).
*/
export const RUN_TABS: TaskRunTab[] = [
{ id: "stages", label: "Stages" },
{ id: "log", label: "Log" },
{ id: "changes", label: "Changed files" },
{ id: "config", label: "Configuration" },
@@ -31,6 +35,9 @@ export const RUN_TABS: TaskRunTab[] = [
const TAB_IDS = new Set(RUN_TABS.map((tab) => tab.id));
/** URL ids from before the split-pane layout that must keep resolving. */
const LEGACY_TAB_IDS = new Set(["stages"]);
/** The task record as the task list serves it. */
export interface TaskRecord {
id: number | string;
@@ -149,6 +156,9 @@ export function parseTaskId(raw: unknown): number | null {
export function initialTab(query: LocationQuery | undefined): string {
const requested = String(query?.tab ?? "");
// tab=stages named the rail before the split pane; the rail is now always
// visible, so the URL resolves to the inspector's first tab.
if (LEGACY_TAB_IDS.has(requested)) return "log";
return TAB_IDS.has(requested) ? requested : RUN_TABS[0].id;
}
+9
View File
@@ -297,6 +297,15 @@ export function provideTaskRun(id: ComputedRef<number | null>): TaskRun {
loadEvents();
});
// A stage filter is a command scoped to the attempt it was made on: the rail
// set it against that attempt's stage list. A different attempt presents a
// different list, so the stage filter resets on an attempt switch and the
// rail can never highlight a stage the operator did not select here. The
// level filter is attempt-agnostic and survives.
watch(attemptNumber, () => {
if (filters.value.stage) filters.value = { ...filters.value, stage: "" };
});
watch([tab, attemptNumber, filters, refreshToken], () => {
const attempt = attemptNumber.value;
if (attempt == null) return;
+101
View File
@@ -0,0 +1,101 @@
import assert from "node:assert/strict";
import test from "node:test";
const { groupActivity, groupKey } = await import("../src/dashboard/activity-group.ts");
import type { ActivityEvent } from "../src/dashboard/state.ts";
function ev(kind: string, taskID: number | undefined, detail: string, at = 1000): ActivityEvent {
return { kind, task_id: taskID, detail, at };
}
test("consecutive events sharing detail and task collapse into one group", () => {
const events = [
ev("session-memory", undefined, "cycle 9"),
ev("session-memory", undefined, "cycle 9"),
ev("session-memory", undefined, "cycle 9"),
];
const groups = groupActivity(events);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 3);
// The newest event (first in the feed) represents the group.
assert.equal(groups[0].representative.detail, "cycle 9");
assert.equal(groups[0].events.length, 3);
});
test("the same kind with different details does not collapse", () => {
const events = [
ev("stage_finished", 7, "build"),
ev("stage_finished", 7, "plan"),
];
const groups = groupActivity(events);
assert.equal(groups.length, 2);
});
test("a singleton stays a plain one-count group", () => {
const groups = groupActivity([ev("stage_finished", 7, "build")]);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 1);
assert.equal(groups[0].events.length, 1);
});
test("a different task breaks the run", () => {
const events = [
ev("runner_run", 7, "a"),
ev("runner_run", 9, "b"),
ev("runner_run", 7, "c"),
];
const groups = groupActivity(events);
assert.equal(groups.length, 3);
for (const group of groups) assert.equal(group.count, 1);
});
test("a different kind breaks the run when the detail differs", () => {
const events = [
ev("session-memory", undefined, "a"),
ev("runner_run", undefined, "b"),
ev("session-memory", undefined, "c"),
];
const groups = groupActivity(events);
assert.equal(groups.length, 3);
});
test("an interleave of kinds sharing one detail and task collapses", () => {
// A background cycle emits one event per internal step; the kinds differ
// but the cycle is one run of noise.
const events = [
ev("curator_action", undefined, "session-memory"),
ev("session-memory", undefined, "session-memory"),
ev("curator_run", undefined, "session-memory"),
ev("curator_action", undefined, "session-memory"),
];
const groups = groupActivity(events);
assert.equal(groups.length, 1);
assert.equal(groups[0].count, 4);
assert.equal(groups[0].label, "curator_action");
});
test("the same detail on a different task breaks the run", () => {
const events = [
ev("runner_run", 7, "building"),
ev("runner_run", 9, "building"),
];
const groups = groupActivity(events);
assert.equal(groups.length, 2);
});
test("a missing kind resolves to the same label an unset row shows", () => {
const events: ActivityEvent[] = [
{ detail: "a", at: 1000 },
{ detail: "a", at: 1001 },
];
const groups = groupActivity(events);
assert.equal(groups.length, 1);
assert.equal(groups[0].label, "event");
});
test("groupKey separates detail and task", () => {
assert.notEqual(groupKey("runner_run", 7), groupKey("runner_run", 9));
assert.equal(groupKey("runner_run", 7), groupKey("runner_run", 7));
assert.equal(groupKey("runner_run", 0), groupKey("runner_run", undefined));
});