Compare commits

...
7 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
30 changed files with 1320 additions and 657 deletions

No files matched your search

+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 }}
+26
View File
@@ -5,6 +5,32 @@ 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
+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{
+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.
+1
View File
@@ -4,6 +4,7 @@ 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)
+2
View File
@@ -51,6 +51,7 @@
"/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/",
@@ -119,6 +120,7 @@
"/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/",
+5
View File
@@ -1,4 +1,9 @@
[
{
"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",
+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"
File diff suppressed because it is too large. Load diff
@@ -37,6 +37,7 @@ 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"
@@ -123,6 +124,7 @@ 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)
@@ -408,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)
@@ -953,6 +965,7 @@ 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)
@@ -1112,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")
}
@@ -1601,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 {
@@ -2523,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,
+56 -48
View File
@@ -35,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"
)
@@ -1046,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)
@@ -1193,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
}
@@ -1242,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
@@ -1336,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.
@@ -1354,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
}
@@ -1407,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'
@@ -1420,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)
}
@@ -1474,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()
@@ -1489,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{
@@ -1506,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
}
@@ -1835,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
@@ -1842,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 {
+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,6 +32,7 @@ import (
// Consumers depend on TaskStore, never on a concrete type.
type TaskStore interface {
TaskLifecycle
TaskParker
TaskEvents
TaskQueries
TaskArchiver
@@ -54,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.
+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)
+11
View File
@@ -100,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.
@@ -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 {
@@ -291,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 {
@@ -69,6 +69,8 @@ func taskProto(t *task.Task) *pb.Task { //nolint:dupl // mirror-image field-by-f
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,
@@ -90,6 +92,8 @@ func taskValue(t *pb.Task) *task.Task { //nolint:dupl // see taskProto above
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,
+111
View File
@@ -107,3 +107,114 @@ func TestUpdateReviewPayloadAppendsOnlyWhileARemediationIsQueued(t *testing.T) {
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)
}
}
+60 -12
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 {
@@ -102,6 +103,8 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
}{
{"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 ''`},
@@ -295,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 '',
@@ -381,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)
}
@@ -423,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) {
@@ -440,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
@@ -459,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) {
@@ -488,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
}
@@ -512,17 +520,57 @@ 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
}
@@ -541,7 +589,7 @@ func (s *Store) BeginRemediation(ctx context.Context, taskID int64, payload stri
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
UPDATE tasks SET status=?, workflow=?, stage='', park_reason='', review_payload=?,
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 {
@@ -616,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) {
@@ -632,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)
@@ -652,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) {
@@ -678,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
@@ -714,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
+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)
}
})
}
}
+19
View File
@@ -36,6 +36,7 @@ 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
@@ -254,6 +255,16 @@ message Task {
// 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
@@ -420,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; }
+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`]))}});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
`).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
+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>